diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..c66ad556 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,154 @@ +#/ +# @license Apache-2.0 +# +# Copyright (c) 2017 The Stdlib Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +#/ + +# EditorConfig configuration file (see ). + +# Indicate that this file is a root-level configuration file: +root = true + +# Set properties for all files: +[*] +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +# Set properties for JavaScript files: +[*.js] +indent_style = tab + +# Set properties for TypeScript files: +[*.ts] +indent_style = tab + +# Set properties for Python files: +[*.py] +indent_style = space +indent_size = 4 + +# Set properties for Julia files: +[*.jl] +indent_style = tab + +# Set properties for R files: +[*.R] +indent_style = tab + +# Set properties for C files: +[*.c] +indent_style = tab + +# Set properties for C header files: +[*.h] +indent_style = tab + +# Set properties for C++ files: +[*.cpp] +indent_style = tab + +# Set properties for C++ header files: +[*.hpp] +indent_style = tab + +# Set properties for Fortran files: +[*.f] +indent_style = space +indent_size = 2 +insert_final_newline = false + +# Set properties for shell files: +[*.sh] +indent_style = tab + +# Set properties for AWK files: +[*.awk] +indent_style = tab + +# Set properties for HTML files: +[*.html] +indent_style = tab +tab_width = 2 + +# Set properties for CSS files: +[*.css] +indent_style = tab + +# Set properties for Makefiles: +[Makefile] +indent_style = tab + +[*.mk] +indent_style = tab + +# Set properties for Markdown files: +[*.md] +indent_style = space +indent_size = 4 +trim_trailing_whitespace = false + +# Set properties for `usage.txt` files: +[usage.txt] +indent_style = space +indent_size = 2 + +# Set properties for `repl.txt` files: +[repl.txt] +indent_style = space +indent_size = 4 + +# Set properties for `package.json` files: +[package.json] +indent_style = space +indent_size = 2 + +# Set properties for `datapackage.json` files: +[datapackage.json] +indent_style = space +indent_size = 2 + +# Set properties for `tslint.json` files: +[tslint.json] +indent_style = space +indent_size = 2 + +# Set properties for `tsconfig.json` files: +[tsconfig.json] +indent_style = space +indent_size = 2 + +# Set properties for LaTeX files: +[*.tex] +indent_style = tab + +# Set properties for LaTeX Bibliography files: +[*.bib] +indent_style = tab + +# Set properties for YAML files: +[*.yml] +indent_style = space +indent_size = 2 + +# Set properties for GYP files: +[binding.gyp] +indent_style = space +indent_size = 2 + +[*.gypi] +indent_style = space +indent_size = 2 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..7212d812 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,33 @@ +#/ +# @license Apache-2.0 +# +# Copyright (c) 2017 The Stdlib Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +#/ + +# Configuration file which assigns attributes to pathnames. +# +# [1]: https://git-scm.com/docs/gitattributes + +# Automatically normalize the line endings of any committed text files: +* text=auto + +# Override what is considered "vendored" by GitHub's linguist: +/deps/** linguist-vendored=false +/lib/node_modules/** linguist-vendored=false linguist-generated=false +test/fixtures/** linguist-vendored=false +tools/** linguist-vendored=false + +# Override what is considered "documentation" by GitHub's linguist: +examples/** linguist-documentation=false diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..19409124 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,7 @@ + + +We are excited about your pull request, but unfortunately we are not accepting pull requests against this repository, as all development happens on the [main project repository](https://github.com/stdlib-js/stdlib). We kindly request that you submit this pull request against the [respective directory](https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/array) of the main repository where we’ll review and provide feedback. + +If this is your first stdlib contribution, be sure to read the [contributing guide](https://github.com/stdlib-js/stdlib/blob/develop/CONTRIBUTING.md) which provides guidelines and instructions for submitting contributions. You may also consult the [development guide](https://github.com/stdlib-js/stdlib/blob/develop/docs/development.md) for help on developing stdlib. + +We look forward to receiving your contribution! :smiley: \ No newline at end of file diff --git a/.github/workflows/close_pull_requests.yml b/.github/workflows/close_pull_requests.yml new file mode 100644 index 00000000..8237e359 --- /dev/null +++ b/.github/workflows/close_pull_requests.yml @@ -0,0 +1,23 @@ +name: Close Pull Requests + +on: + pull_request_target: + types: [opened] + +jobs: + run: + runs-on: ubuntu-latest + steps: + - uses: superbrothers/close-pull-request@v3 + with: + comment: | + Thank you for submitting a pull request. :raised_hands: + + We greatly appreciate your willingness to submit a contribution. However, we are not accepting pull requests against this repository, as all development happens on the [main project repository](https://github.com/stdlib-js/stdlib). + + We kindly request that you submit this pull request against the [respective directory](https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/array) of the main repository where we’ll review and provide feedback. If this is your first stdlib contribution, be sure to read the [contributing guide](https://github.com/stdlib-js/stdlib/blob/develop/CONTRIBUTING.md) which provides guidelines and instructions for submitting contributions. + + Thank you again, and we look forward to receiving your contribution! :smiley: + + Best, + The stdlib team \ No newline at end of file diff --git a/.github/workflows/examples.yml b/.github/workflows/examples.yml new file mode 100644 index 00000000..7668c70a --- /dev/null +++ b/.github/workflows/examples.yml @@ -0,0 +1,19 @@ +name: examples + +on: + workflow_dispatch: + +jobs: + examples: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-node@v1 + with: + node-version: 14 + - name: Install production and development dependencies + run: | + npm install + - name: Run examples + run: | + npm run examples \ No newline at end of file diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 00000000..a5ece1cf --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,34 @@ +name: Publish Package + +on: push + +jobs: + publish: + runs-on: ubuntu-latest + env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-node@v1 + with: + node-version: 14 + - name: Increment version + run: | + git config --local user.email "noreply@stdlib.io" + git config --local user.name "stdlib-bot" + npm version prerelease --preid=alpha + - name: Publish package to npm + uses: JS-DevTools/npm-publish@v1 + with: + token: ${{ secrets.NPM_TOKEN }} + access: public + - name: Push changes + run: | + git push origin main + git push --tags + - uses: act10ns/slack@v1 + with: + status: ${{ job.status }} + steps: ${{ toJson(steps) }} + channel: '#npm-ci' + if: failure() \ No newline at end of file diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 00000000..72b66f4e --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,29 @@ +name: build + +on: + workflow_dispatch: + +jobs: + test: + runs-on: ubuntu-latest + env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-node@v1 + with: + node-version: 14 + - name: Install production and development dependencies + id: install + run: | + npm install + - name: Run tests + id: tests + run: | + npm test + - uses: act10ns/slack@v1 + with: + status: ${{ job.status }} + steps: ${{ toJson(steps) }} + channel: '#npm-ci' + if: failure() \ No newline at end of file diff --git a/.github/workflows/test_coverage.yml b/.github/workflows/test_coverage.yml new file mode 100644 index 00000000..debbfd56 --- /dev/null +++ b/.github/workflows/test_coverage.yml @@ -0,0 +1,24 @@ +name: coverage + +on: + workflow_dispatch: + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-node@v1 + with: + node-version: 14 + - name: Install production and development dependencies + run: | + npm install + - name: Calculate test coverage + run: | + npm run test-cov + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v1 + with: + directory: reports/coverage + flags: unittests \ No newline at end of file diff --git a/.github/workflows/test_install.yml b/.github/workflows/test_install.yml new file mode 100644 index 00000000..039afb6e --- /dev/null +++ b/.github/workflows/test_install.yml @@ -0,0 +1,27 @@ +name: Test Installing Dependencies + +on: + workflow_run: + workflows: ["Publish Package"] + types: [completed] + +jobs: + on-success: + runs-on: ubuntu-latest + env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} + if: ${{ github.event.workflow_run.conclusion == 'success' }} + steps: + - uses: actions/checkout@v1 + - uses: actions/setup-node@v1 + with: + node-version: 14 + - name: Install production dependencies via npm + run: | + npm install --only=prod + - uses: act10ns/slack@v1 + with: + status: ${{ job.status }} + steps: ${{ toJson(steps) }} + channel: '#npm-ci' + if: failure() \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..1475963a --- /dev/null +++ b/.gitignore @@ -0,0 +1,181 @@ +#/ +# @license Apache-2.0 +# +# Copyright (c) 2017 The Stdlib Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +#/ + +# Files # +######### +.postinstall.json + +# Directories # +############### +build/ +downloads/ +reports/ +tmp/ + +# Compiled source # +################### +*.com +*.class +*.dll +*.o +*.so +*.slo +*.lo +*.obj +*.dylib +*.lai +*.la +*.a +*.lib +*.ko +*.elf +*.node + +# Precompiled headers # +####################### +*.gch +*.pch + +# Executables # +############### +*.exe +*.out +*.app + +# Packages # +############ +# It is better to unpack these files and commit the raw source +# git has its own built in compression methods +*.7z +*.dmg +*.gz +*.iso +*.jar +*.rar +*.tar +*.zip + +# Make an exception for compressed distributable files: +!dist/*.gz + +# Logs and databases # +###################### +*.log +*.sql +*.sqlite + +# OS generated files # +###################### +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +Icon? +ehthumbs.db +Thumbs.db +Desktop.ini + +# Temporary files # +################### +*~ + +# Node.js # +########### +/node_modules/ +lib/node_modules/**/node_modules/ +docs/**/node_modules/ +pids +*.pid +*.seed + +# Typescript # +############## +*.tsbuildinfo +lib/node_modules/**/tsconfig.json +lib/node_modules/**/tslint.json + +# Matlab # +########## +*.asv +*.mex* + +# Fortran # +########### +*.mod + +# R # +##### +.Rhistory +.Rapp.history +.Rproj.user/ + +# Python # +########## +__pycache__/ +*.py[cod] +*$py.class +*.egg-info/ + +# TeX # +####### +*.aux +*.lof +*.log +*.lot +*.fls +*.out +*.toc +*.dvi +*-converted-to.* +*.bbl +*.bcf +*.blg +*-blx.aux +*-blx.bib +*.brf +*.run.xml +*.fdb_latexmk +*.synctex +*.synctex.gz +*.synctex.gz(busy) +*.pdfsync +*.alg +*.loa +acs-*.bib +*.thm +*.nav +*.snm +*.vrb +*.acn +*.acr +*.glg +*.glo +*.gls +*-concordance.tex +*.tikz +*-tikzDictionary +*.idx +*.ilg +*.ind +*.ist + +# Visual Studio # +################# +.vscode/ +jsconfig.json diff --git a/.npmignore b/.npmignore new file mode 100644 index 00000000..f4ed12c0 --- /dev/null +++ b/.npmignore @@ -0,0 +1,229 @@ +#/ +# @license Apache-2.0 +# +# Copyright (c) 2017 The Stdlib Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +#/ + +# Files # +######### +CODE_OF_CONDUCT.md +CONTRIBUTING.md +CONTRIBUTORS +TODO.md +ROADMAP.md +.postinstall.json + +# Directories # +############### +.circleci/ +.github/ +**/benchmark/ +**/build/ +**/examples/ +reports/ +support/ +**/tmp/ +workshops/ + +# Ignore test directories, except for testing dependency installation: +**/test/ +!/deps/test/ + +# Ignore top-level tools directory, except for scripts: +/tools/* +!/tools/scripts/ + +# Only top-level directories: +/etc/ +/docs/ + +# Compiled source # +################### +*.com +*.class +*.dll +*.o +*.so +*.slo +*.lo +*.obj +*.dylib +*.lai +*.la +*.a +*.lib +*.ko +*.elf +*.node + +# Precompiled headers # +####################### +*.gch +*.pch + +# Executables # +############### +*.exe +*.out +*.app + +# Packages # +############ +*.7z +*.dmg +*.gz +*.iso +*.jar +*.rar +*.tar +*.zip + +# Make an exception for compressed distributable files: +!dist/*.gz + +# Logs and databases # +###################### +*.log +*.sql +*.sqlite + +# OS generated files # +###################### +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +Icon? +ehthumbs.db +Thumbs.db +Desktop.ini + +# Temporary files # +################### +*~ + +# Node.js # +########### +.npmignore + +# Only top-level node_modules: +/node_modules/ + +# TypeScript # +############## +tsconfig.json +tslint.json +*.tsbuildinfo + +# Matlab # +########## +*.asv +*.mex* + +# Fortran # +########### +*.mod + +# R # +##### +.Rhistory +.Rapp.history +.Rproj.user/ + +# Python # +########## +__pycache__/ +*.py[cod] +*$py.class +*.egg-info/ +.ipynb_checkpoints +setup.cfg +setup.py + +# TeX # +####### +*.aux +*.lof +*.log +*.lot +*.fls +*.out +*.toc +*.dvi +*-converted-to.* +*.bbl +*.bcf +*.blg +*-blx.aux +*-blx.bib +*.brf +*.run.xml +*.fdb_latexmk +*.synctex +*.synctex.gz +*.synctex.gz(busy) +*.pdfsync +*.alg +*.loa +acs-*.bib +*.thm +*.nav +*.snm +*.vrb +*.acn +*.acr +*.glg +*.glo +*.gls +*-concordance.tex +*.tikz +*-tikzDictionary +*.idx +*.ilg +*.ind +*.ist + +# Git # +####### +.git* +.mailmap + +# Visual Studio # +################# +.vscode/ +jsconfig.json + +# Utilities # +############# +.jshintrc +.jshintignore +.eslintrc* +.eslintignore + +.pylintrc +.pycodestyle +.pydocstyle + +.travis.yml +circle.yml +appveyor.yml +azure-pipelines.yml + +.editorconfig +.codeclimate.yml +.codecov.yml + +.rtlintrc diff --git a/.npmrc b/.npmrc new file mode 100644 index 00000000..36f5bef4 --- /dev/null +++ b/.npmrc @@ -0,0 +1,28 @@ +#/ +# @license Apache-2.0 +# +# Copyright (c) 2017 The Stdlib Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +#/ + +# Configuration for [npm][1]. +# +# [1]: https://docs.npmjs.com/files/npmrc + +# Disable the creation of a lock file: +package-lock = false +shrinkwrap = false + +# Disable automatically "saving" dependencies on install: +save = false diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..abd0ae4e --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,3 @@ +# Code of Conduct + +stdlib expects community participants to adhere to the project Code of Conduct. The [full text](https://github.com/stdlib-js/stdlib/blob/develop/CODE_OF_CONDUCT.md) is available in the main project repository. \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..8b60dead --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,3 @@ +# Contribution Guidelines + +Woot woot! If you are new to stdlib, welcome! And thanks for your interest! Guidelines for how to contribute to the project are [available](https://github.com/stdlib-js/stdlib/blob/develop/CONTRIBUTING.md) in the main project repository. \ No newline at end of file diff --git a/CONTRIBUTORS b/CONTRIBUTORS new file mode 100644 index 00000000..da469e5a --- /dev/null +++ b/CONTRIBUTORS @@ -0,0 +1,24 @@ +# This file is generated by tools/scripts/update_contributors. +# +# Contributors listed in alphabetical order. + +Athan Reines +Brendan Graetz +Bruno Fenzl +Christopher Dambamuromo +Dominik Moritz +Frank Kovacs +James +Jithin KS +Joey Reed +Joris Labie +Justin Dennison +Marcus +Matt Cochrane +Milan Raj +Ognjen Jevremović +Philipp Burckhardt +Ricky Reusser +Ryan Seal +Shraddheya Shendre +rei2hu diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..fcc99346 --- /dev/null +++ b/LICENSE @@ -0,0 +1,481 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + + +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by this +license (the "Software") to use, reproduce, display, distribute, execute, and +transmit the Software, and to prepare derivative works of the Software, and to +permit third-parties to whom the Software is furnished to do so, all subject to +the following: + +The copyright notices in the Software and this entire statement, including the +above license grant, this restriction and the following disclaimer, must be +included in all copies of the Software, in whole or in part, and all derivative +works of the Software, unless such copies or derivative works are solely in the +form of machine-executable object code generated by a source language processor. + +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, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE +COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES +OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF +OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +DEPENDENCIES + +The library links against the following external libraries, which have their own +licenses: + +* OpenBLAS + +Copyright (c) 2011-2014, The OpenBLAS Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + 3. Neither the name of the OpenBLAS project nor the names of + its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +* Electron + +Copyright (c) 2013-2017 GitHub Inc. + +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. + + +* Boost + +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +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, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +* Cephes + +Copyright (c) 1984-2000 Stephen L. Moshier + +Some software in this archive may be from the book _Methods and Programs for +Mathematical Functions_ (Prentice-Hall or Simon & Schuster International, 1989) +or from the Cephes Mathematical Library, a commercial product. In either event, +it is copyrighted by the author. What you see here may be used freely but it +comes with no support or guarantee. + +Stephen L. Moshier +moshier@na-net.ornl.gov + + + +ATTRIBUTION + +The library contains implementations from the following external libraries, +which have their own licenses: + +* FreeBSD + +Copyright (C) 1993-2004 by Sun Microsystems, Inc. All rights reserved. + +Developed at SunPro, a Sun Microsystems, Inc. business. +Permission to use, copy, modify, and distribute this +software is freely granted, provided that this notice +is preserved. + + +* FDLIBM + +Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved. + +Developed at SunPro, a Sun Microsystems, Inc. business. +Permission to use, copy, modify, and distribute this +software is freely granted, provided that this notice +is preserved. + + +* Go + +Copyright (c) 2009 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +* SLATEC Common Mathematical Library + +Public domain. + + +* ESLint + +Copyright JS Foundation and other contributors, https://js.foundation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +* StatsFuns.jl + +Copyright (c) 2015: Dahua Lin. + +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. + + +* SpecialFunctions.jl + +The MIT License (MIT) + +Copyright (c) 2017 Jeff Bezanson, Stefan Karpinski, Viral B. Shah, and others: + +https://github.com/JuliaMath/SpecialFunctions.jl/graphs/contributors + +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. + + +* MT19937 + +Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. The names of its contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/NOTICE b/NOTICE new file mode 100644 index 00000000..f5374f67 --- /dev/null +++ b/NOTICE @@ -0,0 +1 @@ +Copyright (c) 2016-2021 The Stdlib Authors. diff --git a/README.md b/README.md new file mode 100644 index 00000000..7d752575 --- /dev/null +++ b/README.md @@ -0,0 +1,304 @@ + + +# Arrays + +[![NPM version][npm-image]][npm-url] [![Build Status][test-image]][test-url] [![Coverage Status][coverage-image]][coverage-url] [![dependencies][dependencies-image]][dependencies-url] + +> Arrays. + +
+ +## Installation + +```bash +npm install @stdlib/array +``` + +
+ +
+ +## Usage + +```javascript +var ns = require( '@stdlib/array' ); +``` + +#### ns + +Arrays. + +```javascript +var o = ns; +// returns {...} +``` + +The namespace exports the following array constructors: + + + +
+ +- [`ArrayBuffer( size )`][@stdlib/array/buffer]: constructor which returns an object used to represent a generic, fixed-length raw binary data buffer. +- [`Float32Array()`][@stdlib/array/float32]: typed array constructor which returns a typed array representing an array of single-precision floating-point numbers in the platform byte order. +- [`Float64Array()`][@stdlib/array/float64]: typed array constructor which returns a typed array representing an array of double-precision floating-point numbers in the platform byte order. +- [`Int16Array()`][@stdlib/array/int16]: typed array constructor which returns a typed array representing an array of twos-complement 16-bit signed integers in the platform byte order. +- [`Int32Array()`][@stdlib/array/int32]: typed array constructor which returns a typed array representing an array of twos-complement 32-bit signed integers in the platform byte order. +- [`Int8Array()`][@stdlib/array/int8]: typed array constructor which returns a typed array representing an array of twos-complement 8-bit signed integers in the platform byte order. +- [`SharedArrayBuffer( size )`][@stdlib/array/shared-buffer]: constructor returning an object used to represent a generic, fixed-length raw binary data buffer which can be used to create views of shared memory. +- [`Uint16Array()`][@stdlib/array/uint16]: typed array constructor which returns a typed array representing an array of 16-bit unsigned integers in the platform byte order. +- [`Uint32Array()`][@stdlib/array/uint32]: typed array constructor which returns a typed array representing an array of 32-bit unsigned integers in the platform byte order. +- [`Uint8Array()`][@stdlib/array/uint8]: typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order. +- [`Uint8ClampedArray()`][@stdlib/array/uint8c]: typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order clamped to 0-255. + +
+ + + +```javascript +var arr = new ns.Int32Array( 5 ); +// returns [ 0, 0, 0, 0, 0 ] +``` + +Alternatively, use the `typedarray` function to create a typed array of a given data type: + + + +
+ +- [`typedarray()`][@stdlib/array/typed]: create a typed array. + +
+ + + +```javascript +var arr1 = ns.typedarray( 5 ); +// returns [ 0.0, 0.0, 0.0, 0.0, 0.0 ] + +var arr2 = ns.typedarray( 5, 'uint8' ); +// returns [ 0, 0, 0, 0, 0 ] +``` + +The namespace contains functions to create arrays pre-filled with spaced values: + + + +
+ +- [`datespace( start, stop[, length][, opts] )`][@stdlib/array/datespace]: generate an array of linearly spaced dates. +- [`incrspace( start, stop[, increment] )`][@stdlib/array/incrspace]: generate a linearly spaced numeric array using a provided increment. +- [`linspace( start, stop[, length] )`][@stdlib/array/linspace]: generate a linearly spaced numeric array. +- [`logspace( a, b[, length] )`][@stdlib/array/logspace]: generate a logarithmically spaced numeric array. + +
+ + + +You can use the following functions to retrieve a list of available data types: + + + +
+ +- [`arrayDataTypes()`][@stdlib/array/dtypes]: list of array data types. +- [`typedarrayComplexDataTypes()`][@stdlib/array/typed-complex-dtypes]: list of complex typed array data types. +- [`typedarrayDataTypes()`][@stdlib/array/typed-dtypes]: list of typed array data types. + +
+ + + +```javascript +var DTYPES = ns.arrayDataTypes(); +// returns [ 'float32', 'float64', 'generic', 'int16', 'int32', 'int8', 'uint16', 'uint32', 'uint8', 'uint8c' ] +``` + +Furthermore, the namespace contains utility functions to retrieve a given constructor: + + + +
+ +- [`arrayCtors( dtype )`][@stdlib/array/ctors]: array constructors. +- [`typedarrayComplexCtors( dtype )`][@stdlib/array/typed-complex-ctors]: complex typed array constructors. +- [`typedarrayCtors( dtype )`][@stdlib/array/typed-ctors]: typed array constructors. + +
+ + + +```javascript +var ctor = ns.typedarrayCtors( 'float64' ); +// returns + +ctor = ns.typedarrayCtors( 'int' ); +// returns null +``` + +Lastly, the namespace contains various other functions for dealing with arrays, including functions to convert arrays from one data type to another or to serialize them as JSON and vice versa. + + + +
+ +- [`convertArray( arr, dtype )`][@stdlib/array/convert]: convert an array to an array of a different data type. +- [`convertArraySame( x, y )`][@stdlib/array/convert-same]: convert an array to the same data type as a second input array. +- [`arrayDataType( array )`][@stdlib/array/dtype]: return the data type of an array. +- [`reviveTypedArray( key, value )`][@stdlib/array/reviver]: revive a JSON-serialized typed array. +- [`typedarray2json( typedarray )`][@stdlib/array/to-json]: return a JSON representation of a typed array. + +
+ + + +
+ + + +
+ +## Examples + + + + + +```javascript +var objectKeys = require( '@stdlib/utils/keys' ); +var ns = require( '@stdlib/array' ); + +console.log( objectKeys( ns ) ); +``` + +
+ + + + +
+ +* * * + +## Notice + +This package is part of [stdlib][stdlib], a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing. The library provides a collection of robust, high performance libraries for mathematics, statistics, streams, utilities, and more. + +For more information on the project, filing bug reports and feature requests, and guidance on how to develop [stdlib][stdlib], see the main project [repository][stdlib]. + +--- + +## License + +See [LICENSE][stdlib-license]. + + +## Copyright + +Copyright © 2016-2021. The Stdlib [Authors][stdlib-authors]. + +
+ + + + + + + + diff --git a/buffer/README.md b/buffer/README.md new file mode 100644 index 00000000..bcf8b574 --- /dev/null +++ b/buffer/README.md @@ -0,0 +1,235 @@ + + +# ArrayBuffer + +> [Constructor][mdn-arraybuffer] which returns an object used to represent a generic, fixed-length raw binary data buffer. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var ArrayBuffer = require( '@stdlib/array/buffer' ); +``` + +#### ArrayBuffer( size ) + +Returns an [`ArrayBuffer`][mdn-arraybuffer] having a specified number of bytes. + + + +```javascript +var buf = new ArrayBuffer( 5 ); +// returns +``` + +* * * + +### Properties + +#### ArrayBuffer.length + +Number of input arguments the constructor accepts. + + + +```javascript +var len = ArrayBuffer.length; +// returns 1 +``` + +#### ArrayBuffer.prototype.byteLength + +**Read-only** property which returns the length (in bytes) of the [`ArrayBuffer`][mdn-arraybuffer]. + + + +```javascript +var buf = new ArrayBuffer( 5 ); +var byteLength = buf.byteLength; +// returns 5 +``` + +* * * + +### Methods + +#### ArrayBuffer.isView( arr ) + +Static method which returns a `boolean` indicating if provided a buffer view. + + + +```javascript +var Float64Array = require( '@stdlib/array/float64' ); +var view = new Float64Array( 10 ); + +var bool = ArrayBuffer.isView( view ); +// returns true +``` + +#### ArrayBuffer.prototype.slice( \[start\[, end]] ) + +Copies the bytes of an `ArrayBuffer` to a new [`ArrayBuffer`][mdn-arraybuffer]. + + + +```javascript +var b1 = new ArrayBuffer( 10 ); + +var b2 = b1.slice(); +// returns + +var bool = ( b2 === b1 ); +// returns false +``` + +By default, the method copies from the beginning of the [`ArrayBuffer`][mdn-arraybuffer]. To beginning copying from a different byte index, provide a `start` argument, specifying the starting byte index (inclusive). + + + +```javascript +var b1 = new ArrayBuffer( 10 ); +var b2 = b1.slice( 2 ); + +var nbytes = b2.byteLength; +// returns 8 +``` + +If `start < 0`, the index is relative to the end of the [`ArrayBuffer`][mdn-arraybuffer]. + + + +```javascript +var b1 = new ArrayBuffer( 10 ); +var b2 = b1.slice( -2 ); + +var nbytes = b2.byteLength; +// returns 2 +``` + +By default, the method copies to the end of the [`ArrayBuffer`][mdn-arraybuffer]. To copy until a particular byte index, provide an `end` index, specifying the ending byte index (exclusive). + + + +```javascript +var b1 = new ArrayBuffer( 10 ); +var b2 = b1.slice( 2, 6 ); + +var nbytes = b2.byteLength; +// returns 4 +``` + +If `end < 0`, the index is relative to the end of the [`ArrayBuffer`][mdn-arraybuffer]. + + + +```javascript +var b1 = new ArrayBuffer( 10 ); +var b2 = b1.slice( 2, -2 ); + +var nbytes = b2.byteLength; +// returns 6 +``` + +
+ + + +* * * + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var randu = require( '@stdlib/random/base/randu' ); +var Float64Array = require( '@stdlib/array/float64' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var toBinaryString = require( '@stdlib/number/uint8/base/to-binary-string' ); +var ArrayBuffer = require( '@stdlib/array/buffer' ); + +var bytes; +var buf; +var arr; +var i; + +// Create a new ArrayBuffer: +buf = new ArrayBuffer( 64 ); + +// Create a Float64 array buffer view: +arr = new Float64Array( buf.byteLength/8 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = randu() * 100.0; +} + +// Create a "bytes" view of the array buffer: +bytes = new Uint8Array( arr.buffer ); + +// Print the bytes: +for ( i = 0; i < bytes.length; i++ ) { + console.log( 'byte %d: %s', i, toBinaryString( bytes[ i ] ) ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/buffer/benchmark/benchmark.js b/buffer/benchmark/benchmark.js new file mode 100644 index 00000000..579bbbbf --- /dev/null +++ b/buffer/benchmark/benchmark.js @@ -0,0 +1,55 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var hasArrayBufferSupport = require( '@stdlib/assert/has-arraybuffer-support' ); +var isArrayBuffer = require( '@stdlib/assert/is-arraybuffer' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// VARIABLES // + +var opts = { + 'skip': !hasArrayBufferSupport() // TODO: remove once ArrayBuffer polyfill is written +}; + + +// MAIN // + +bench( pkg, opts, function benchmark( b ) { + var buf; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf = new ctor( 0 ); + if ( buf.byteLength !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isArrayBuffer( buf ) ) { + b.fail( 'should return an ArrayBuffer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/buffer/benchmark/benchmark.length.js b/buffer/benchmark/benchmark.length.js new file mode 100644 index 00000000..c58f5d1e --- /dev/null +++ b/buffer/benchmark/benchmark.length.js @@ -0,0 +1,101 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var hasArrayBufferSupport = require( '@stdlib/assert/has-arraybuffer-support' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isArrayBuffer = require( '@stdlib/assert/is-arraybuffer' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// VARIABLES // + +var opts = { + 'skip': !hasArrayBufferSupport() // TODO: remove once ArrayBuffer polyfill is written +}; + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array buffer length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var buf; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf = new ctor( len ); + if ( buf.byteLength !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isArrayBuffer( buf ) ) { + b.fail( 'should return an ArrayBuffer' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':len='+len, opts, f ); + } +} + +main(); diff --git a/buffer/docs/repl.txt b/buffer/docs/repl.txt new file mode 100644 index 00000000..c99f899a --- /dev/null +++ b/buffer/docs/repl.txt @@ -0,0 +1,92 @@ + +{{alias}}( size ) + Returns an array buffer having a specified number of bytes. + + Buffer contents are initialized to 0. + + Parameters + ---------- + size: integer + Number of bytes. + + Returns + ------- + out: ArrayBuffer + An array buffer. + + Examples + -------- + > var buf = new {{alias}}( 5 ) + + + +{{alias}}.length + Number of input arguments the constructor accepts. + + Examples + -------- + > {{alias}}.length + 1 + + +{{alias}}.isView( arr ) + Returns a boolean indicating if provided an array buffer view. + + Parameters + ---------- + arr: any + Value to test. + + Returns + ------- + bool: boolean + Boolean indicating if an input argument is a buffer view. + + Examples + -------- + > var arr = new {{alias:@stdlib/array/float64}}( 10 ); + > {{alias}}.isView( arr ) + true + + +{{alias}}.prototype.byteLength + Read-only property which returns the length (in bytes) of the array buffer. + + Examples + -------- + > var buf = new {{alias}}( 5 ); + > buf.byteLength + 5 + + +{{alias}}.prototype.slice( [start[, end]] ) + Copies the bytes of an array buffer to a new array buffer. + + Parameters + ---------- + start: integer (optional) + Index at which to start copying buffer contents (inclusive). If + negative, the index is relative to the end of the buffer. + + end: integer (optional) + Index at which to stop copying buffer contents (exclusive). If negative, + the index is relative to the end of the buffer. + + Returns + ------- + out: ArrayBuffer + A new array buffer whose contents have been copied from the calling + array buffer. + + Examples + -------- + > var b1 = new {{alias}}( 10 ); + > var b2 = b1.slice( 2, 6 ); + > var bool = ( b1 === b2 ) + false + > b2.byteLength + 4 + + See Also + -------- + diff --git a/buffer/docs/types/index.d.ts b/buffer/docs/types/index.d.ts new file mode 100644 index 00000000..409a264a --- /dev/null +++ b/buffer/docs/types/index.d.ts @@ -0,0 +1,26 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +// EXPORTS // + +/** +* Constructor which returns an object used to represent a generic, fixed-length raw binary data buffer. +*/ +export = ArrayBuffer; diff --git a/buffer/docs/types/test.ts b/buffer/docs/types/test.ts new file mode 100644 index 00000000..3a5288ac --- /dev/null +++ b/buffer/docs/types/test.ts @@ -0,0 +1,35 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// tslint:disable: no-construct +// tslint:disable: no-unused-expression + +import ArrayBuffer = require( './index' ); + + +// TESTS // + +// The function returns a data view instance... +{ + new ArrayBuffer( 5 ); // $ExpectType ArrayBuffer +} + +// The constructor function has to be invoked with `new`... +{ + ArrayBuffer( 5 ); // $ExpectError +} diff --git a/buffer/examples/index.js b/buffer/examples/index.js new file mode 100644 index 00000000..9080725a --- /dev/null +++ b/buffer/examples/index.js @@ -0,0 +1,54 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var proc = require( 'process' ); +var hasArrayBufferSupport = require( '@stdlib/assert/has-arraybuffer-support' ); +var randu = require( '@stdlib/random/base/randu' ); +var Float64Array = require( '@stdlib/array/float64' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var toBinaryString = require( '@stdlib/number/uint8/base/to-binary-string' ); +var ArrayBuffer = require( './../lib' ); + +var bytes; +var buf; +var arr; +var i; + +if ( !hasArrayBufferSupport() ) { + // TODO: remove once ArrayBuffer polyfill is written + console.error( 'Environment does not provide ArrayBuffer support.' ); + proc.exit( 0 ); +} +// Create a new ArrayBuffer: +buf = new ArrayBuffer( 64 ); + +// Create a Float64 array buffer view: +arr = new Float64Array( buf.byteLength/8 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = randu() * 100.0; +} + +// Create a "bytes" view of the array buffer: +bytes = new Uint8Array( arr.buffer ); + +// Print the bytes: +for ( i = 0; i < bytes.length; i++ ) { + console.log( 'byte %d: %s', i, toBinaryString( bytes[ i ] ) ); +} diff --git a/buffer/lib/arraybuffer.js b/buffer/lib/arraybuffer.js new file mode 100644 index 00000000..39e05e18 --- /dev/null +++ b/buffer/lib/arraybuffer.js @@ -0,0 +1,28 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MAIN // + +var ctor = ( typeof ArrayBuffer === 'function' ) ? ArrayBuffer : void 0; // eslint-disable-line stdlib/require-globals + + +// EXPORTS // + +module.exports = ctor; diff --git a/buffer/lib/index.js b/buffer/lib/index.js new file mode 100644 index 00000000..43c77725 --- /dev/null +++ b/buffer/lib/index.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Constructor which returns an object used to represent a generic, fixed-length raw binary data buffer. +* +* @module @stdlib/array/buffer +* +* @example +* var ctor = require( '@stdlib/array/buffer' ); +* +* var buf = new ctor( 10 ); +* // returns +*/ + +// MODULES // + +var hasArrayBufferSupport = require( '@stdlib/assert/has-arraybuffer-support' ); +var builtin = require( './arraybuffer.js' ); +var polyfill = require( './polyfill.js' ); + + +// MAIN // + +var ctor; +if ( hasArrayBufferSupport() ) { + ctor = builtin; +} else { + ctor = polyfill; +} + + +// EXPORTS // + +module.exports = ctor; diff --git a/buffer/lib/polyfill.js b/buffer/lib/polyfill.js new file mode 100644 index 00000000..f1249980 --- /dev/null +++ b/buffer/lib/polyfill.js @@ -0,0 +1,37 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// TODO: write polyfill + +// MAIN // + +/** +* Constructor which returns an object used to represent a generic, fixed-length raw binary data buffer. +* +* @throws {Error} not implemented +*/ +function polyfill() { + throw new Error( 'not implemented' ); +} + + +// EXPORTS // + +module.exports = polyfill; diff --git a/buffer/package.json b/buffer/package.json new file mode 100644 index 00000000..8e8caeae --- /dev/null +++ b/buffer/package.json @@ -0,0 +1,66 @@ +{ + "name": "@stdlib/array/buffer", + "version": "0.0.0", + "description": "ArrayBuffer.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structure", + "array", + "typed", + "typed array", + "typed-array", + "arraybuffer", + "buffer", + "buf", + "binary" + ] +} diff --git a/buffer/test/test.js b/buffer/test/test.js new file mode 100644 index 00000000..528db184 --- /dev/null +++ b/buffer/test/test.js @@ -0,0 +1,195 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var hasArrayBufferSupport = require( '@stdlib/assert/has-arraybuffer-support' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var instanceOf = require( '@stdlib/assert/instance-of' ); +var Float64Array = require( '@stdlib/array/float64' ); +var MAX_SAFE_INTEGER = require( '@stdlib/constants/float64/max-safe-integer' ); +var hasOwnProp = require( '@stdlib/assert/has-own-property' ); +var hasProp = require( '@stdlib/assert/has-property' ); +var NODE_VERSION = require( '@stdlib/process/node-version' ); +var polyfill = require( './../lib/polyfill.js' ); +var Ctor = require( './../lib' ); + + +// VARIABLES // + +var FLG = hasArrayBufferSupport(); +var opts = { + 'skip': ( NODE_VERSION && NODE_VERSION.slice( 0, 4 ) === '0.10' ) // FIXME: remove once polyfill is written +}; + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof Ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'if an environment supports `ArrayBuffer`, the export is an alias for `ArrayBuffer`', function test( t ) { + var Foo = proxyquire( './../lib', { + '@stdlib/assert/has-arraybuffer-support': isTrue, + './arraybuffer.js': Mock + }); + t.strictEqual( Foo, Mock, 'returns builtin' ); + + if ( FLG ) { + t.strictEqual( Ctor, ArrayBuffer, 'is alias' ); // eslint-disable-line stdlib/require-globals + } + + t.end(); + + function Mock() { + return this; + } + + function isTrue() { + return true; + } +}); + +tape( 'if an environment does not support `ArrayBuffer`, the export is a polyfill', function test( t ) { + var Foo = proxyquire( './../lib', { + '@stdlib/assert/has-arraybuffer-support': isFalse + }); + + t.strictEqual( Foo, polyfill, 'returns polyfill' ); + t.end(); + + function isFalse() { + return false; + } +}); + +tape( 'the main export is a constructor', opts, function test( t ) { + var buf = new Ctor( 10 ); + t.strictEqual( instanceOf( buf, Ctor ), true, 'returns an instance' ); + t.end(); +}); + +tape( 'the constructor has a static method for testing whether a value is a buffer view', opts, function test( t ) { + var arr; + + t.strictEqual( isFunction( Ctor.isView ), true, 'has method' ); + + arr = new Float64Array( 10 ); + t.strictEqual( Ctor.isView( arr ), true, 'returns expected value' ); + t.strictEqual( Ctor.isView( [] ), false, 'returns expected value' ); + + t.end(); +}); + +tape( 'the constructor length is equal to `1`', opts, function test( t ) { + t.strictEqual( Ctor.length, 1, 'returns expected value' ); + t.end(); +}); + +tape( 'the constructor throws an error if provided a value exceeding `2^53-1`', opts, function test( t ) { + t.throws( badValue, RangeError, 'throws an error' ); + t.end(); + + function badValue() { + return new Ctor( MAX_SAFE_INTEGER+1 ); + } +}); + +tape( 'the constructor returns an `ArrayBuffer` instance having a `byteLength` property, which returns the number of bytes in an `ArrayBuffer`', opts, function test( t ) { + var buf; + + t.strictEqual( hasOwnProp( Ctor.prototype, 'byteLength' ), true, 'has prototype property' ); + + buf = new Ctor( 10 ); + t.strictEqual( hasOwnProp( buf, 'byteLength' ), false, 'does not have own property' ); + t.strictEqual( hasProp( buf, 'byteLength' ), true, 'has property' ); + t.strictEqual( buf.byteLength, 10, 'returns expected value' ); + + t.end(); +}); + +tape( 'the constructor returns an `ArrayBuffer` instance having a `slice` method, which copies the bytes of an `ArrayBuffer` to a new `ArrayBuffer`', opts, function test( t ) { + var b1; + var b2; + + t.strictEqual( hasOwnProp( Ctor.prototype, 'slice' ), true, 'has prototype property' ); + t.strictEqual( isFunction( Ctor.prototype.slice ), true, 'has method' ); + + b1 = new Ctor( 10 ); + t.strictEqual( hasOwnProp( b1, 'slice' ), false, 'does not have own property' ); + t.strictEqual( hasProp( b1, 'slice' ), true, 'has property' ); + + b2 = b1.slice(); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, b1.byteLength, 'has same number of bytes' ); + + b2 = b1.slice( 2 ); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, 8, 'has expected number of bytes' ); + + b2 = b1.slice( b1.byteLength + 10 ); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, 0, 'has expected number of bytes' ); + + b2 = b1.slice( -2 ); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, 2, 'has expected number of bytes' ); + + b2 = b1.slice( -100 ); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, 10, 'has expected number of bytes' ); + + b2 = b1.slice( 0, 6 ); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, 6, 'has expected number of bytes' ); + + b2 = b1.slice( 2, 6 ); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, 4, 'has expected number of bytes' ); + + b2 = b1.slice( 0, -2 ); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, 8, 'has expected number of bytes' ); + + b2 = b1.slice( 0, -100 ); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, 0, 'has expected number of bytes' ); + + b2 = b1.slice( -4, -2 ); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, 2, 'has expected number of bytes' ); + + t.end(); +}); diff --git a/buffer/test/test.polyfill.js b/buffer/test/test.polyfill.js new file mode 100644 index 00000000..9d6fcb19 --- /dev/null +++ b/buffer/test/test.polyfill.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var ctor = require( './../lib/polyfill.js' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error when invoked', function test( t ) { + t.throws( foo, Error, 'throws an error' ); + t.end(); + + function foo() { + var f = new ctor(); // eslint-disable-line no-unused-vars + } +}); + +// TODO: tests diff --git a/complex128/docs/types/index.d.ts b/complex128/docs/types/index.d.ts new file mode 100644 index 00000000..026d2629 --- /dev/null +++ b/complex128/docs/types/index.d.ts @@ -0,0 +1,538 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/// + +import { ArrayLike, TypedArray } from '@stdlib/types/array'; +import { ComplexLike } from '@stdlib/types/object'; +import ArrayBuffer = require( '@stdlib/array/buffer' ); +import Complex128 = require( '@stdlib/complex/float64' ); + +/** +* Class for creating a 128-bit complex number array. +*/ +declare class Complex128Array { + /** + * 128-bit complex number array constructor. + * + * @param arg - length, typed array, array-like object, or buffer + * @param byteOffset - byte offset (default: 0) + * @param length - view length + * @throws ArrayBuffer byte length must be a multiple of `8` + * @throws array-like object and typed array input arguments must have a length which is a multiple of two + * @throws if provided only a single argument, must provide a valid argument + * @throws byte offset must be a nonnegative integer + * @throws byte offset must be a multiple of `8` + * @throws view length must be a positive multiple of `8` + * @throws must provide sufficient memory to accommodate byte offset and view length requirements + * @throws an iterator must return either a two element array containing real and imaginary components or a complex number + * @returns complex number array + * + * @example + * var arr = new Complex128Array(); + * // returns + * + * var len = arr.length; + * // returns 0 + * + * @example + * var arr = new Complex128Array( 2 ); + * // returns + * + * var len = arr.length; + * // returns 2 + * + * @example + * var arr = new Complex128Array( [ 1.0, -1.0 ] ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 16 ); + * var arr = new Complex128Array( buf ); + * // returns + * + * var len = arr.length; + * // returns 2 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 16 ); + * var arr = new Complex128Array( buf, 8 ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 32 ); + * var arr = new Complex128Array( buf, 8, 2 ); + * // returns + * + * var len = arr.length; + * // returns 2 + */ + constructor( arg?: number | TypedArray | ArrayLike | ArrayBuffer | Iterable, byteOffset?: number, length?: number ); // tslint:disable-line:max-line-length + + /** + * Length (in bytes) of the array. + * + * @example + * var arr = new Complex128Array( 10 ); + * + * var byteLength = arr.byteLength; + * // returns 160 + */ + readonly byteLength: number; + + /** + * Offset (in bytes) of the array from the start of its underlying `ArrayBuffer`. + * + * @example + * var arr = new Complex128Array( 10 ); + * + * var byteOffset = arr.byteOffset; + * // returns 0 + */ + readonly byteOffset: number; + + /** + * Size (in bytes) of each array element. + * + * @example + * var arr = new Complex128Array( 10 ); + * + * var nbytes = arr.BYTES_PER_ELEMENT; + * // returns 16 + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Number of array elements. + * + * @example + * var arr = new Complex128Array( 10 ); + * + * var len = arr.length; + * // returns 10 + */ + readonly length: number; + + /** + * Returns an array element. + * + * @param i - element index + * @throws index argument must be a nonnegative integer + * @returns array element + * + * @example + * var arr = new Complex128Array( 10 ); + * + * var z = arr.get( 0 ); + * // returns + * + * arr.set( [ 1.0, -1.0 ], 0 ); + * + * z = arr.get( 100 ); + * // returns undefined + */ + get( i: number ): Complex128 | void; + + /** + * Returns an array element. + * + * @param out - output array + * @param i - element index + * @throws index argument must be a nonnegative integer + * @returns array element + * + * @example + * var arr = new Complex128Array( 10 ); + * + * var z = arr.get( 0 ); + * // returns + * + * arr.set( [ 1.0, -1.0 ], 0 ); + * + * z = arr.get( [ 0.0, 0.0 ], 0 ); + * // returns [ 1.0, -1.0 ] + */ + get( out: ArrayLike, i: number ): ArrayLike | void; + + /** + * Sets an array element. + * + * ## Notes + * + * - When provided a typed array, real or complex, we must check whether the source array shares the same buffer as the target array and whether the underlying memory overlaps. In particular, we are concerned with the following scenario: + * + * ```text + * buf: --------------------- + * src: --------------------- + * ``` + * + * In the above, as we copy values from `src`, we will overwrite values in the `src` view, resulting in duplicated values copied into the end of `buf`, which is not intended. Hence, to avoid overwriting source values, we must **copy** source values to a temporary array. + * + * In the other overlapping scenario, + * + * ```text + * buf: --------------------- + * src: --------------------- + * ``` + * + * by the time we begin copying into the overlapping region, we are copying from the end of `src`, a non-overlapping region, which means we don't run the risk of copying copied values, rather than the original `src` values as intended. + * + * + * @param value - value(s) + * @param i - element index at which to start writing values (default: 0) + * @throws index argument must be a nonnegative integer + * @throws array-like objects must have a length which is a multiple of two + * @throws index argument is out-of-bounds + * @throws target array lacks sufficient storage to accommodate source values + * + * @example + * var real = require( `@stdlib/complex/real` ); + * var imag = require( `@stdlib/complex/imag` ); + * + * var arr = new Complex128Array( 10 ); + * + * var z = arr.get( 0 ); + * // returns + * + * var re = real( z ); + * // returns 0.0 + * + * var im = imag( z ); + * // returns 0.0 + * + * arr.set( [ 1.0, -1.0 ], 0 ); + * + * z = arr.get( 0 ); + * // returns + * + * re = real( z ); + * // returns 1.0 + * + * im = imag( z ); + * // returns -1.0 + */ + set( value: ArrayLike | Complex128Array | ComplexLike, i?: number ): void; // tslint:disable-line:max-line-length +} + +/** +* Interface defining a 128-bit complex number array constructor which is both "newable" and "callable". +*/ +interface Constructor { + /** + * 128-bit complex number array constructor. + * + * @param arg - length, typed array, array-like object, or buffer + * @param byteOffset - byte offset (default: 0) + * @param length - view length + * @throws ArrayBuffer byte length must be a multiple of `8` + * @throws array-like object and typed array input arguments must have a length which is a multiple of two + * @throws if provided only a single argument, must provide a valid argument + * @throws byte offset must be a nonnegative integer + * @throws byte offset must be a multiple of `8` + * @throws view length must be a positive multiple of `8` + * @throws must provide sufficient memory to accommodate byte offset and view length requirements + * @throws an iterator must return either a two element array containing real and imaginary components or a complex number + * @returns complex number array + * + * @example + * var arr = new Complex128Array(); + * // returns + * + * var len = arr.length; + * // returns 0 + * + * @example + * var arr = new Complex128Array( 2 ); + * // returns + * + * var len = arr.length; + * // returns 2 + * + * @example + * var arr = new Complex128Array( [ 1.0, -1.0 ] ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 16 ); + * var arr = new Complex128Array( buf ); + * // returns + * + * var len = arr.length; + * // returns 2 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 16 ); + * var arr = new Complex128Array( buf, 8 ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 32 ); + * var arr = new Complex128Array( buf, 8, 2 ); + * // returns + * + * var len = arr.length; + * // returns 2 + */ + new( arg?: number | TypedArray | ArrayLike | ArrayBuffer | Iterable, byteOffset?: number, length?: number ): Complex128Array; // tslint-disable-line max-line-length + + /** + * 128-bit complex number array constructor. + * + * @param arg - length, typed array, array-like object, or buffer + * @param byteOffset - byte offset (default: 0) + * @param length - view length + * @throws ArrayBuffer byte length must be a multiple of `8` + * @throws array-like object and typed array input arguments must have a length which is a multiple of two + * @throws if provided only a single argument, must provide a valid argument + * @throws byte offset must be a nonnegative integer + * @throws byte offset must be a multiple of `8` + * @throws view length must be a positive multiple of `8` + * @throws must provide sufficient memory to accommodate byte offset and view length requirements + * @throws an iterator must return either a two element array containing real and imaginary components or a complex number + * @returns complex number array + * + * @example + * var arr = new Complex128Array(); + * // returns + * + * var len = arr.length; + * // returns 0 + * + * @example + * var arr = new Complex128Array( 2 ); + * // returns + * + * var len = arr.length; + * // returns 2 + * + * @example + * var arr = new Complex128Array( [ 1.0, -1.0 ] ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 16 ); + * var arr = new Complex128Array( buf ); + * // returns + * + * var len = arr.length; + * // returns 2 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 16 ); + * var arr = new Complex128Array( buf, 8 ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 32 ); + * var arr = new Complex128Array( buf, 8, 2 ); + * // returns + * + * var len = arr.length; + * // returns 2 + */ + ( arg?: number | TypedArray | ArrayLike | ArrayBuffer | Iterable, byteOffset?: number, length?: number ): Complex128Array; // tslint-disable-line max-line-length + + /** + * Constructor name. + * + * @example + * var str = Complex128Array.name; + * // returns 'Complex128Array' + */ + readonly name: string; + + /** + * Size (in bytes) of each array element. + * + * @example + * var nbytes = Complex128Array.BYTES_PER_ELEMENT; + * // returns 16 + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Creates a new 128-bit complex number array from an array-like object or an iterable. + * + * @param src - array-like object or iterable + * @param clbk - callback to invoke for each source element + * @param thisArg - context + * @throws array-like objects must have a length which is a multiple of two + * @throws an iterator must return either a two element array containing real and imaginary components or a complex number + * @throws when provided an iterator, a callback must return either a two element array containing real and imaginary components or a complex number + * @returns 128-bit complex number array + * + * @example + * var arr = Complex128Array.from( [ 1.0, -1.0 ] ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var Complex128 = require( `@stdlib/complex/float64` ); + * + * var arr = Complex128Array.from( [ new Complex128( 1.0, 1.0 ) ] ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var Complex128 = require( `@stdlib/complex/float64` ); + * var real = require( `@stdlib/complex/real` ); + * var imag = require( `@stdlib/complex/imag` ); + * + * function clbk( v ) { + * return new Complex128( real(v)*2.0, imag(v)*2.0 ); + * } + * + * var arr = Complex128Array.from( [ new Complex128( 1.0, 1.0 ) ], clbk ); + * // returns + * + * var len = arr.length; + * // returns 1 + */ + from( src: ArrayLike | Iterable, clbk?: Function, thisArg?: any ): Complex128Array; // tslint:disable-line:max-line-length + + /** + * Creates a new 128-bit complex number array from a variable number of arguments. + * + * @param element - array elements + * @returns 128-bit complex number array + * + * @example + * var arr = Complex128Array.of( 1.0, 1.0, 1.0, 1.0 ); + * // returns + * + * var len = arr.length; + * // returns 2 + */ + of( ...elements: Array ): Complex128Array; +} + +/** +* 128-bit complex number array constructor. +* +* @param arg - length, typed array, array-like object, or buffer +* @param byteOffset - byte offset (default: 0) +* @param length - view length +* @throws ArrayBuffer byte length must be a multiple of `8` +* @throws array-like object and typed array input arguments must have a length which is a multiple of two +* @throws if provided only a single argument, must provide a valid argument +* @throws byte offset must be a nonnegative integer +* @throws byte offset must be a multiple of `8` +* @throws view length must be a positive multiple of `8` +* @throws must provide sufficient memory to accommodate byte offset and view length requirements +* @throws an iterator must return either a two element array containing real and imaginary components or a complex number +* @returns complex number array +* +* @example +* var arr = new Complex128Array(); +* // returns +* +* var len = arr.length; +* // returns 0 +* +* @example +* var arr = new Complex128Array( 2 ); +* // returns +* +* var len = arr.length; +* // returns 2 +* +* @example +* var arr = new Complex128Array( [ 1.0, -1.0 ] ); +* // returns +* +* var len = arr.length; +* // returns 1 +* +* @example +* var ArrayBuffer = require( `@stdlib/array/buffer` ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = new Complex128Array( buf ); +* // returns +* +* var len = arr.length; +* // returns 2 +* +* @example +* var ArrayBuffer = require( `@stdlib/array/buffer` ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = new Complex128Array( buf, 8 ); +* // returns +* +* var len = arr.length; +* // returns 1 +* +* @example +* var ArrayBuffer = require( `@stdlib/array/buffer` ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = new Complex128Array( buf, 8, 2 ); +* // returns +* +* var len = arr.length; +* // returns 2 +*/ +declare var ctor: Constructor; + + +// EXPORTS // + +export = ctor; diff --git a/complex128/docs/types/test.ts b/complex128/docs/types/test.ts new file mode 100644 index 00000000..cb2170e8 --- /dev/null +++ b/complex128/docs/types/test.ts @@ -0,0 +1,153 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// tslint:disable:no-unused-expression + +import Complex128Array = require( './index' ); +import Complex128 = require( '@stdlib/complex/float64' ); +import ArrayBuffer = require( '@stdlib/array/buffer' ); +import real = require( '@stdlib/complex/real' ); +import imag = require( '@stdlib/complex/imag' ); + +const clbk = ( v: Complex128 ) => { + return new Complex128( real( v ) * 2.0, imag( v ) * 2.0 ); +}; + + +// TESTS // + +// The function returns a complex number array... +{ + new Complex128Array(); // $ExpectType Complex128Array + Complex128Array(); // $ExpectType Complex128Array + new Complex128Array( 2 ); // $ExpectType Complex128Array + Complex128Array( 2 ); // $ExpectType Complex128Array + new Complex128Array( [ 1.0, -1.0 ] ); // $ExpectType Complex128Array + Complex128Array( [ 1.0, -1.0 ] ); // $ExpectType Complex128Array + + const buf = new ArrayBuffer( 16 ); + new Complex128Array( buf ); // $ExpectType Complex128Array + Complex128Array( buf ); // $ExpectType Complex128Array + new Complex128Array( buf, 8 ); // $ExpectType Complex128Array + Complex128Array( buf, 8 ); // $ExpectType Complex128Array + new Complex128Array( buf, 8, 2 ); // $ExpectType Complex128Array + Complex128Array( buf, 8, 2 ); // $ExpectType Complex128Array +} + +// The compiler throws an error if the function is provided a first argument that is not a number, typed array, array-like object, or array buffer... +{ + new Complex128Array( true ); // $ExpectError + new Complex128Array( false ); // $ExpectError + new Complex128Array( null ); // $ExpectError + new Complex128Array( 'abc' ); // $ExpectError + new Complex128Array( {} ); // $ExpectError + new Complex128Array( ( x: number ): number => x ); // $ExpectError + + Complex128Array( true ); // $ExpectError + Complex128Array( false ); // $ExpectError + Complex128Array( null ); // $ExpectError + Complex128Array( 'abc' ); // $ExpectError + Complex128Array( {} ); // $ExpectError + Complex128Array( ( x: number ): number => x ); // $ExpectError +} + +// The compiler throws an error if the function is provided a second argument that is not a number... +{ + const buf = new ArrayBuffer( 16 ); + new Complex128Array( buf, true ); // $ExpectError + new Complex128Array( buf, false ); // $ExpectError + new Complex128Array( buf, null ); // $ExpectError + new Complex128Array( buf, 'abc' ); // $ExpectError + new Complex128Array( buf, {} ); // $ExpectError + new Complex128Array( buf, ( x: number ): number => x ); // $ExpectError + + Complex128Array( buf, true ); // $ExpectError + Complex128Array( buf, false ); // $ExpectError + Complex128Array( buf, null ); // $ExpectError + Complex128Array( buf, 'abc' ); // $ExpectError + Complex128Array( buf, {} ); // $ExpectError + Complex128Array( buf, ( x: number ): number => x ); // $ExpectError +} + +// The compiler throws an error if the function is provided a third argument that is not a number... +{ + const buf = new ArrayBuffer( 16 ); + new Complex128Array( buf, 8, true ); // $ExpectError + new Complex128Array( buf, 8, false ); // $ExpectError + new Complex128Array( buf, 8, null ); // $ExpectError + new Complex128Array( buf, 8, 'abc' ); // $ExpectError + new Complex128Array( buf, 8, {} ); // $ExpectError + new Complex128Array( buf, 8, ( x: number ): number => x ); // $ExpectError + + Complex128Array( buf, 8, true ); // $ExpectError + Complex128Array( buf, 8, false ); // $ExpectError + Complex128Array( buf, 8, null ); // $ExpectError + Complex128Array( buf, 8, 'abc' ); // $ExpectError + Complex128Array( buf, 8, {} ); // $ExpectError + Complex128Array( buf, 8, ( x: number ): number => x ); // $ExpectError +} + +// The `from` method returns a complex number array... +{ + Complex128Array.from( [ 1.0, 1.0 ] ); // $ExpectType Complex128Array + Complex128Array.from( [ 1.0, 1.0 ], ( x: number ): number => x * x ); // $ExpectType Complex128Array + Complex128Array.from( [ new Complex128( 1.0, 1.0 ) ], clbk, {} ); // $ExpectType Complex128Array +} + +// The compiler throws an error if the `from` method is provided a first argument which is not array-like or iterable... +{ + Complex128Array.from( true ); // $ExpectError + Complex128Array.from( false ); // $ExpectError + Complex128Array.from( 123 ); // $ExpectError + Complex128Array.from( null ); // $ExpectError + Complex128Array.from( {} ); // $ExpectError + + Complex128Array.from( true, clbk ); // $ExpectError + Complex128Array.from( false, clbk ); // $ExpectError + Complex128Array.from( 123, clbk ); // $ExpectError + Complex128Array.from( null, clbk ); // $ExpectError + Complex128Array.from( {}, clbk ); // $ExpectError + + Complex128Array.from( true, clbk, {} ); // $ExpectError + Complex128Array.from( false, clbk, {} ); // $ExpectError + Complex128Array.from( 123, clbk, {} ); // $ExpectError + Complex128Array.from( null, clbk, {} ); // $ExpectError + Complex128Array.from( {}, clbk, {} ); // $ExpectError +} + +// The compiler throws an error if the `from` method is provided a second argument which is not a function with a supported signature... +{ + Complex128Array.from( [ 1, 1 ], true ); // $ExpectError + Complex128Array.from( [ 1, 1 ], false ); // $ExpectError + Complex128Array.from( [ 1, 1 ], 123 ); // $ExpectError + Complex128Array.from( [ 1, 1 ], null ); // $ExpectError + Complex128Array.from( [ 1, 1 ], {} ); // $ExpectError +} + +// The `of` method returns a complex number array... +{ + Complex128Array.of( 1.0, 1.0, 1.0, 1.0 ); // $ExpectType Complex128Array +} + +// The compiler throws an error if the `of` method is provided arguments that are not numbers... +{ + Complex128Array.of( 'abc', 'def' ); // $ExpectError + Complex128Array.of( true, false ); // $ExpectError + Complex128Array.of( {}, [] ); // $ExpectError + Complex128Array.of( null, null ); // $ExpectError +} diff --git a/complex128/lib/from_array.js b/complex128/lib/from_array.js new file mode 100644 index 00000000..d9a8d1ab --- /dev/null +++ b/complex128/lib/from_array.js @@ -0,0 +1,61 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isComplexLike = require( '@stdlib/assert/is-complex-like' ); +var real = require( '@stdlib/complex/real' ); +var imag = require( '@stdlib/complex/imag' ); + + +// MAIN // + +/** +* Returns a strided array of real and imaginary components. +* +* @private +* @param {Float64Array} buf - output array +* @param {Array} arr - array containing complex numbers +* @returns {(Float64Array|null)} output array or null +*/ +function fromArray( buf, arr ) { + var len; + var v; + var i; + var j; + + len = arr.length; + j = 0; + for ( i = 0; i < len; i++ ) { + v = arr[ i ]; + if ( !isComplexLike( v ) ) { + return null; + } + buf[ j ] = real( v ); + buf[ j+1 ] = imag( v ); + j += 2; // stride + } + return buf; +} + + +// EXPORTS // + +module.exports = fromArray; diff --git a/complex128/lib/from_iterator.js b/complex128/lib/from_iterator.js new file mode 100644 index 00000000..9fe2dd6c --- /dev/null +++ b/complex128/lib/from_iterator.js @@ -0,0 +1,64 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isArrayLikeObject = require( '@stdlib/assert/is-array-like-object' ); +var isComplexLike = require( '@stdlib/assert/is-complex-like' ); +var real = require( '@stdlib/complex/real' ); +var imag = require( '@stdlib/complex/imag' ); + + +// MAIN // + +/** +* Returns an array of iterated values. +* +* @private +* @param {Object} it - iterator +* @returns {(Array|TypeError)} array or an error +*/ +function fromIterator( it ) { + var out; + var v; + + out = []; + while ( true ) { + v = it.next(); + if ( v.value ) { + if ( isArrayLikeObject( v.value ) ) { + out.push( v.value[0], v.value[1] ); + } else if ( isComplexLike( v.value ) ) { + out.push( real( v.value ), imag( v.value ) ); + } else { + return new TypeError( 'invalid argument. An iterator must return either a two-element array containing real and imaginary components or a complex number. Value: `'+v.value+'`.' ); + } + } + if ( v.done ) { + break; + } + } + return out; +} + + +// EXPORTS // + +module.exports = fromIterator; diff --git a/complex128/lib/from_iterator_map.js b/complex128/lib/from_iterator_map.js new file mode 100644 index 00000000..1a43aa29 --- /dev/null +++ b/complex128/lib/from_iterator_map.js @@ -0,0 +1,70 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isArrayLikeObject = require( '@stdlib/assert/is-array-like-object' ); +var isComplexLike = require( '@stdlib/assert/is-complex-like' ); +var real = require( '@stdlib/complex/real' ); +var imag = require( '@stdlib/complex/imag' ); + + +// MAIN // + +/** +* Returns an array of iterated values. +* +* @private +* @param {Object} it - iterator +* @param {Function} clbk - callback to invoke for each iterated value +* @param {*} thisArg - invocation context +* @returns {(Array|TypeError)} array or an error +*/ +function fromIteratorMap( it, clbk, thisArg ) { + var out; + var v; + var i; + + out = []; + i = 0; + while ( true ) { + v = it.next(); + i += 1; + if ( v.value ) { + v = clbk.call( thisArg, v.value, i ); + if ( isArrayLikeObject( v ) ) { + out.push( v[ 0 ], v[ 1 ] ); + } else if ( isComplexLike( v ) ) { + out.push( real( v ), imag( v ) ); + } else { + return new TypeError( 'invalid argument. Callback must return either a two-element array containing real and imaginary components or a complex number. Value: `'+v+'`.' ); + } + } + if ( v.done ) { + break; + } + } + return out; +} + + +// EXPORTS // + +module.exports = fromIteratorMap; diff --git a/complex128/lib/index.js b/complex128/lib/index.js new file mode 100644 index 00000000..c5b4b2b7 --- /dev/null +++ b/complex128/lib/index.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* 128-bit complex number array. +* +* @module @stdlib/array/complex128 +* +* @example +* var Complex128Array = require( '@stdlib/array/complex128' ); +* +* var arr = new Complex128Array(); +* // returns +* +* var len = arr.length; +* // returns 0 +* +* @example +* var Complex128Array = require( '@stdlib/array/complex128' ); +* +* var arr = new Complex128Array( 2 ); +* // returns +* +* var len = arr.length; +* // returns 2 +* +* @example +* var Complex128Array = require( '@stdlib/array/complex128' ); +* +* var arr = new Complex128Array( [ 1.0, -1.0 ] ); +* // returns +* +* var len = arr.length; +* // returns 1 +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* var Complex128Array = require( '@stdlib/array/complex128' ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = new Complex128Array( buf ); +* // returns +* +* var len = arr.length; +* // returns 2 +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* var Complex128Array = require( '@stdlib/array/complex128' ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = new Complex128Array( buf, 16 ); +* // returns +* +* var len = arr.length; +* // returns 2 +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* var Complex128Array = require( '@stdlib/array/complex128' ); +* +* var buf = new ArrayBuffer( 64 ); +* var arr = new Complex128Array( buf, 16, 2 ); +* // returns +* +* var len = arr.length; +* // returns 2 +*/ + +// MODULES // + +var Complex128Array = require( './main.js' ); + + +// EXPORTS // + +module.exports = Complex128Array; diff --git a/complex128/lib/main.js b/complex128/lib/main.js new file mode 100644 index 00000000..934453f6 --- /dev/null +++ b/complex128/lib/main.js @@ -0,0 +1,883 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* eslint-disable no-restricted-syntax */ + +'use strict'; + +// MODULES // + +var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; +var isArrayLikeObject = require( '@stdlib/assert/is-array-like-object' ); +var isCollection = require( '@stdlib/assert/is-collection' ); +var isArrayBuffer = require( '@stdlib/assert/is-arraybuffer' ); +var isObject = require( '@stdlib/assert/is-object' ); +var isArray = require( '@stdlib/assert/is-array' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var isComplexLike = require( '@stdlib/assert/is-complex-like' ); +var isEven = require( '@stdlib/math/base/assert/is-even' ); +var isInteger = require( '@stdlib/math/base/assert/is-integer' ); +var hasIteratorSymbolSupport = require( '@stdlib/assert/has-iterator-symbol-support' ); +var ITERATOR_SYMBOL = require( '@stdlib/symbol/iterator' ); +var defineProperty = require( '@stdlib/utils/define-property' ); +var Float64Array = require( '@stdlib/array/float64' ); +var Complex128 = require( '@stdlib/complex/float64' ); +var real = require( '@stdlib/complex/real' ); +var imag = require( '@stdlib/complex/imag' ); +var fromIterator = require( './from_iterator.js' ); +var fromIteratorMap = require( './from_iterator_map.js' ); +var fromArray = require( './from_array.js' ); + + +// VARIABLES // + +var BYTES_PER_ELEMENT = Float64Array.BYTES_PER_ELEMENT * 2; +var HAS_ITERATOR_SYMBOL = hasIteratorSymbolSupport(); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating if a value is a complex typed array. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating if a value is a complex typed array +*/ +function isComplexArray( value ) { + return ( + value instanceof Complex128Array || + ( + typeof value === 'object' && + value !== null && + ( + value.constructor.name === 'Complex64Array' || + value.constructor.name === 'Complex128Array' + ) && + typeof value._length === 'number' && // eslint-disable-line no-underscore-dangle + + // NOTE: we don't perform a more rigorous test here for a typed array for performance reasons, as robustly checking for a typed array instance could require walking the prototype tree and performing relatively expensive constructor checks... + typeof value._buffer === 'object' // eslint-disable-line no-underscore-dangle + ) + ); +} + +/** +* Returns a boolean indicating if a value is a complex typed array constructor. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating if a value is a complex typed array constructor +*/ +function isComplexArrayConstructor( value ) { + return ( + value === Complex128Array || + + // NOTE: weaker test in order to avoid a circular dependency with Complex64Array... + value.name === 'Complex64Array' + ); +} + + +// MAIN // + +/** +* 128-bit complex number array constructor. +* +* @constructor +* @param {(NonNegativeInteger|TypedArray|ArrayLikeObject|ArrayBuffer|Iterable)} [arg] - length, typed array, array-like object, or buffer +* @param {NonNegativeInteger} [byteOffset=0] - byte offset +* @param {NonNegativeInteger} [length] - view length +* @throws {RangeError} ArrayBuffer byte length must be a multiple of `16` +* @throws {RangeError} array-like object and typed array input arguments must have a length which is a multiple of two +* @throws {TypeError} if provided only a single argument, must provide a valid argument +* @throws {TypeError} byte offset must be a nonnegative integer +* @throws {RangeError} byte offset must be a multiple of `16` +* @throws {TypeError} view length must be a positive multiple of `16` +* @throws {RangeError} must provide sufficient memory to accommodate byte offset and view length requirements +* @throws {TypeError} an iterator must return either a two element array containing real and imaginary components or a complex number +* @returns {Complex128Array} complex number array +* +* @example +* var arr = new Complex128Array(); +* // returns +* +* var len = arr.length; +* // returns 0 +* +* @example +* var arr = new Complex128Array( 2 ); +* // returns +* +* var len = arr.length; +* // returns 2 +* +* @example +* var arr = new Complex128Array( [ 1.0, -1.0 ] ); +* // returns +* +* var len = arr.length; +* // returns 1 +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = new Complex128Array( buf ); +* // returns +* +* var len = arr.length; +* // returns 2 +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = new Complex128Array( buf, 16 ); +* // returns +* +* var len = arr.length; +* // returns 1 +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* +* var buf = new ArrayBuffer( 64 ); +* var arr = new Complex128Array( buf, 16, 2 ); +* // returns +* +* var len = arr.length; +* // returns 2 +*/ +function Complex128Array() { + var byteOffset; + var nargs; + var buf; + var len; + + nargs = arguments.length; + if ( !(this instanceof Complex128Array) ) { + if ( nargs === 0 ) { + return new Complex128Array(); + } + if ( nargs === 1 ) { + return new Complex128Array( arguments[0] ); + } + if ( nargs === 2 ) { + return new Complex128Array( arguments[0], arguments[1] ); + } + return new Complex128Array( arguments[0], arguments[1], arguments[2] ); + } + // Create the underlying data buffer... + if ( nargs === 0 ) { + buf = new Float64Array( 0 ); // backward-compatibility + } else if ( nargs === 1 ) { + if ( isNonNegativeInteger( arguments[0] ) ) { + buf = new Float64Array( arguments[0]*2 ); + } else if ( isCollection( arguments[0] ) ) { + buf = arguments[ 0 ]; + len = buf.length; + + // If provided a "generic" array, peak at the first value, and, if the value is a complex number, try to process as an array of complex numbers, falling back to "normal" typed array initialization if we fail and ensuring consistency if the first value had not been a complex number... + if ( len && isArray( buf ) && isComplexLike( buf[0] ) ) { + buf = fromArray( new Float64Array( len*2 ), buf ); + if ( buf === null ) { + // We failed and we are now forced to allocate a new array :-( + if ( !isEven( len ) ) { + throw new RangeError( 'invalid argument. Array-like object input arguments must have a length which is a multiple of two. Length: `'+len+'`.' ); + } + // We failed, so fall back to directly setting values... + buf = new Float64Array( arguments[0] ); + } + } else { + if ( !isEven( len ) ) { + throw new RangeError( 'invalid argument. Array-like object and typed array input arguments must have a length which is a multiple of two. Length: `'+len+'`.' ); + } + buf = new Float64Array( buf ); + } + } else if ( isArrayBuffer( arguments[0] ) ) { + buf = arguments[ 0 ]; + if ( !isInteger( buf.byteLength/BYTES_PER_ELEMENT ) ) { + throw new RangeError( 'invalid argument. ArrayBuffer byte length must be a multiple of '+BYTES_PER_ELEMENT+'. Byte length: `'+buf.byteLength+'`.' ); + } + buf = new Float64Array( buf ); + } else if ( isObject( arguments[0] ) ) { + buf = arguments[ 0 ]; + if ( HAS_ITERATOR_SYMBOL === false ) { + throw new TypeError( 'invalid argument. Environment lacks Symbol.iterator support. Must provide a length, ArrayBuffer, typed array, or array-like object. Value: `'+buf+'`.' ); + } + if ( !isFunction( buf[ ITERATOR_SYMBOL ] ) ) { + throw new TypeError( 'invalid argument. Must provide a length, ArrayBuffer, typed array, array-like object, or an iterable. Value: `'+buf+'`.' ); + } + buf = buf[ ITERATOR_SYMBOL ](); + if ( !isFunction( buf.next ) ) { + throw new TypeError( 'invalid argument. Must provide a length, ArrayBuffer, typed array, array-like object, or an iterable.' ); + } + buf = fromIterator( buf ); + if ( buf instanceof Error ) { + throw buf; + } + buf = new Float64Array( buf ); + } else { + throw new TypeError( 'invalid argument. Must provide a length, ArrayBuffer, typed array, array-like object, or an iterable. Value: `'+arguments[0]+'`.' ); + } + } else { + buf = arguments[ 0 ]; + if ( !isArrayBuffer( buf ) ) { + throw new TypeError( 'invalid argument. First argument must be an array buffer. Value: `'+buf+'`.' ); + } + byteOffset = arguments[ 1 ]; + if ( !isNonNegativeInteger( byteOffset ) ) { + throw new TypeError( 'invalid argument. Byte offset must be a nonnegative integer. Value: `'+byteOffset+'`.' ); + } + if ( !isInteger( byteOffset/BYTES_PER_ELEMENT ) ) { + throw new RangeError( 'invalid argument. Byte offset must be a multiple of '+BYTES_PER_ELEMENT+'. Value: `'+byteOffset+'`.' ); + } + if ( nargs === 2 ) { + len = buf.byteLength - byteOffset; + if ( !isInteger( len/BYTES_PER_ELEMENT ) ) { + throw new RangeError( 'invalid arguments. ArrayBuffer view byte length must be a multiple of '+BYTES_PER_ELEMENT+'. View byte length: `'+len+'`.' ); + } + buf = new Float64Array( buf, byteOffset ); + } else { + len = arguments[ 2 ]; + if ( !isNonNegativeInteger( len ) ) { + throw new TypeError( 'invalid argument. Length must be a nonnegative integer. Value: `'+len+'`.' ); + } + if ( (len*BYTES_PER_ELEMENT) > (buf.byteLength-byteOffset) ) { + throw new RangeError( 'invalid arguments. ArrayBuffer has insufficient capacity. Either decrease the array length or provide a bigger buffer. Minimum capacity: `'+(len*BYTES_PER_ELEMENT)+'`.' ); + } + buf = new Float64Array( buf, byteOffset, len*2 ); + } + } + defineProperty( this, '_buffer', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': buf + }); + defineProperty( this, '_length', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': buf.length / 2 + }); + + return this; +} + +/** +* Size (in bytes) of each array element. +* +* @name BYTES_PER_ELEMENT +* @memberof Complex128Array +* @type {PositiveInteger} +* @default 16 +* +* @example +* var nbytes = Complex128Array.BYTES_PER_ELEMENT; +* // returns 16 +*/ +defineProperty( Complex128Array, 'BYTES_PER_ELEMENT', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': BYTES_PER_ELEMENT +}); + +/** +* Constructor name. +* +* @name name +* @memberof Complex128Array +* @type {string} +* @default 'Complex128Array' +* +* @example +* var name = Complex128Array.name; +* // returns 'Complex128Array' +*/ +defineProperty( Complex128Array, 'name', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': 'Complex128Array' +}); + +/** +* Creates a new 128-bit complex number array from an array-like object or an iterable. +* +* @name from +* @memberof Complex128Array +* @type {Function} +* @param {(ArrayLikeObject|Object)} src - array-like object or iterable +* @param {Function} [clbk] - callback to invoke for each source element +* @param {*} [thisArg] - context +* @throws {TypeError} `this` context must be a constructor +* @throws {TypeError} `this` must be a complex number array +* @throws {TypeError} first argument must be an array-like object or an iterable +* @throws {TypeError} second argument must be a function +* @throws {RangeError} array-like objects must have a length which is a multiple of two +* @throws {TypeError} an iterator must return either a two element array containing real and imaginary components or a complex number +* @throws {TypeError} when provided an iterator, a callback must return either a two element array containing real and imaginary components or a complex number +* @returns {Complex128Array} 128-bit complex number array +* +* @example +* var arr = Complex128Array.from( [ 1.0, -1.0 ] ); +* // returns +* +* var len = arr.length; +* // returns 1 +* +* @example +* var Complex128 = require( '@stdlib/complex/float64' ); +* +* var arr = Complex128Array.from( [ new Complex128( 1.0, 1.0 ) ] ); +* // returns +* +* var len = arr.length; +* // returns 1 +* +* @example +* var Complex128 = require( '@stdlib/complex/float64' ); +* var real = require( '@stdlib/complex/real' ); +* var imag = require( '@stdlib/complex/imag' ); +* +* function clbk( v ) { +* return new Complex128( real(v)*2.0, imag(v)*2.0 ); +* } +* +* var arr = Complex128Array.from( [ new Complex128( 1.0, 1.0 ) ], clbk ); +* // returns +* +* var len = arr.length; +* // returns 1 +*/ +defineProperty( Complex128Array, 'from', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': function from( src ) { + var thisArg; + var nargs; + var clbk; + var out; + var buf; + var tmp; + var len; + var flg; + var v; + var i; + var j; + if ( !isFunction( this ) ) { + throw new TypeError( 'invalid invocation. `this` context must be a constructor.' ); + } + if ( !isComplexArrayConstructor( this ) ) { + throw new TypeError( 'invalid invocation. `this` is not a complex number array.' ); + } + nargs = arguments.length; + if ( nargs > 1 ) { + clbk = arguments[ 1 ]; + if ( !isFunction( clbk ) ) { + throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+clbk+'`.' ); + } + if ( nargs > 2 ) { + thisArg = arguments[ 2 ]; + } + } + if ( isCollection( src ) ) { + if ( clbk ) { + // Note: array contents affect how we iterate over a provided data source. If only complex numbers, we can extract real and imaginary components. Otherwise, we assume a strided array where real and imaginary components are interleaved. In the former case, we expect a callback to return real and imaginary components (possibly as a complex number). In the latter case, we expect a callback to return *either* a real or imaginary component. + + // Detect whether we've been provided an array of complex numbers... + len = src.length; + for ( i = 0; i < len; i++ ) { + if ( !isComplexLike( src[ i ] ) ) { + flg = true; + break; + } + } + // If an array does not contain only complex numbers, then we assume interleaved real and imaginary components... + if ( flg ) { + if ( !isEven( len ) ) { + throw new RangeError( 'invalid argument. First argument must have a length which is a multiple of two. Length: `'+len+'`.' ); + } + out = new this( len/2 ); + buf = out._buffer; // eslint-disable-line no-underscore-dangle + for ( i = 0; i < len; i++ ) { + buf[ i ] = clbk.call( thisArg, src[ i ], i ); + } + } + // If an array contains only complex numbers, then we need to extract real and imaginary components... + else { + out = new this( len ); + buf = out._buffer; // eslint-disable-line no-underscore-dangle + j = 0; + for ( i = 0; i < len; i++ ) { + v = clbk.call( thisArg, src[ i ], i ); + if ( isComplexLike( v ) ) { + buf[ j ] = real( v ); + buf[ j+1 ] = imag( v ); + } else if ( isArrayLikeObject( v ) ) { + buf[ j ] = v[ 0 ]; + buf[ j+1 ] = v[ 1 ]; + } else { + throw new TypeError( 'invalid argument. Callback must return either a two-element array containing real and imaginary components or a complex number. Value: `'+v+'`.' ); + } + j += 2; // stride + } + } + } else { + out = new this( src ); + } + } else if ( isObject( src ) && HAS_ITERATOR_SYMBOL && isFunction( src[ ITERATOR_SYMBOL ] ) ) { // eslint-disable-line max-len + buf = src[ ITERATOR_SYMBOL ](); + if ( !isFunction( buf.next ) ) { + throw new TypeError( 'invalid argument. First argument must be an array-like object or an iterable.' ); + } + if ( clbk ) { + tmp = fromIteratorMap( buf, clbk, thisArg ); + } else { + tmp = fromIterator( buf ); + } + if ( tmp instanceof Error ) { + throw tmp; + } + len = tmp.length / 2; + out = new this( len ); + buf = out._buffer; // eslint-disable-line no-underscore-dangle + for ( i = 0; i < len; i++ ) { + buf[ i ] = tmp[ i ]; + } + } else { + throw new TypeError( 'invalid argument. First argument must be an array-like object or an iterable. Value: `'+src+'`.' ); + } + return out; + } +}); + +/** +* Creates a new 128-bit complex number array from a variable number of arguments. +* +* @name of +* @memberof Complex128Array +* @type {Function} +* @param {...*} element - array elements +* @throws {TypeError} `this` context must be a constructor +* @throws {TypeError} `this` must be a complex number array +* @returns {Complex128Array} 128-bit complex number array +* +* @example +* var arr = Complex128Array.of( 1.0, 1.0, 1.0, 1.0 ); +* // returns +* +* var len = arr.length; +* // returns 2 +*/ +defineProperty( Complex128Array, 'of', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': function of() { + var args; + var i; + if ( !isFunction( this ) ) { + throw new TypeError( 'invalid invocation. `this` context must be a constructor.' ); + } + if ( !isComplexArrayConstructor( this ) ) { + throw new TypeError( 'invalid invocation. `this` is not a complex number array.' ); + } + args = []; + for ( i = 0; i < arguments.length; i++ ) { + args.push( arguments[ i ] ); + } + return new this( args ); + } +}); + +/** +* Pointer to the underlying data buffer. +* +* @name buffer +* @memberof Complex128Array.prototype +* @type {ArrayBuffer} +* +* @example +* var arr = new Complex128Array( 10 ); +* +* var buf = arr.buffer; +* // returns +*/ +defineProperty( Complex128Array.prototype, 'buffer', { + 'configurable': false, + 'enumerable': false, + 'get': function get() { + return this._buffer.buffer; + } +}); + +/** +* Size (in bytes) of the array. +* +* @name byteLength +* @memberof Complex128Array.prototype +* @type {NonNegativeInteger} +* +* @example +* var arr = new Complex128Array( 10 ); +* +* var byteLength = arr.byteLength; +* // returns 160 +*/ +defineProperty( Complex128Array.prototype, 'byteLength', { + 'configurable': false, + 'enumerable': false, + 'get': function get() { + return this._buffer.byteLength; + } +}); + +/** +* Offset (in bytes) of the array from the start of its underlying `ArrayBuffer`. +* +* @name byteOffset +* @memberof Complex128Array.prototype +* @type {NonNegativeInteger} +* +* @example +* var arr = new Complex128Array( 10 ); +* +* var byteOffset = arr.byteOffset; +* // returns 0 +*/ +defineProperty( Complex128Array.prototype, 'byteOffset', { + 'configurable': false, + 'enumerable': false, + 'get': function get() { + return this._buffer.byteOffset; + } +}); + +/** +* Size (in bytes) of each array element. +* +* @name BYTES_PER_ELEMENT +* @memberof Complex128Array.prototype +* @type {PositiveInteger} +* @default 16 +* +* @example +* var arr = new Complex128Array( 10 ); +* +* var nbytes = arr.BYTES_PER_ELEMENT; +* // returns 16 +*/ +defineProperty( Complex128Array.prototype, 'BYTES_PER_ELEMENT', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': Complex128Array.BYTES_PER_ELEMENT +}); + +/** +* Returns an array element. +* +* @name get +* @memberof Complex128Array.prototype +* @type {Function} +* @param {ArrayLikeObject} [out] - output array +* @param {NonNegativeInteger} i - element index +* @throws {TypeError} `this` must be a complex number array +* @throws {TypeError} index argument must be a nonnegative integer +* @throws {TypeError} output argument must be an array-like object +* @returns {(Complex128|ArrayLikeObject|void)} array element +* +* @example +* var arr = new Complex128Array( 10 ); +* +* var z = arr.get( 0 ); +* // returns +* +* arr.set( [ 1.0, -1.0 ], 0 ); +* +* z = arr.get( [ 0.0, 0.0 ], 0 ); +* // returns [ 1.0, -1.0 ] +* +* z = arr.get( 100 ); +* // returns undefined +*/ +defineProperty( Complex128Array.prototype, 'get', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': function get( i ) { + var idx; + var out; + var buf; + + if ( !isComplexArray( this ) ) { + throw new TypeError( 'invalid invocation. `this` is not a complex number array.' ); + } + buf = this._buffer; + if ( arguments.length > 1 ) { + idx = arguments[ 1 ]; + out = i; + if ( !isArrayLikeObject( out ) || out.length < 2 ) { + throw new TypeError( 'invalid argument. Output argument must be an array-like object. Value: `'+out+'`.' ); + } + } else { + idx = i; + } + if ( !isNonNegativeInteger( idx ) ) { + throw new TypeError( 'invalid argument. Index argument must be a nonnegative integer. Value: `'+idx+'`.' ); + } + if ( idx >= this._length ) { + return; + } + idx *= 2; + if ( out ) { + out[ 0 ] = buf[ idx ]; + out[ 1 ] = buf[ idx+1 ]; + return out; + } + return new Complex128( buf[ idx ], buf[ idx+1 ] ); + } +}); + +/** +* Number of array elements. +* +* @name length +* @memberof Complex128Array.prototype +* @type {NonNegativeInteger} +* +* @example +* var arr = new Complex128Array( 10 ); +* +* var len = arr.length; +* // returns 10 +*/ +defineProperty( Complex128Array.prototype, 'length', { + 'configurable': false, + 'enumerable': false, + 'get': function get() { + return this._length; + } +}); + +/** +* Sets an array element. +* +* ## Notes +* +* - When provided a typed array, real or complex, we must check whether the source array shares the same buffer as the target array and whether the underlying memory overlaps. In particular, we are concerned with the following scenario: +* +* ```text +* buf: --------------------- +* src: --------------------- +* ``` +* +* In the above, as we copy values from `src`, we will overwrite values in the `src` view, resulting in duplicated values copied into the end of `buf`, which is not intended. Hence, to avoid overwriting source values, we must **copy** source values to a temporary array. +* +* In the other overlapping scenario, +* +* ```text +* buf: --------------------- +* src: --------------------- +* ``` +* +* by the time we begin copying into the overlapping region, we are copying from the end of `src`, a non-overlapping region, which means we don't run the risk of copying copied values, rather than the original `src` values as intended. +* +* +* @name set +* @memberof Complex128Array.prototype +* @type {Function} +* @param {(Collection|Complex|ComplexArray)} value - value(s) +* @param {NonNegativeInteger} [i=0] - element index at which to start writing values +* @throws {TypeError} `this` must be a complex number array +* @throws {TypeError} first argument must be either a complex number, an array-like object, or a complex number array +* @throws {TypeError} index argument must be a nonnegative integer +* @throws {RangeError} array-like objects must have a length which is a multiple of two +* @throws {RangeError} index argument is out-of-bounds +* @throws {RangeError} target array lacks sufficient storage to accommodate source values +* @returns {void} +* +* @example +* var real = require( '@stdlib/complex/real' ); +* var imag = require( '@stdlib/complex/imag' ); +* +* var arr = new Complex128Array( 10 ); +* +* var z = arr.get( 0 ); +* // returns +* +* var re = real( z ); +* // returns 0.0 +* +* var im = imag( z ); +* // returns 0.0 +* +* arr.set( [ 1.0, -1.0 ], 0 ); +* +* z = arr.get( 0 ); +* // returns +* +* re = real( z ); +* // returns 1.0 +* +* im = imag( z ); +* // returns -1.0 +*/ +defineProperty( Complex128Array.prototype, 'set', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': function set( value ) { + /* eslint-disable no-underscore-dangle */ + var dbuf; + var idx; + var buf; + var tmp; + var flg; + var N; + var v; + var i; + var j; + if ( !isComplexArray( this ) ) { + throw new TypeError( 'invalid invocation. `this` is not a complex number array.' ); + } + buf = this._buffer; + if ( arguments.length > 1 ) { + idx = arguments[ 1 ]; + if ( !isNonNegativeInteger( idx ) ) { + throw new TypeError( 'invalid argument. Index argument must be a nonnegative integer. Value: `'+idx+'`.' ); + } + } else { + idx = 0; + } + if ( isComplexLike( value ) ) { + if ( idx >= this._length ) { + throw new RangeError( 'invalid argument. Index argument is out-of-bounds. Value: `'+idx+'`.' ); + } + idx *= 2; + buf[ idx ] = real( value ); + buf[ idx+1 ] = imag( value ); + return; + } + if ( isComplexArray( value ) ) { + N = value._length; + if ( idx+N > this._length ) { + throw new RangeError( 'invalid arguments. Target array lacks sufficient storage to accommodate source values.' ); + } + dbuf = value._buffer; + + // Check for overlapping memory... + j = buf.byteOffset + (idx*BYTES_PER_ELEMENT); + if ( + dbuf.buffer === buf.buffer && + ( + dbuf.byteOffset < j && + dbuf.byteOffset+dbuf.byteLength > j + ) + ) { + // We need to copy source values... + tmp = new Float64Array( dbuf.length ); + for ( i = 0; i < dbuf.length; i++ ) { + tmp[ i ] = dbuf[ i ]; + } + dbuf = tmp; + } + idx *= 2; + j = 0; + for ( i = 0; i < N; i++ ) { + buf[ idx ] = dbuf[ j ]; + buf[ idx+1 ] = dbuf[ j+1 ]; + idx += 2; // stride + j += 2; // stride + } + return; + } + if ( isCollection( value ) ) { + // Detect whether we've been provided an array of complex numbers... + N = value.length; + for ( i = 0; i < N; i++ ) { + if ( !isComplexLike( value[ i ] ) ) { + flg = true; + break; + } + } + // If an array does not contain only complex numbers, then we assume interleaved real and imaginary components... + if ( flg ) { + if ( !isEven( N ) ) { + throw new RangeError( 'invalid argument. Array-like object arguments must have a length which is a multiple of two. Length: `'+N+'`.' ); + } + if ( idx+(N/2) > this._length ) { + throw new RangeError( 'invalid arguments. Target array lacks sufficient storage to accommodate source values.' ); + } + dbuf = value; + + // Check for overlapping memory... + j = buf.byteOffset + (idx*BYTES_PER_ELEMENT); + if ( + dbuf.buffer === buf.buffer && + ( + dbuf.byteOffset < j && + dbuf.byteOffset+dbuf.byteLength > j + ) + ) { + // We need to copy source values... + tmp = new Float64Array( N ); + for ( i = 0; i < N; i++ ) { + tmp[ i ] = dbuf[ i ]; + } + dbuf = tmp; + } + idx *= 2; + N /= 2; + j = 0; + for ( i = 0; i < N; i++ ) { + buf[ idx ] = dbuf[ j ]; + buf[ idx+1 ] = dbuf[ j+1 ]; + idx += 2; // stride + j += 2; // stride + } + return; + } + // If an array contains only complex numbers, then we need to extract real and imaginary components... + if ( idx+N > this._length ) { + throw new RangeError( 'invalid arguments. Target array lacks sufficient storage to accommodate source values.' ); + } + idx *= 2; + for ( i = 0; i < N; i++ ) { + v = value[ i ]; + buf[ idx ] = real( v ); + buf[ idx+1 ] = imag( v ); + idx += 2; // stride + } + return; + } + throw new TypeError( 'invalid argument. First argument must be either a complex number, an array-like object, or a complex number array. Value: `'+value+'`.' ); + + /* eslint-enable no-underscore-dangle */ + } +}); + + +// EXPORTS // + +module.exports = Complex128Array; diff --git a/complex128/package.json b/complex128/package.json new file mode 100644 index 00000000..cbde2f21 --- /dev/null +++ b/complex128/package.json @@ -0,0 +1,73 @@ +{ + "name": "@stdlib/array/complex128", + "version": "0.0.0", + "description": "Complex128Array.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structure", + "array", + "typed", + "typed array", + "typed-array", + "complex128array", + "complex128", + "complex", + "cmplx", + "real", + "imaginary", + "imag", + "double", + "float64", + "double-precision", + "ieee754" + ] +} diff --git a/complex64/README.md b/complex64/README.md new file mode 100644 index 00000000..29ebc321 --- /dev/null +++ b/complex64/README.md @@ -0,0 +1,902 @@ + + +# Complex64Array + +> 64-bit complex number array. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var Complex64Array = require( '@stdlib/array/complex64' ); +``` + + + +#### Complex64Array() + +Creates a 64-bit complex number array. + +```javascript +var arr = new Complex64Array(); +// returns +``` + +#### Complex64Array( length ) + +Creates a 64-bit complex number array having a specified `length`. + +```javascript +var arr = new Complex64Array( 10 ); +// returns + +var len = arr.length; +// returns 10 +``` + +#### Complex64Array( typedarray ) + +Creates a 64-bit complex number array from a [typed array][@stdlib/array/typed] containing interleaves real and imaginary components. + +```javascript +var Float32Array = require( '@stdlib/array/float32' ); + +var buf = new Float32Array( [ 1.0, -1.0, 2.0, -2.0 ] ); // [ re, im, re, im ] +// returns [ 1.0, -1.0, 2.0, -2.0 ] + +var arr = new Complex64Array( buf ); +// returns + +var len = arr.length; +// returns 2 +``` + +#### Complex64Array( obj ) + +Creates a 64-bit complex number array from an array-like `object` or iterable. + +```javascript +var Complex64 = require( '@stdlib/complex/float32' ); + +// From an array of interleaved real and imaginary components: +var arr1 = new Complex64Array( [ 1.0, -1.0, 2.0, -2.0 ] ); +// returns + +var len = arr1.length; +// returns 2 + +// From an array containing complex numbers: +var buf = [ new Complex64( 1.0, -1.0 ), new Complex64( 2.0, -2.0 ) ]; +var arr2 = new Complex64Array( buf ); + +len = arr2.length; +// returns 2 +``` + +#### Complex64Array( buffer\[, byteOffset\[, length]] ) + +Returns a 64-bit complex number array view of an [`ArrayBuffer`][@stdlib/array/buffer]. + +```javascript +var ArrayBuffer = require( '@stdlib/array/buffer' ); +var buf = new ArrayBuffer( 240 ); + +var arr1 = new Complex64Array( buf ); +// returns + +var len = arr1.length; +// returns 30 + +var arr2 = new Complex64Array( buf, 8 ); +// returns + +len = arr2.length; +// returns 29 + +var arr3 = new Complex64Array( buf, 8, 20 ); +// returns + +len = arr3.length; +// returns 20 +``` + +* * * + +### Properties + + + +#### Complex64Array.BYTES_PER_ELEMENT + +Static property returning the size (in bytes) of each array element. + +```javascript +var nbytes = Complex64Array.BYTES_PER_ELEMENT; +// returns 8 +``` + + + +#### Complex64Array.name + +Static property returning the constructor name. + +```javascript +var str = Complex64Array.name; +// returns 'Complex64Array' +``` + + + +#### Complex64Array.prototype.buffer + +Pointer to the underlying data buffer. + +```javascript +var arr = new Complex64Array( 2 ); +// returns + +var buf = arr.buffer; +// returns +``` + + + +#### Complex64Array.prototype.byteLength + +Size (in bytes) of the array. + +```javascript +var arr = new Complex64Array( 10 ); +// returns + +var nbytes = arr.byteLength; +// returns 80 +``` + + + +#### Complex64Array.prototype.byteOffset + +Offset (in bytes) of the array from the start of its underlying `ArrayBuffer`. + +```javascript +var ArrayBuffer = require( '@stdlib/array/buffer' ); + +var arr = new Complex64Array( 10 ); +// returns + +var offset = arr.byteOffset; +// returns 0 + +var buf = new ArrayBuffer( 240 ); +arr = new Complex64Array( buf, 64 ); +// returns + +offset = arr.byteOffset; +// returns 64 +``` + + + +#### Complex64Array.prototype.BYTES_PER_ELEMENT + +Size (in bytes) of each array element. + +```javascript +var arr = new Complex64Array( 10 ); +// returns + +var nbytes = arr.BYTES_PER_ELEMENT; +// returns 8 +``` + + + +#### Complex64Array.prototype.length + +Number of array elements. + +```javascript +var arr = new Complex64Array( 10 ); +// returns + +var len = arr.length; +// returns 10 +``` + +* * * + +### Methods + + + +#### Complex64Array.from( src\[, clbk\[, thisArg]] ) + +Creates a new 64-bit complex number array from an array-like `object` or an iterable. + +```javascript +var Complex64 = require( '@stdlib/complex/float32' ); + +// Create an array from interleaved real and imaginary components: +var arr = Complex64Array.from( [ 1.0, -1.0 ] ); +// returns + +var len = arr.length; +// returns 1 + +// Create an array from an array of complex numbers: +arr = Complex64Array.from( [ new Complex64( 1.0, -1.0 ) ] ); +// returns + +len = arr.length; +// returns 1 +``` + +The iterator returned by an iterable must return either a complex number or an array-like `object` containing a real and imaginary component. + +```javascript +var ITERATOR_SYMBOL = require( '@stdlib/symbol/iterator' ); +var Float32Array = require( '@stdlib/array/float32' ); +var real = require( '@stdlib/complex/real' ); +var imag = require( '@stdlib/complex/imag' ); + +var iter; +var arr; +var len; +var re; +var im; +var z; + +// Define a function which returns an iterator protocol-compliant object... +function iterable() { + var buf = new Float32Array( 2 ); + var i = 0; + return { + 'next': next + }; + + function next() { + i += 1; + if ( i < 3 ) { + // Reuse allocated memory... + buf[ 0 ] = i; + buf[ 1 ] = -i; + return { + 'value': buf + }; + } + return { + 'done': true + }; + } +} + +if ( ITERATOR_SYMBOL === null ) { + console.error( 'Environment does not support iterables.' ); +} else { + // Create an iterable: + iter = {}; + iter[ ITERATOR_SYMBOL ] = iterable; + + // Generate a complex number array: + arr = Complex64Array.from( iter ); + // returns + + len = arr.length; + // returns 2 + + z = arr.get( 0 ); + // returns + + re = real( z ); + // returns 1.0 + + im = imag( z ); + // returns -1.0 +} +``` + +To invoke a function for each `src` value, provide a callback function. If `src` is an iterable or an array-like `object` containing complex numbers, the callback must return either a complex number + +```javascript +var Complex64 = require( '@stdlib/complex/float32' ); +var real = require( '@stdlib/complex/real' ); +var imag = require( '@stdlib/complex/imag' ); + +function map( z ) { + return new Complex64( real(z)*2.0, imag(z)*2.0 ); +} + +// Create a source array: +var src = [ new Complex64( 1.0, -1.0 ) ]; + +// Create a new complex number array by scaling the source array: +var arr = Complex64Array.from( src, map ); +// returns + +var len = arr.length; +// returns 1 + +var z = arr.get( 0 ); +// returns + +var re = real( z ); +// returns 2.0 + +var im = imag( z ); +// returns -2.0 +``` + +or an array-like `object` containing real and imaginary components + +```javascript +var Float32Array = require( '@stdlib/array/float32' ); +var Complex64 = require( '@stdlib/complex/float32' ); +var real = require( '@stdlib/complex/real' ); +var imag = require( '@stdlib/complex/imag' ); + +// Return a callback which reuses allocated memory... +function mapFcn() { + var buf = new Float32Array( 2 ); + return map; + + function map( z ) { + buf[ 0 ] = real( z ) * 2.0; + buf[ 1 ] = imag( z ) * 2.0; + return buf; + } +} + +// Create a source array: +var src = [ new Complex64( 1.0, -1.0 ), new Complex64( 2.0, -2.0 ) ]; + +// Create a new complex number array by scaling the source array: +var arr = Complex64Array.from( src, mapFcn() ); +// returns + +var len = arr.length; +// returns 2 + +var z = arr.get( 0 ); +// returns + +var re = real( z ); +// returns 2.0 + +var im = imag( z ); +// returns -2.0 + +z = arr.get( 1 ); +// returns + +re = real( z ); +// returns 4.0 + +im = imag( z ); +// returns -4.0 +``` + +If `src` is an array-like `object` containing interleaved real and imaginary components, the callback is invoked for each component and should return the transformed component value. + +```javascript +var Float32Array = require( '@stdlib/array/float32' ); +var Complex64 = require( '@stdlib/complex/float32' ); +var real = require( '@stdlib/complex/real' ); +var imag = require( '@stdlib/complex/imag' ); + +function map( v ) { + return v * 2.0; +} + +// Create a source array: +var src = new Float32Array( [ 1.0, -1.0 ] ); + +// Create a new complex number array by scaling the source array: +var arr = Complex64Array.from( src, map ); +// returns + +var len = arr.length; +// returns 1 + +var z = arr.get( 0 ); +// returns + +var re = real( z ); +// returns 2.0 + +var im = imag( z ); +// returns -2.0 +``` + +A callback function is provided two arguments: + +- `value`: source value +- `index`: source index + +To set the callback execution context, provide a `thisArg`. + +```javascript +var Complex64 = require( '@stdlib/complex/float32' ); +var real = require( '@stdlib/complex/real' ); +var imag = require( '@stdlib/complex/imag' ); + +function map( z ) { + this.count += 1; + return new Complex64( real(z)*2.0, imag(z)*2.0 ); +} + +// Create a source array: +var src = [ new Complex64( 1.0, -1.0 ), new Complex64( 1.0, -1.0 ) ]; + +// Define an execution context: +var ctx = { + 'count': 0 +}; + +// Create a new complex number array by scaling the source array: +var arr = Complex64Array.from( src, map, ctx ); +// returns + +var len = arr.length; +// returns 2 + +var n = ctx.count; +// returns 2 +``` + + + +#### Complex64Array.of( element0\[, element1\[, ...elementN]] ) + +Creates a new 64-bit complex number array from a variable number of arguments. + +```javascript +var Complex64 = require( '@stdlib/complex/float32' ); + +var arr = Complex64Array.of( 1.0, -1.0, 2.0, -2.0 ); +// returns + +var len = arr.length; +// returns 2 + +var z1 = new Complex64( 1.0, -1.0 ); +var z2 = new Complex64( 2.0, -2.0 ); + +arr = Complex64Array.of( z1, z2 ); +// returns + +len = arr.length; +// returns 2 +``` + + + +#### Complex64Array.prototype.copyWithin( target, start\[, end] ) + +Copies a sequence of elements within the array starting at `start` and ending at `end` (non-inclusive) to the position starting at `target`. + +```javascript +var Complex64 = require( '@stdlib/complex/float32' ); + +var arr = new Complex64Array( 4 ); + +// Set the array elements: +arr.set( new Complex64( 1.0, -1.0 ), 0 ); +arr.set( new Complex64( 2.0, -2.0 ), 1 ); +arr.set( new Complex64( 3.0, -3.0 ), 2 ); +arr.set( new Complex64( 4.0, -4.0 ), 3 ); + +// Get the first array element: +var z = arr.get( [ 0.0, 0.0 ], 0 ); +// returns [ 1.0, -1.0 ] + +// Get the second array element: +z = arr.get( [ 0.0, 0.0 ], 1 ); +// returns [ 2.0, -2.0 ] + +// Copy the last two elements to the first two elements: +arr.copyWithin( 0, 2 ); + +// Get the first array element: +z = arr.get( [ 0.0, 0.0 ], 0 ); +// returns [ 3.0, -3.0 ] + +// Get the second array element: +z = arr.get( [ 0.0, 0.0 ], 1 ); +// returns [ 4.0, -4.0 ] +``` + +By default, `end` equals the number of array elements (i.e., one more than the last array index). To limit the sequence length, provide an `end` argument. + +```javascript +var Complex64 = require( '@stdlib/complex/float32' ); + +var arr = new Complex64Array( 4 ); + +// Set the array elements: +arr.set( new Complex64( 1.0, -1.0 ), 0 ); +arr.set( new Complex64( 2.0, -2.0 ), 1 ); +arr.set( new Complex64( 3.0, -3.0 ), 2 ); +arr.set( new Complex64( 4.0, -4.0 ), 3 ); + +// Get the third array element: +var z = arr.get( [ 0.0, 0.0 ], 2 ); +// returns [ 3.0, -3.0 ] + +// Get the last array element: +z = arr.get( [ 0.0, 0.0 ], 3 ); +// returns [ 4.0, -4.0 ] + +// Copy the first two elements to the last two elements: +arr.copyWithin( 2, 0, 2 ); + +// Get the third array element: +z = arr.get( [ 0.0, 0.0 ], 2 ); +// returns [ 1.0, -1.0 ] + +// Get the last array element: +z = arr.get( [ 0.0, 0.0 ], 3 ); +// returns [ 2.0, -2.0 ] +``` + +When a `target`, `start`, and/or `end` index is negative, the respective index is determined relative to the last array element. The following example achieves the same behavior as the previous example: + +```javascript +var Complex64 = require( '@stdlib/complex/float32' ); + +var arr = new Complex64Array( 4 ); + +// Set the array elements: +arr.set( new Complex64( 1.0, -1.0 ), 0 ); +arr.set( new Complex64( 2.0, -2.0 ), 1 ); +arr.set( new Complex64( 3.0, -3.0 ), 2 ); +arr.set( new Complex64( 4.0, -4.0 ), 3 ); + +// Get the third array element: +var z = arr.get( [ 0.0, 0.0 ], 2 ); +// returns [ 3.0, -3.0 ] + +// Get the last array element: +z = arr.get( [ 0.0, 0.0 ], 3 ); +// returns [ 4.0, -4.0 ] + +// Copy the first two elements to the last two elements using negative indices: +arr.copyWithin( -2, -4, -2 ); + +// Get the third array element: +z = arr.get( [ 0.0, 0.0 ], 2 ); +// returns [ 1.0, -1.0 ] + +// Get the last array element: +z = arr.get( [ 0.0, 0.0 ], 3 ); +// returns [ 2.0, -2.0 ] +``` + + + +#### Complex64Array.prototype.entries() + +Returns an iterator for iterating over array key-value pairs. + +```javascript +var Complex64 = require( '@stdlib/complex/float32' ); +var real = require( '@stdlib/complex/real' ); +var imag = require( '@stdlib/complex/imag' ); + +var arr = [ + new Complex64( 1.0, -1.0 ), + new Complex64( 2.0, -2.0 ), + new Complex64( 3.0, -3.0 ) +]; +arr = new Complex64Array( arr ); + +// Create an iterator: +var it = arr.entries(); + +// Iterate over the key-value pairs... +var v = it.next().value; +// returns [ 0, ] + +var re = real( v[ 1 ] ); +// returns 1.0 + +var im = imag( v[ 1 ] ); +// returns -1.0 + +v = it.next().value; +// returns [ 1, ] + +re = real( v[ 1 ] ); +// returns 2.0 + +im = imag( v[ 1 ] ); +// returns -2.0 + +v = it.next().value; +// returns [ 2, ] + +re = real( v[ 1 ] ); +// returns 3.0 + +im = imag( v[ 1 ] ); +// returns -3.0 + +var bool = it.next().done; +// returns true +``` + + + +#### Complex64Array.prototype.get( \[out,] i ) + +Returns an array element located at position (index) `i`. + +```javascript +var real = require( '@stdlib/complex/real' ); +var imag = require( '@stdlib/complex/imag' ); + +var arr = new Complex64Array( 10 ); + +// Set the first element: +arr.set( [ 1.0, -1.0 ], 0 ); + +// Get the first element: +var z = arr.get( 0 ); +// returns + +var re = real( z ); +// returns 1.0 + +var im = imag( z ); +// returns -1.0 +``` + +By default, the method returns a [64-bit complex number][@stdlib/complex/float32]. To return real and imaginary components separately, provide an array-like `object` as the first argument. + +```javascript +var arr = new Complex64Array( 10 ); + +// Set the first element: +arr.set( [ 1.0, -1.0 ], 0 ); + +// Define an output array: +var out = [ 0.0, 0.0 ]; + +// Get the first element: +var z = arr.get( out, 0 ); +// returns [ 1.0, -1.0 ] + +var bool = ( out === z ); +// returns true +``` + +If provided an out-of-bounds index, the method returns `undefined`. + +```javascript +var arr = new Complex64Array( 10 ); + +var z = arr.get( 100 ); +// returns undefined + +var out = [ 0.0, 0.0 ]; + +z = arr.get( out, 100 ); +// returns undefined + +var bool = ( out === z ); +// returns false +``` + + + +#### Complex64Array.prototype.set( z\[, i] ) + +Sets one or more array elements. + +```javascript +var Complex64 = require( '@stdlib/complex/float32' ); + +var arr = new Complex64Array( 10 ); + +// Get the first element: +var z = arr.get( [ 0.0, 0.0 ], 0 ); +// returns [ 0.0, 0.0 ] + +// Set the first element: +arr.set( new Complex64( 1.0, -1.0 ) ); + +// Get the first element: +z = arr.get( [ 0.0, 0.0 ], 0 ); +// returns [ 1.0, -1.0 ] +``` + +By default, the method sets array elements starting at position (index) `i = 0`. To set elements starting elsewhere in the array, provide an index argument `i`. + +```javascript +var Complex64 = require( '@stdlib/complex/float32' ); + +var arr = new Complex64Array( 10 ); + +// Get the fifth element: +var z = arr.get( [ 0.0, 0.0 ], 4 ); +// returns [ 0.0, 0.0 ] + +// Set the fifth element: +arr.set( new Complex64( 1.0, -1.0 ), 4 ); + +// Get the fifth element: +z = arr.get( [ 0.0, 0.0 ], 4 ); +// returns [ 1.0, -1.0 ] +``` + +In addition to providing a complex number, to set one or more array elements, provide an array-like `object` containing either complex numbers + +```javascript +var Complex64 = require( '@stdlib/complex/float32' ); + +var arr = new Complex64Array( 10 ); + +// Define an array of complex numbers: +var buf = [ + new Complex64( 1.0, -1.0 ), + new Complex64( 2.0, -2.0 ), + new Complex64( 3.0, -3.0 ) +]; + +// Set the fifth, sixth, and seventh elements: +arr.set( buf, 4 ); + +// Get the sixth element: +var z = arr.get( [ 0.0, 0.0 ], 5 ); +// returns [ 2.0, -2.0 ] +``` + +or interleaved real and imaginary components + +```javascript +var Float32Array = require( '@stdlib/array/float32' ); + +var arr = new Complex64Array( 10 ); + +// Define an interleaved array of real and imaginary components: +var buf = new Float32Array( [ 1.0, -1.0, 2.0, -2.0, 3.0, -3.0 ] ); + +// Set the fifth, sixth, and seventh elements: +arr.set( buf, 4 ); + +// Get the sixth element: +var z = arr.get( [ 0.0, 0.0 ], 5 ); +// returns [ 2.0, -2.0 ] +``` + +A few notes: + +- If `i` is out-of-bounds, the method throws an error. +- If a target array cannot accommodate all values (i.e., the length of source array plus `i` exceeds the target array length), the method throws an error. +- If provided a [typed array][@stdlib/array/typed] which shares an [`ArrayBuffer`][@stdlib/array/buffer] with the target array, the method will intelligently copy the source range to the destination range. + +
+ + + + + +
+ +* * * + +## Notes + +- While a `Complex64Array` _strives_ to maintain (but does not **guarantee**) consistency with [typed arrays][@stdlib/array/typed], significant deviations from ECMAScript-defined [typed array][@stdlib/array/typed] behavior are as follows: + + - The constructor does **not** require the `new` operator. + - The constructor and associated methods support a broader variety of input argument types in order to better accommodate complex number input. + - Accessing array elements using bracket syntax (e.g., `Z[i]`) is **not** supported. Instead, one **must** use the `.get()` method which returns a value compatible with complex number output. + - The `set` method has extended behavior in order to support complex numbers. + +
+ + + + + +
+ +* * * + +## Examples + + + +```javascript +var Complex64 = require( '@stdlib/complex/float32' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Complex64Array = require( '@stdlib/array/complex64' ); + +var arr; +var out; + +// Create a complex array by specifying a length: +out = new Complex64Array( 3 ); +console.log( out ); + +// Create a complex array from an array of complex numbers: +arr = [ + new Complex64( 1.0, -1.0 ), + new Complex64( -3.14, 3.14 ), + new Complex64( 0.5, 0.5 ) +]; +out = new Complex64Array( arr ); +console.log( out ); + +// Create a complex array from an interleaved typed array: +arr = new Float32Array( [ 1.0, -1.0, -3.14, 3.14, 0.5, 0.5 ] ); +out = new Complex64Array( arr ); +console.log( out ); + +// Create a complex array from an array buffer: +arr = new Float32Array( [ 1.0, -1.0, -3.14, 3.14, 0.5, 0.5 ] ); +out = new Complex64Array( arr.buffer ); +console.log( out ); + +// Create a complex array from an array buffer view: +arr = new Float32Array( [ 1.0, -1.0, -3.14, 3.14, 0.5, 0.5 ] ); +out = new Complex64Array( arr.buffer, 8, 2 ); +console.log( out ); +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/complex64/benchmark/benchmark.copy_within.js b/complex64/benchmark/benchmark.copy_within.js new file mode 100644 index 00000000..17409d7a --- /dev/null +++ b/complex64/benchmark/benchmark.copy_within.js @@ -0,0 +1,57 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var Complex64 = require( '@stdlib/complex/float32' ); +var pkg = require( './../package.json' ).name; +var Complex64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':copyWithin', function benchmark( b ) { + var arr; + var buf; + var i; + + arr = []; + for ( i = 0; i < 5; i++ ) { + arr.push( new Complex64( i, i ) ); + } + arr = new Complex64Array( arr ); + buf = arr.buffer; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = i; + arr = arr.copyWithin( 1, 0 ); + if ( buf[ 0 ] !== i ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( buf[ 0 ] !== buf[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/complex64/benchmark/benchmark.copy_within.length.js b/complex64/benchmark/benchmark.copy_within.length.js new file mode 100644 index 00000000..d7a3d892 --- /dev/null +++ b/complex64/benchmark/benchmark.copy_within.length.js @@ -0,0 +1,104 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var Complex64 = require( '@stdlib/complex/float32' ); +var pkg = require( './../package.json' ).name; +var Complex64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr; + var buf; + var i; + + arr = []; + for ( i = 0; i < len+1; i++ ) { + arr.push( new Complex64( i, i ) ); + } + arr = new Complex64Array( arr ); + buf = arr.buffer; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = i; + arr.copyWithin( 1, 0 ); + if ( buf[ 0 ] !== i ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( buf[ 0 ] !== buf[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':copyWithin:len='+len, f ); + } +} + +main(); diff --git a/complex64/benchmark/benchmark.entries.js b/complex64/benchmark/benchmark.entries.js new file mode 100644 index 00000000..24abdf16 --- /dev/null +++ b/complex64/benchmark/benchmark.entries.js @@ -0,0 +1,55 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var Complex64 = require( '@stdlib/complex/float32' ); +var pkg = require( './../package.json' ).name; +var Complex64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':entries', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( new Complex64( i, i ) ); + } + arr = new Complex64Array( arr ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.entries(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/complex64/benchmark/benchmark.from.js b/complex64/benchmark/benchmark.from.js new file mode 100644 index 00000000..37401e48 --- /dev/null +++ b/complex64/benchmark/benchmark.from.js @@ -0,0 +1,312 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var Float32Array = require( '@stdlib/array/float32' ); +var ITERATOR_SYMBOL = require( '@stdlib/symbol/iterator' ); +var pkg = require( './../package.json' ).name; +var Complex64Array = require( './../lib' ); + + +// VARIABLES // + +var opts = { + 'skip': ( ITERATOR_SYMBOL === null ) +}; + + +// MAIN // + +bench( pkg+'::typed_array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Float32Array( 0 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Complex64Array.from( buf ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array:from:len=5', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Float32Array( 10 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Complex64Array.from( buf ); + if ( arr.length !== 5 ) { + b.fail( 'should have length 5' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array,clbk:from:len=5', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Float32Array( 10 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Complex64Array.from( buf, clbk ); + if ( arr.length !== 5 ) { + b.fail( 'should have length 5' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1.0; + } +}); + +bench( pkg+'::array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = []; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Complex64Array.from( buf ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::array:from:len=5', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Complex64Array.from( buf ); + if ( arr.length !== 5 ) { + b.fail( 'should have length 5' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::array,clbk:from:len=5', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Complex64Array.from( buf, clbk ); + if ( arr.length !== 5 ) { + b.fail( 'should have length 5' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1.0; + } +}); + +bench( pkg+'::iterable:from', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Complex64Array.from( createIterable() ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + return { + 'done': true + }; + } + } +}); + +bench( pkg+'::iterable:from:len=5', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Complex64Array.from( createIterable() ); + if ( arr.length !== 5 ) { + b.fail( 'should have length 5' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + return out; + + function iterator() { + var it = { + 'next': next, + 'i': 0, + 'N': 5 + }; + return it; + + function next() { + it.i += 1; + if ( it.i <= it.N ) { + return { + 'value': [ 1.0, 1.0 ] + }; + } + return { + 'done': true + }; + } + } + } +}); + +bench( pkg+'::iterable,clbk:from:len=5', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Complex64Array.from( createIterable(), clbk ); + if ( arr.length !== 5 ) { + b.fail( 'should have length 5' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + return out; + + function iterator() { + var it = { + 'next': next, + 'i': 0, + 'N': 5 + }; + return it; + + function next() { + it.i += 1; + if ( it.i <= it.N ) { + return { + 'value': [ 1.0, 1.0 ] + }; + } + return { + 'done': true + }; + } + } + } + + function clbk( v ) { + v[ 0 ] += 1.0; + v[ 1 ] += 1.0; + return v; + } +}); diff --git a/complex64/benchmark/benchmark.get.js b/complex64/benchmark/benchmark.get.js new file mode 100644 index 00000000..7b9f3e37 --- /dev/null +++ b/complex64/benchmark/benchmark.get.js @@ -0,0 +1,159 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Complex64 = require( '@stdlib/complex/float32' ); +var isComplex64 = require( '@stdlib/assert/is-complex64' ); +var isArray = require( '@stdlib/assert/is-array' ); +var pkg = require( './../package.json' ).name; +var Complex64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':get', function benchmark( b ) { + var arr; + var N; + var z; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( new Complex64( i, i ) ); + } + arr = new Complex64Array( arr ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + z = arr.get( i%N ); + if ( typeof z !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isComplex64( z ) ) { + b.fail( 'should return a complex number' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::memory_reuse:get', function benchmark( b ) { + var arr; + var out; + var N; + var z; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( new Complex64( i, i ) ); + } + arr = new Complex64Array( arr ); + N = arr.length; + + out = [ 0.0, 0.0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + z = arr.get( out, i%N ); + if ( typeof z !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isArray( z ) || z.length !== 2 ) { + b.fail( 'should return an array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::manual:get', function benchmark( b ) { + var arr; + var buf; + var N; + var z; + var i; + var j; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( new Complex64( i, i ) ); + } + arr = new Complex64Array( arr ); + N = arr.length; + + buf = new Float32Array( arr.buffer ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + j = ( i%N ) * 2; + z = [ buf[ j ], buf[ j+1 ] ]; + if ( typeof z !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isArray( z ) || z.length !== 2 ) { + b.fail( 'should return an array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::manual,memory_reuse:get', function benchmark( b ) { + var arr; + var buf; + var out; + var N; + var i; + var j; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( new Complex64( i, i ) ); + } + arr = new Complex64Array( arr ); + N = arr.length; + + buf = new Float32Array( arr.buffer ); + out = [ 0.0, 0.0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + j = ( i%N ) * 2; + out[ 0 ] = buf[ j ]; + out[ 1 ] = buf[ j+1 ]; + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isArray( out ) || out.length !== 2 ) { + b.fail( 'should return an array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/complex64/benchmark/benchmark.js b/complex64/benchmark/benchmark.js new file mode 100644 index 00000000..4ded56ca --- /dev/null +++ b/complex64/benchmark/benchmark.js @@ -0,0 +1,337 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var ArrayBuffer = require( '@stdlib/array/buffer' ); +var Float32Array = require( '@stdlib/array/float32' ); +var isArrayBuffer = require( '@stdlib/assert/is-arraybuffer' ); +var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; +var ITERATOR_SYMBOL = require( '@stdlib/symbol/iterator' ); +var pkg = require( './../package.json' ).name; +var Complex64Array = require( './../lib' ); + + +// VARIABLES // + +var opts = { + 'skip': ( ITERATOR_SYMBOL === null ) +}; + + +// MAIN // + +bench( pkg+'::instantiation,new', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new Complex64Array(); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::instantiation,no_new', function benchmark( b ) { + var ctor; + var arr; + var i; + + ctor = Complex64Array; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = ctor(); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::instantiation,length', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new Complex64Array( 0 ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::instantiation,typed_array', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Float32Array( 0 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new Complex64Array( buf ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::instantiation,array', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = []; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new Complex64Array( buf ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::instantiation,iterable', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new Complex64Array( createIterable() ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + return { + 'done': true + }; + } + } +}); + +bench( pkg+'::instantiation,arraybuffer', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new ArrayBuffer( 0 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new Complex64Array( buf ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::instantiation,arraybuffer,byte_offset', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new ArrayBuffer( 8 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new Complex64Array( buf, 8 ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::instantiation,arraybuffer,byte_offset,length', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new ArrayBuffer( 8 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new Complex64Array( buf, 8, 0 ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:buffer', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Complex64Array(); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.buffer; + if ( typeof v !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isArrayBuffer( v ) ) { + b.fail( 'should return an ArrayBuffer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteLength', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Complex64Array(); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteLength; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteOffset', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Complex64Array(); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteOffset; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:length', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Complex64Array(); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.length; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/complex64/benchmark/benchmark.length.js b/complex64/benchmark/benchmark.length.js new file mode 100644 index 00000000..35ea7ce0 --- /dev/null +++ b/complex64/benchmark/benchmark.length.js @@ -0,0 +1,92 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Complex64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new Complex64Array( len ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':len='+len, f ); + } +} + +main(); diff --git a/complex64/benchmark/benchmark.of.js b/complex64/benchmark/benchmark.of.js new file mode 100644 index 00000000..b33e0b96 --- /dev/null +++ b/complex64/benchmark/benchmark.of.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var Complex64 = require( '@stdlib/complex/float32' ); +var pkg = require( './../package.json' ).name; +var Complex64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':of', function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Complex64Array.of(); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::interleaved:of:len=5', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Complex64Array.of.apply( Complex64Array, buf ); + if ( arr.length !== 5 ) { + b.fail( 'should have length 5' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::complex_numbers:of:len=5', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = []; + for ( i = 0; i < 5; i++ ) { + buf.push( new Complex64( 1.0, 1.0 ) ); + } + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Complex64Array.of.apply( Complex64Array, buf ); + if ( arr.length !== 5 ) { + b.fail( 'should have length 5' ); + } + } + b.toc(); + if ( !(arr instanceof Complex64Array) ) { + b.fail( 'should return an instance' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/complex64/benchmark/benchmark.set.js b/complex64/benchmark/benchmark.set.js new file mode 100644 index 00000000..f5a39c62 --- /dev/null +++ b/complex64/benchmark/benchmark.set.js @@ -0,0 +1,161 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Complex64 = require( '@stdlib/complex/float32' ); +var pkg = require( './../package.json' ).name; +var Complex64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::complex_number:set', function benchmark( b ) { + var values; + var arr; + var N; + var v; + var i; + + values = []; + for ( i = 0; i < 10; i++ ) { + values.push( new Complex64( i, i ) ); + } + arr = new Complex64Array( values ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr.set( values[ (i+1)%N ] ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::array:set', function benchmark( b ) { + var values; + var arr; + var N; + var v; + var i; + + values = []; + for ( i = 0; i < 10; i++ ) { + values.push( new Complex64( i, i ) ); + } + arr = new Complex64Array( values ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr.set( [ values[ (i+1)%N ] ] ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array:set', function benchmark( b ) { + var values; + var arr; + var buf; + var M; + var N; + var v; + var i; + + values = new Float32Array( 20 ); + M = values.length; + for ( i = 0; i < M; i++ ) { + values[ i ] = i; + } + + arr = new Complex64Array( values ); + N = arr.length; + + buf = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = values[ i%N ]; + buf[ 1 ] = values[ (i+1)%N ]; + v = arr.set( buf ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::complex_typed_array:set', function benchmark( b ) { + var values; + var arr; + var buf; + var M; + var N; + var v; + var i; + + values = new Float32Array( 20 ); + M = values.length; + for ( i = 0; i < M; i++ ) { + values[ i ] = i; + } + + arr = new Complex64Array( values ); + N = arr.length; + + buf = new Complex64Array( 1 ); + buf.set( new Complex64( 1.0, -1.0 ) ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr.set( buf, i%N ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/complex64/benchmark/benchmark.set.length.js b/complex64/benchmark/benchmark.set.length.js new file mode 100644 index 00000000..cab3b8b9 --- /dev/null +++ b/complex64/benchmark/benchmark.set.length.js @@ -0,0 +1,117 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randu = require( '@stdlib/random/base/randu' ); +var Complex64 = require( '@stdlib/complex/float32' ); +var pkg = require( './../package.json' ).name; +var Complex64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var values; + var arr1; + var arr2; + var arr3; + var N; + var i; + + arr1 = []; + arr2 = []; + arr3 = []; + for ( i = 0; i < len; i++ ) { + arr1.push( new Complex64( i, i ) ); + arr2.push( new Complex64( randu(), randu() ) ); + arr3.push( new Complex64( randu(), -randu() ) ); + } + arr1 = new Complex64Array( arr1 ); + + values = [ + new Complex64Array( arr2 ), + new Complex64Array( arr3 ) + ]; + N = values.length; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr1.set( values[ i%N ] ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 4; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':set:len='+len, f ); + } +} + +main(); diff --git a/complex64/docs/types/index.d.ts b/complex64/docs/types/index.d.ts new file mode 100644 index 00000000..dcbef11c --- /dev/null +++ b/complex64/docs/types/index.d.ts @@ -0,0 +1,610 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/// + +import { Iterator as Iter, IterableIterator } from '@stdlib/types/iter'; +import { ArrayLike, TypedArray } from '@stdlib/types/array'; +import { ComplexLike } from '@stdlib/types/object'; +import ArrayBuffer = require( '@stdlib/array/buffer' ); +import Complex64 = require( '@stdlib/complex/float32' ); + +// Define a union type representing both iterable and non-iterable iterators: +type Iterator = Iter | IterableIterator; + +/** +* Class for creating a 64-bit complex number array. +*/ +declare class Complex64Array { + /** + * 64-bit complex number array constructor. + * + * @param arg - length, typed array, array-like object, or buffer + * @param byteOffset - byte offset (default: 0) + * @param length - view length + * @throws ArrayBuffer byte length must be a multiple of `8` + * @throws array-like object and typed array input arguments must have a length which is a multiple of two + * @throws if provided only a single argument, must provide a valid argument + * @throws byte offset must be a nonnegative integer + * @throws byte offset must be a multiple of `8` + * @throws view length must be a positive multiple of `8` + * @throws must provide sufficient memory to accommodate byte offset and view length requirements + * @throws an iterator must return either a two element array containing real and imaginary components or a complex number + * @returns complex number array + * + * @example + * var arr = new Complex64Array(); + * // returns + * + * var len = arr.length; + * // returns 0 + * + * @example + * var arr = new Complex64Array( 2 ); + * // returns + * + * var len = arr.length; + * // returns 2 + * + * @example + * var arr = new Complex64Array( [ 1.0, -1.0 ] ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 16 ); + * var arr = new Complex64Array( buf ); + * // returns + * + * var len = arr.length; + * // returns 2 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 16 ); + * var arr = new Complex64Array( buf, 8 ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 32 ); + * var arr = new Complex64Array( buf, 8, 2 ); + * // returns + * + * var len = arr.length; + * // returns 2 + */ + constructor( arg?: number | TypedArray | ArrayLike | ArrayBuffer | Iterable, byteOffset?: number, length?: number ); // tslint:disable-line:max-line-length + + /** + * Length (in bytes) of the array. + * + * @example + * var arr = new Complex64Array( 10 ); + * + * var byteLength = arr.byteLength; + * // returns 80 + */ + readonly byteLength: number; + + /** + * Offset (in bytes) of the array from the start of its underlying `ArrayBuffer`. + * + * @example + * var arr = new Complex64Array( 10 ); + * + * var byteOffset = arr.byteOffset; + * // returns 0 + */ + readonly byteOffset: number; + + /** + * Size (in bytes) of each array element. + * + * @example + * var arr = new Complex64Array( 10 ); + * + * var nbytes = arr.BYTES_PER_ELEMENT; + * // returns 8 + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Number of array elements. + * + * @example + * var arr = new Complex64Array( 10 ); + * + * var len = arr.length; + * // returns 10 + */ + readonly length: number; + + /** + * Copies a sequence of elements within the array to the position starting at `target`. + * + * @param target - index at which to start copying elements + * @param start - source index at which to copy elements from + * @param end - source index at which to stop copying elements from + * @returns modified array + * + * @example + * var Complex64 = require( `@stdlib/complex/float32` ); + * var real = require( `@stdlib/complex/real` ); + * var imag = require( `@stdlib/complex/imag` ); + * + * var arr = new Complex64Array( 4 ); + * + * // Set the array elements: + * arr.set( new Complex64( 1.0, 1.0 ), 0 ); + * arr.set( new Complex64( 2.0, 2.0 ), 1 ); + * arr.set( new Complex64( 3.0, 3.0 ), 2 ); + * arr.set( new Complex64( 4.0, 4.0 ), 3 ); + * + * // Copy the first two elements to the last two elements: + * arr.copyWithin( 2, 0, 2 ); + * + * // Get the last array element: + * var z = arr.get( 3 ); + * + * var re = real( z ); + * // returns 2.0 + * + * var im = imag( z ); + * // returns 2.0 + */ + copyWithin( target: number, start: number, end?: number ): Complex64Array; + + /** + * Returns an iterator for iterating over array key-value pairs. + * + * @returns iterator + * + * @example + * var Complex64 = require( `@stdlib/complex/float32` ); + * + * var arr = [ + * new Complex64( 1.0, 1.0 ), + * new Complex64( 2.0, 2.0 ), + * new Complex64( 3.0, 3.0 ) + * ]; + * arr = new Complex64Array( arr ); + * + * // Create an iterator: + * var it = arr.entries(); + * + * // Iterate over the key-value pairs... + * var v = it.next().value; + * // returns [ 0, ] + * + * v = it.next().value; + * // returns [ 1, ] + * + * v = it.next().value; + * // returns [ 2, ] + * + * var bool = it.next().done; + * // returns true + */ + entries(): Iterator; + + /** + * Returns an array element. + * + * @param i - element index + * @throws index argument must be a nonnegative integer + * @returns array element + * + * @example + * var arr = new Complex64Array( 10 ); + * + * var z = arr.get( 0 ); + * // returns + * + * arr.set( [ 1.0, -1.0 ], 0 ); + * + * z = arr.get( 100 ); + * // returns undefined + */ + get( i: number ): Complex64 | void; + + /** + * Returns an array element. + * + * @param out - output array + * @param i - element index + * @throws index argument must be a nonnegative integer + * @returns array element + * + * @example + * var arr = new Complex64Array( 10 ); + * + * var z = arr.get( 0 ); + * // returns + * + * arr.set( [ 1.0, -1.0 ], 0 ); + * + * z = arr.get( [ 0.0, 0.0 ], 0 ); + * // returns [ 1.0, -1.0 ] + */ + get( out: ArrayLike, i: number ): ArrayLike | void; + + /** + * Sets an array element. + * + * ## Notes + * + * - When provided a typed array, real or complex, we must check whether the source array shares the same buffer as the target array and whether the underlying memory overlaps. In particular, we are concerned with the following scenario: + * + * ```text + * buf: --------------------- + * src: --------------------- + * ``` + * + * In the above, as we copy values from `src`, we will overwrite values in the `src` view, resulting in duplicated values copied into the end of `buf`, which is not intended. Hence, to avoid overwriting source values, we must **copy** source values to a temporary array. + * + * In the other overlapping scenario, + * + * ```text + * buf: --------------------- + * src: --------------------- + * ``` + * + * by the time we begin copying into the overlapping region, we are copying from the end of `src`, a non-overlapping region, which means we don't run the risk of copying copied values, rather than the original `src` values as intended. + * + * + * @param value - value(s) + * @param i - element index at which to start writing values (default: 0) + * @throws index argument must be a nonnegative integer + * @throws array-like objects must have a length which is a multiple of two + * @throws index argument is out-of-bounds + * @throws target array lacks sufficient storage to accommodate source values + * + * @example + * var real = require( `@stdlib/complex/real` ); + * var imag = require( `@stdlib/complex/imag` ); + * + * var arr = new Complex64Array( 10 ); + * + * var z = arr.get( 0 ); + * // returns + * + * var re = real( z ); + * // returns 0.0 + * + * var im = imag( z ); + * // returns 0.0 + * + * arr.set( [ 1.0, -1.0 ], 0 ); + * + * z = arr.get( 0 ); + * // returns + * + * re = real( z ); + * // returns 1.0 + * + * im = imag( z ); + * // returns -1.0 + */ + set( value: ArrayLike | Complex64Array | ComplexLike, i?: number ): void; // tslint:disable-line:max-line-length +} + +/** +* Interface defining a 64-bit complex number array constructor which is both "newable" and "callable". +*/ +interface Constructor { + /** + * 64-bit complex number array constructor. + * + * @param arg - length, typed array, array-like object, or buffer + * @param byteOffset - byte offset (default: 0) + * @param length - view length + * @throws ArrayBuffer byte length must be a multiple of `8` + * @throws array-like object and typed array input arguments must have a length which is a multiple of two + * @throws if provided only a single argument, must provide a valid argument + * @throws byte offset must be a nonnegative integer + * @throws byte offset must be a multiple of `8` + * @throws view length must be a positive multiple of `8` + * @throws must provide sufficient memory to accommodate byte offset and view length requirements + * @throws an iterator must return either a two element array containing real and imaginary components or a complex number + * @returns complex number array + * + * @example + * var arr = new Complex64Array(); + * // returns + * + * var len = arr.length; + * // returns 0 + * + * @example + * var arr = new Complex64Array( 2 ); + * // returns + * + * var len = arr.length; + * // returns 2 + * + * @example + * var arr = new Complex64Array( [ 1.0, -1.0 ] ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 16 ); + * var arr = new Complex64Array( buf ); + * // returns + * + * var len = arr.length; + * // returns 2 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 16 ); + * var arr = new Complex64Array( buf, 8 ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 32 ); + * var arr = new Complex64Array( buf, 8, 2 ); + * // returns + * + * var len = arr.length; + * // returns 2 + */ + new( arg?: number | TypedArray | ArrayLike | ArrayBuffer | Iterable, byteOffset?: number, length?: number ): Complex64Array; // tslint-disable-line max-line-length + + /** + * 64-bit complex number array constructor. + * + * @param arg - length, typed array, array-like object, or buffer + * @param byteOffset - byte offset (default: 0) + * @param length - view length + * @throws ArrayBuffer byte length must be a multiple of `8` + * @throws array-like object and typed array input arguments must have a length which is a multiple of two + * @throws if provided only a single argument, must provide a valid argument + * @throws byte offset must be a nonnegative integer + * @throws byte offset must be a multiple of `8` + * @throws view length must be a positive multiple of `8` + * @throws must provide sufficient memory to accommodate byte offset and view length requirements + * @throws an iterator must return either a two element array containing real and imaginary components or a complex number + * @returns complex number array + * + * @example + * var arr = new Complex64Array(); + * // returns + * + * var len = arr.length; + * // returns 0 + * + * @example + * var arr = new Complex64Array( 2 ); + * // returns + * + * var len = arr.length; + * // returns 2 + * + * @example + * var arr = new Complex64Array( [ 1.0, -1.0 ] ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 16 ); + * var arr = new Complex64Array( buf ); + * // returns + * + * var len = arr.length; + * // returns 2 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 16 ); + * var arr = new Complex64Array( buf, 8 ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 32 ); + * var arr = new Complex64Array( buf, 8, 2 ); + * // returns + * + * var len = arr.length; + * // returns 2 + */ + ( arg?: number | TypedArray | ArrayLike | ArrayBuffer | Iterable, byteOffset?: number, length?: number ): Complex64Array; // tslint-disable-line max-line-length + + /** + * Constructor name. + * + * @example + * var str = Complex64Array.name; + * // returns 'Complex64Array' + */ + readonly name: string; + + /** + * Size (in bytes) of each array element. + * + * @example + * var nbytes = Complex64Array.BYTES_PER_ELEMENT; + * // returns 8 + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Creates a new 64-bit complex number array from an array-like object or an iterable. + * + * @param src - array-like object or iterable + * @param clbk - callback to invoke for each source element + * @param thisArg - context + * @throws array-like objects must have a length which is a multiple of two + * @throws an iterator must return either a two element array containing real and imaginary components or a complex number + * @throws when provided an iterator, a callback must return either a two element array containing real and imaginary components or a complex number + * @returns 64-bit complex number array + * + * @example + * var arr = Complex64Array.from( [ 1.0, -1.0 ] ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var Complex64 = require( `@stdlib/complex/float32` ); + * + * var arr = Complex64Array.from( [ new Complex64( 1.0, 1.0 ) ] ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var Complex64 = require( `@stdlib/complex/float32` ); + * var real = require( `@stdlib/complex/real` ); + * var imag = require( `@stdlib/complex/imag` ); + * + * function clbk( v ) { + * return new Complex64( real(v)*2.0, imag(v)*2.0 ); + * } + * + * var arr = Complex64Array.from( [ new Complex64( 1.0, 1.0 ) ], clbk ); + * // returns + * + * var len = arr.length; + * // returns 1 + */ + from( src: ArrayLike | Iterable, clbk?: Function, thisArg?: any ): Complex64Array; // tslint:disable-line:max-line-length + + /** + * Creates a new 64-bit complex number array from a variable number of arguments. + * + * @param element - array elements + * @returns 64-bit complex number array + * + * @example + * var arr = Complex64Array.of( 1.0, 1.0, 1.0, 1.0 ); + * // returns + * + * var len = arr.length; + * // returns 2 + */ + of( ...elements: Array ): Complex64Array; +} + +/** +* 64-bit complex number array constructor. +* +* @param arg - length, typed array, array-like object, or buffer +* @param byteOffset - byte offset (default: 0) +* @param length - view length +* @throws ArrayBuffer byte length must be a multiple of `8` +* @throws array-like object and typed array input arguments must have a length which is a multiple of two +* @throws if provided only a single argument, must provide a valid argument +* @throws byte offset must be a nonnegative integer +* @throws byte offset must be a multiple of `8` +* @throws view length must be a positive multiple of `8` +* @throws must provide sufficient memory to accommodate byte offset and view length requirements +* @throws an iterator must return either a two element array containing real and imaginary components or a complex number +* @returns complex number array +* +* @example +* var arr = new Complex64Array(); +* // returns +* +* var len = arr.length; +* // returns 0 +* +* @example +* var arr = new Complex64Array( 2 ); +* // returns +* +* var len = arr.length; +* // returns 2 +* +* @example +* var arr = new Complex64Array( [ 1.0, -1.0 ] ); +* // returns +* +* var len = arr.length; +* // returns 1 +* +* @example +* var ArrayBuffer = require( `@stdlib/array/buffer` ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = new Complex64Array( buf ); +* // returns +* +* var len = arr.length; +* // returns 2 +* +* @example +* var ArrayBuffer = require( `@stdlib/array/buffer` ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = new Complex64Array( buf, 8 ); +* // returns +* +* var len = arr.length; +* // returns 1 +* +* @example +* var ArrayBuffer = require( `@stdlib/array/buffer` ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = new Complex64Array( buf, 8, 2 ); +* // returns +* +* var len = arr.length; +* // returns 2 +*/ +declare var ctor: Constructor; + + +// EXPORTS // + +export = ctor; diff --git a/complex64/docs/types/test.ts b/complex64/docs/types/test.ts new file mode 100644 index 00000000..5ffb13b3 --- /dev/null +++ b/complex64/docs/types/test.ts @@ -0,0 +1,153 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// tslint:disable:no-unused-expression + +import Complex64Array = require( './index' ); +import Complex64 = require( '@stdlib/complex/float32' ); +import ArrayBuffer = require( '@stdlib/array/buffer' ); +import real = require( '@stdlib/complex/real' ); +import imag = require( '@stdlib/complex/imag' ); + +const clbk = ( v: Complex64 ) => { + return new Complex64( real( v ) * 2.0, imag( v ) * 2.0 ); +}; + + +// TESTS // + +// The function returns a complex number array... +{ + new Complex64Array(); // $ExpectType Complex64Array + Complex64Array(); // $ExpectType Complex64Array + new Complex64Array( 2 ); // $ExpectType Complex64Array + Complex64Array( 2 ); // $ExpectType Complex64Array + new Complex64Array( [ 1.0, -1.0 ] ); // $ExpectType Complex64Array + Complex64Array( [ 1.0, -1.0 ] ); // $ExpectType Complex64Array + + const buf = new ArrayBuffer( 16 ); + new Complex64Array( buf ); // $ExpectType Complex64Array + Complex64Array( buf ); // $ExpectType Complex64Array + new Complex64Array( buf, 8 ); // $ExpectType Complex64Array + Complex64Array( buf, 8 ); // $ExpectType Complex64Array + new Complex64Array( buf, 8, 2 ); // $ExpectType Complex64Array + Complex64Array( buf, 8, 2 ); // $ExpectType Complex64Array +} + +// The compiler throws an error if the function is provided a first argument that is not a number, typed array, array-like object, or array buffer... +{ + new Complex64Array( true ); // $ExpectError + new Complex64Array( false ); // $ExpectError + new Complex64Array( null ); // $ExpectError + new Complex64Array( 'abc' ); // $ExpectError + new Complex64Array( {} ); // $ExpectError + new Complex64Array( ( x: number ): number => x ); // $ExpectError + + Complex64Array( true ); // $ExpectError + Complex64Array( false ); // $ExpectError + Complex64Array( null ); // $ExpectError + Complex64Array( 'abc' ); // $ExpectError + Complex64Array( {} ); // $ExpectError + Complex64Array( ( x: number ): number => x ); // $ExpectError +} + +// The compiler throws an error if the function is provided a second argument that is not a number... +{ + const buf = new ArrayBuffer( 16 ); + new Complex64Array( buf, true ); // $ExpectError + new Complex64Array( buf, false ); // $ExpectError + new Complex64Array( buf, null ); // $ExpectError + new Complex64Array( buf, 'abc' ); // $ExpectError + new Complex64Array( buf, {} ); // $ExpectError + new Complex64Array( buf, ( x: number ): number => x ); // $ExpectError + + Complex64Array( buf, true ); // $ExpectError + Complex64Array( buf, false ); // $ExpectError + Complex64Array( buf, null ); // $ExpectError + Complex64Array( buf, 'abc' ); // $ExpectError + Complex64Array( buf, {} ); // $ExpectError + Complex64Array( buf, ( x: number ): number => x ); // $ExpectError +} + +// The compiler throws an error if the function is provided a third argument that is not a number... +{ + const buf = new ArrayBuffer( 16 ); + new Complex64Array( buf, 8, true ); // $ExpectError + new Complex64Array( buf, 8, false ); // $ExpectError + new Complex64Array( buf, 8, null ); // $ExpectError + new Complex64Array( buf, 8, 'abc' ); // $ExpectError + new Complex64Array( buf, 8, {} ); // $ExpectError + new Complex64Array( buf, 8, ( x: number ): number => x ); // $ExpectError + + Complex64Array( buf, 8, true ); // $ExpectError + Complex64Array( buf, 8, false ); // $ExpectError + Complex64Array( buf, 8, null ); // $ExpectError + Complex64Array( buf, 8, 'abc' ); // $ExpectError + Complex64Array( buf, 8, {} ); // $ExpectError + Complex64Array( buf, 8, ( x: number ): number => x ); // $ExpectError +} + +// The `from` method returns a complex number array... +{ + Complex64Array.from( [ 1.0, 1.0 ] ); // $ExpectType Complex64Array + Complex64Array.from( [ 1.0, 1.0 ], ( x: number ): number => x * x ); // $ExpectType Complex64Array + Complex64Array.from( [ new Complex64( 1.0, 1.0 ) ], clbk, {} ); // $ExpectType Complex64Array +} + +// The compiler throws an error if the `from` method is provided a first argument which is not array-like or iterable... +{ + Complex64Array.from( true ); // $ExpectError + Complex64Array.from( false ); // $ExpectError + Complex64Array.from( 123 ); // $ExpectError + Complex64Array.from( null ); // $ExpectError + Complex64Array.from( {} ); // $ExpectError + + Complex64Array.from( true, clbk ); // $ExpectError + Complex64Array.from( false, clbk ); // $ExpectError + Complex64Array.from( 123, clbk ); // $ExpectError + Complex64Array.from( null, clbk ); // $ExpectError + Complex64Array.from( {}, clbk ); // $ExpectError + + Complex64Array.from( true, clbk, {} ); // $ExpectError + Complex64Array.from( false, clbk, {} ); // $ExpectError + Complex64Array.from( 123, clbk, {} ); // $ExpectError + Complex64Array.from( null, clbk, {} ); // $ExpectError + Complex64Array.from( {}, clbk, {} ); // $ExpectError +} + +// The compiler throws an error if the `from` method is provided a second argument which is not a function with a supported signature... +{ + Complex64Array.from( [ 1, 1 ], true ); // $ExpectError + Complex64Array.from( [ 1, 1 ], false ); // $ExpectError + Complex64Array.from( [ 1, 1 ], 123 ); // $ExpectError + Complex64Array.from( [ 1, 1 ], null ); // $ExpectError + Complex64Array.from( [ 1, 1 ], {} ); // $ExpectError +} + +// The `of` method returns a complex number array... +{ + Complex64Array.of( 1.0, 1.0, 1.0, 1.0 ); // $ExpectType Complex64Array +} + +// The compiler throws an error if the `of` method is provided arguments that are not numbers... +{ + Complex64Array.of( 'abc', 'def' ); // $ExpectError + Complex64Array.of( true, false ); // $ExpectError + Complex64Array.of( {}, [] ); // $ExpectError + Complex64Array.of( null, null ); // $ExpectError +} diff --git a/complex64/examples/index.js b/complex64/examples/index.js new file mode 100644 index 00000000..dea19277 --- /dev/null +++ b/complex64/examples/index.js @@ -0,0 +1,54 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var Complex64 = require( '@stdlib/complex/float32' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Complex64Array = require( './../lib' ); + +var arr; +var out; + +// Create a complex array by specifying a length: +out = new Complex64Array( 3 ); +console.log( out ); + +// Create a complex array from an array of complex numbers: +arr = [ + new Complex64( 1.0, -1.0 ), + new Complex64( -3.14, 3.14 ), + new Complex64( 0.5, 0.5 ) +]; +out = new Complex64Array( arr ); +console.log( out ); + +// Create a complex array from an interleaved typed array: +arr = new Float32Array( [ 1.0, -1.0, -3.14, 3.14, 0.5, 0.5 ] ); +out = new Complex64Array( arr ); +console.log( out ); + +// Create a complex array from an array buffer: +arr = new Float32Array( [ 1.0, -1.0, -3.14, 3.14, 0.5, 0.5 ] ); +out = new Complex64Array( arr.buffer ); +console.log( out ); + +// Create a complex array from an array buffer view: +arr = new Float32Array( [ 1.0, -1.0, -3.14, 3.14, 0.5, 0.5 ] ); +out = new Complex64Array( arr.buffer, 8, 2 ); +console.log( out ); diff --git a/complex64/lib/from_array.js b/complex64/lib/from_array.js new file mode 100644 index 00000000..078599a7 --- /dev/null +++ b/complex64/lib/from_array.js @@ -0,0 +1,61 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isComplexLike = require( '@stdlib/assert/is-complex-like' ); +var real = require( '@stdlib/complex/real' ); +var imag = require( '@stdlib/complex/imag' ); + + +// MAIN // + +/** +* Returns a strided array of real and imaginary components. +* +* @private +* @param {Float32Array} buf - output array +* @param {Array} arr - array containing complex numbers +* @returns {(Float32Array|null)} output array or null +*/ +function fromArray( buf, arr ) { + var len; + var v; + var i; + var j; + + len = arr.length; + j = 0; + for ( i = 0; i < len; i++ ) { + v = arr[ i ]; + if ( !isComplexLike( v ) ) { + return null; + } + buf[ j ] = real( v ); + buf[ j+1 ] = imag( v ); + j += 2; // stride + } + return buf; +} + + +// EXPORTS // + +module.exports = fromArray; diff --git a/complex64/lib/from_iterator.js b/complex64/lib/from_iterator.js new file mode 100644 index 00000000..aa32ff00 --- /dev/null +++ b/complex64/lib/from_iterator.js @@ -0,0 +1,66 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isArrayLikeObject = require( '@stdlib/assert/is-array-like-object' ); +var isComplexLike = require( '@stdlib/assert/is-complex-like' ); +var real = require( '@stdlib/complex/real' ); +var imag = require( '@stdlib/complex/imag' ); + + +// MAIN // + +/** +* Returns an array of iterated values. +* +* @private +* @param {Object} it - iterator +* @returns {(Array|TypeError)} array or an error +*/ +function fromIterator( it ) { + var out; + var v; + var z; + + out = []; + while ( true ) { + v = it.next(); + z = v.value; + if ( z ) { + if ( isArrayLikeObject( z ) && z.length >= 2 ) { + out.push( z[ 0 ], z[ 1 ] ); + } else if ( isComplexLike( z ) ) { + out.push( real( z ), imag( z ) ); + } else { + return new TypeError( 'invalid argument. An iterator must return either a two-element array containing real and imaginary components or a complex number. Value: `'+z+'`.' ); + } + } + if ( v.done ) { + break; + } + } + return out; +} + + +// EXPORTS // + +module.exports = fromIterator; diff --git a/complex64/lib/from_iterator_map.js b/complex64/lib/from_iterator_map.js new file mode 100644 index 00000000..84caa076 --- /dev/null +++ b/complex64/lib/from_iterator_map.js @@ -0,0 +1,72 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isArrayLikeObject = require( '@stdlib/assert/is-array-like-object' ); +var isComplexLike = require( '@stdlib/assert/is-complex-like' ); +var real = require( '@stdlib/complex/real' ); +var imag = require( '@stdlib/complex/imag' ); + + +// MAIN // + +/** +* Returns an array of iterated values. +* +* @private +* @param {Object} it - iterator +* @param {Function} clbk - callback to invoke for each iterated value +* @param {*} thisArg - invocation context +* @returns {(Array|TypeError)} array or an error +*/ +function fromIteratorMap( it, clbk, thisArg ) { + var out; + var v; + var z; + var i; + + out = []; + i = -1; + while ( true ) { + i += 1; + v = it.next(); + z = v.value; + if ( z ) { + z = clbk.call( thisArg, z, i ); + if ( isArrayLikeObject( z ) && z.length >= 2 ) { + out.push( z[ 0 ], z[ 1 ] ); + } else if ( isComplexLike( z ) ) { + out.push( real( z ), imag( z ) ); + } else { + return new TypeError( 'invalid argument. Callback must return either a two-element array containing real and imaginary components or a complex number. Value: `'+z+'`.' ); + } + } + if ( v.done ) { + break; + } + } + return out; +} + + +// EXPORTS // + +module.exports = fromIteratorMap; diff --git a/complex64/lib/index.js b/complex64/lib/index.js new file mode 100644 index 00000000..fd46d0bb --- /dev/null +++ b/complex64/lib/index.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* 64-bit complex number array. +* +* @module @stdlib/array/complex64 +* +* @example +* var Complex64Array = require( '@stdlib/array/complex64' ); +* +* var arr = new Complex64Array(); +* // returns +* +* var len = arr.length; +* // returns 0 +* +* @example +* var Complex64Array = require( '@stdlib/array/complex64' ); +* +* var arr = new Complex64Array( 2 ); +* // returns +* +* var len = arr.length; +* // returns 2 +* +* @example +* var Complex64Array = require( '@stdlib/array/complex64' ); +* +* var arr = new Complex64Array( [ 1.0, -1.0 ] ); +* // returns +* +* var len = arr.length; +* // returns 1 +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* var Complex64Array = require( '@stdlib/array/complex64' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = new Complex64Array( buf ); +* // returns +* +* var len = arr.length; +* // returns 2 +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* var Complex64Array = require( '@stdlib/array/complex64' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = new Complex64Array( buf, 8 ); +* // returns +* +* var len = arr.length; +* // returns 2 +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* var Complex64Array = require( '@stdlib/array/complex64' ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = new Complex64Array( buf, 8, 2 ); +* // returns +* +* var len = arr.length; +* // returns 2 +*/ + +// MODULES // + +var Complex64Array = require( './main.js' ); + + +// EXPORTS // + +module.exports = Complex64Array; diff --git a/complex64/lib/main.js b/complex64/lib/main.js new file mode 100644 index 00000000..33a1ebfd --- /dev/null +++ b/complex64/lib/main.js @@ -0,0 +1,1074 @@ +/* eslint-disable no-restricted-syntax, max-lines */ + +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; +var isArrayLikeObject = require( '@stdlib/assert/is-array-like-object' ); +var isCollection = require( '@stdlib/assert/is-collection' ); +var isArrayBuffer = require( '@stdlib/assert/is-arraybuffer' ); +var isObject = require( '@stdlib/assert/is-object' ); +var isArray = require( '@stdlib/assert/is-array' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var isComplexLike = require( '@stdlib/assert/is-complex-like' ); +var isEven = require( '@stdlib/math/base/assert/is-even' ); +var isInteger = require( '@stdlib/math/base/assert/is-integer' ); +var hasIteratorSymbolSupport = require( '@stdlib/assert/has-iterator-symbol-support' ); +var ITERATOR_SYMBOL = require( '@stdlib/symbol/iterator' ); +var defineProperty = require( '@stdlib/utils/define-property' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Complex64 = require( '@stdlib/complex/float32' ); +var real = require( '@stdlib/complex/real' ); +var imag = require( '@stdlib/complex/imag' ); +var fromIterator = require( './from_iterator.js' ); +var fromIteratorMap = require( './from_iterator_map.js' ); +var fromArray = require( './from_array.js' ); + + +// VARIABLES // + +var BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT * 2; +var HAS_ITERATOR_SYMBOL = hasIteratorSymbolSupport(); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating if a value is a complex typed array. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating if a value is a complex typed array +*/ +function isComplexArray( value ) { + return ( + value instanceof Complex64Array || + ( + typeof value === 'object' && + value !== null && + ( + value.constructor.name === 'Complex64Array' || + value.constructor.name === 'Complex128Array' + ) && + typeof value._length === 'number' && // eslint-disable-line no-underscore-dangle + + // NOTE: we don't perform a more rigorous test here for a typed array for performance reasons, as robustly checking for a typed array instance could require walking the prototype tree and performing relatively expensive constructor checks... + typeof value._buffer === 'object' // eslint-disable-line no-underscore-dangle + ) + ); +} + +/** +* Returns a boolean indicating if a value is a complex typed array constructor. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating if a value is a complex typed array constructor +*/ +function isComplexArrayConstructor( value ) { + return ( + value === Complex64Array || + + // NOTE: weaker test in order to avoid a circular dependency with Complex128Array... + value.name === 'Complex128Array' + ); +} + + +// MAIN // + +/** +* 64-bit complex number array constructor. +* +* @constructor +* @param {(NonNegativeInteger|TypedArray|ArrayLikeObject|ArrayBuffer|Iterable)} [arg] - length, typed array, array-like object, or buffer +* @param {NonNegativeInteger} [byteOffset=0] - byte offset +* @param {NonNegativeInteger} [length] - view length +* @throws {RangeError} ArrayBuffer byte length must be a multiple of `8` +* @throws {RangeError} array-like object and typed array input arguments must have a length which is a multiple of two +* @throws {TypeError} if provided only a single argument, must provide a valid argument +* @throws {TypeError} byte offset must be a nonnegative integer +* @throws {RangeError} byte offset must be a multiple of `8` +* @throws {TypeError} view length must be a positive multiple of `8` +* @throws {RangeError} must provide sufficient memory to accommodate byte offset and view length requirements +* @throws {TypeError} an iterator must return either a two element array containing real and imaginary components or a complex number +* @returns {Complex64Array} complex number array +* +* @example +* var arr = new Complex64Array(); +* // returns +* +* var len = arr.length; +* // returns 0 +* +* @example +* var arr = new Complex64Array( 2 ); +* // returns +* +* var len = arr.length; +* // returns 2 +* +* @example +* var arr = new Complex64Array( [ 1.0, -1.0 ] ); +* // returns +* +* var len = arr.length; +* // returns 1 +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = new Complex64Array( buf ); +* // returns +* +* var len = arr.length; +* // returns 2 +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = new Complex64Array( buf, 8 ); +* // returns +* +* var len = arr.length; +* // returns 1 +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = new Complex64Array( buf, 8, 2 ); +* // returns +* +* var len = arr.length; +* // returns 2 +*/ +function Complex64Array() { + var byteOffset; + var nargs; + var buf; + var len; + + nargs = arguments.length; + if ( !(this instanceof Complex64Array) ) { + if ( nargs === 0 ) { + return new Complex64Array(); + } + if ( nargs === 1 ) { + return new Complex64Array( arguments[0] ); + } + if ( nargs === 2 ) { + return new Complex64Array( arguments[0], arguments[1] ); + } + return new Complex64Array( arguments[0], arguments[1], arguments[2] ); + } + // Create the underlying data buffer... + if ( nargs === 0 ) { + buf = new Float32Array( 0 ); // backward-compatibility + } else if ( nargs === 1 ) { + if ( isNonNegativeInteger( arguments[0] ) ) { + buf = new Float32Array( arguments[0]*2 ); + } else if ( isCollection( arguments[0] ) ) { + buf = arguments[ 0 ]; + len = buf.length; + + // If provided a "generic" array, peak at the first value, and, if the value is a complex number, try to process as an array of complex numbers, falling back to "normal" typed array initialization if we fail and ensuring consistency if the first value had not been a complex number... + if ( len && isArray( buf ) && isComplexLike( buf[0] ) ) { + buf = fromArray( new Float32Array( len*2 ), buf ); + if ( buf === null ) { + // We failed and we are now forced to allocate a new array :-( + if ( !isEven( len ) ) { + throw new RangeError( 'invalid argument. Array-like object input arguments must have a length which is a multiple of two. Length: `'+len+'`.' ); + } + // We failed, so fall back to directly setting values... + buf = new Float32Array( arguments[0] ); + } + } else { + if ( !isEven( len ) ) { + throw new RangeError( 'invalid argument. Array-like object and typed array input arguments must have a length which is a multiple of two. Length: `'+len+'`.' ); + } + buf = new Float32Array( buf ); + } + } else if ( isArrayBuffer( arguments[0] ) ) { + buf = arguments[ 0 ]; + if ( !isInteger( buf.byteLength/BYTES_PER_ELEMENT ) ) { + throw new RangeError( 'invalid argument. ArrayBuffer byte length must be a multiple of '+BYTES_PER_ELEMENT+'. Byte length: `'+buf.byteLength+'`.' ); + } + buf = new Float32Array( buf ); + } else if ( isObject( arguments[0] ) ) { + buf = arguments[ 0 ]; + if ( HAS_ITERATOR_SYMBOL === false ) { + throw new TypeError( 'invalid argument. Environment lacks Symbol.iterator support. Must provide a length, ArrayBuffer, typed array, or array-like object. Value: `'+buf+'`.' ); + } + if ( !isFunction( buf[ ITERATOR_SYMBOL ] ) ) { + throw new TypeError( 'invalid argument. Must provide a length, ArrayBuffer, typed array, array-like object, or an iterable. Value: `'+buf+'`.' ); + } + buf = buf[ ITERATOR_SYMBOL ](); + if ( !isFunction( buf.next ) ) { + throw new TypeError( 'invalid argument. Must provide a length, ArrayBuffer, typed array, array-like object, or an iterable.' ); + } + buf = fromIterator( buf ); + if ( buf instanceof Error ) { + throw buf; + } + buf = new Float32Array( buf ); + } else { + throw new TypeError( 'invalid argument. Must provide a length, ArrayBuffer, typed array, array-like object, or an iterable. Value: `'+arguments[0]+'`.' ); + } + } else { + buf = arguments[ 0 ]; + if ( !isArrayBuffer( buf ) ) { + throw new TypeError( 'invalid argument. First argument must be an array buffer. Value: `'+buf+'`.' ); + } + byteOffset = arguments[ 1 ]; + if ( !isNonNegativeInteger( byteOffset ) ) { + throw new TypeError( 'invalid argument. Byte offset must be a nonnegative integer. Value: `'+byteOffset+'`.' ); + } + if ( !isInteger( byteOffset/BYTES_PER_ELEMENT ) ) { + throw new RangeError( 'invalid argument. Byte offset must be a multiple of '+BYTES_PER_ELEMENT+'. Value: `'+byteOffset+'`.' ); + } + if ( nargs === 2 ) { + len = buf.byteLength - byteOffset; + if ( !isInteger( len/BYTES_PER_ELEMENT ) ) { + throw new RangeError( 'invalid arguments. ArrayBuffer view byte length must be a multiple of '+BYTES_PER_ELEMENT+'. View byte length: `'+len+'`.' ); + } + buf = new Float32Array( buf, byteOffset ); + } else { + len = arguments[ 2 ]; + if ( !isNonNegativeInteger( len ) ) { + throw new TypeError( 'invalid argument. Length must be a nonnegative integer. Value: `'+len+'`.' ); + } + if ( (len*BYTES_PER_ELEMENT) > (buf.byteLength-byteOffset) ) { + throw new RangeError( 'invalid arguments. ArrayBuffer has insufficient capacity. Either decrease the array length or provide a bigger buffer. Minimum capacity: `'+(len*BYTES_PER_ELEMENT)+'`.' ); + } + buf = new Float32Array( buf, byteOffset, len*2 ); + } + } + defineProperty( this, '_buffer', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': buf + }); + defineProperty( this, '_length', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': buf.length / 2 + }); + + return this; +} + +/** +* Size (in bytes) of each array element. +* +* @name BYTES_PER_ELEMENT +* @memberof Complex64Array +* @type {PositiveInteger} +* @default 8 +* +* @example +* var nbytes = Complex64Array.BYTES_PER_ELEMENT; +* // returns 8 +*/ +defineProperty( Complex64Array, 'BYTES_PER_ELEMENT', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': BYTES_PER_ELEMENT +}); + +/** +* Constructor name. +* +* @name name +* @memberof Complex64Array +* @type {string} +* @default 'Complex64Array' +* +* @example +* var str = Complex64Array.name; +* // returns 'Complex64Array' +*/ +defineProperty( Complex64Array, 'name', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': 'Complex64Array' +}); + +/** +* Creates a new 64-bit complex number array from an array-like object or an iterable. +* +* @name from +* @memberof Complex64Array +* @type {Function} +* @param {(ArrayLikeObject|Iterable)} src - array-like object or iterable +* @param {Function} [clbk] - callback to invoke for each source element +* @param {*} [thisArg] - context +* @throws {TypeError} `this` context must be a constructor +* @throws {TypeError} `this` must be a complex number array +* @throws {TypeError} first argument must be an array-like object or an iterable +* @throws {TypeError} second argument must be a function +* @throws {RangeError} array-like objects must have a length which is a multiple of two +* @throws {TypeError} an iterator must return either a two element array containing real and imaginary components or a complex number +* @throws {TypeError} when provided an iterator, a callback must return either a two element array containing real and imaginary components or a complex number +* @returns {Complex64Array} 64-bit complex number array +* +* @example +* var arr = Complex64Array.from( [ 1.0, -1.0 ] ); +* // returns +* +* var len = arr.length; +* // returns 1 +* +* @example +* var Complex64 = require( '@stdlib/complex/float32' ); +* +* var arr = Complex64Array.from( [ new Complex64( 1.0, 1.0 ) ] ); +* // returns +* +* var len = arr.length; +* // returns 1 +* +* @example +* var Complex64 = require( '@stdlib/complex/float32' ); +* var real = require( '@stdlib/complex/real' ); +* var imag = require( '@stdlib/complex/imag' ); +* +* function clbk( v ) { +* return new Complex64( real(v)*2.0, imag(v)*2.0 ); +* } +* +* var arr = Complex64Array.from( [ new Complex64( 1.0, 1.0 ) ], clbk ); +* // returns +* +* var len = arr.length; +* // returns 1 +*/ +defineProperty( Complex64Array, 'from', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': function from( src ) { + var thisArg; + var nargs; + var clbk; + var out; + var buf; + var tmp; + var len; + var flg; + var v; + var i; + var j; + if ( !isFunction( this ) ) { + throw new TypeError( 'invalid invocation. `this` context must be a constructor.' ); + } + if ( !isComplexArrayConstructor( this ) ) { + throw new TypeError( 'invalid invocation. `this` is not a complex number array.' ); + } + nargs = arguments.length; + if ( nargs > 1 ) { + clbk = arguments[ 1 ]; + if ( !isFunction( clbk ) ) { + throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+clbk+'`.' ); + } + if ( nargs > 2 ) { + thisArg = arguments[ 2 ]; + } + } + if ( isCollection( src ) ) { + if ( clbk ) { + // Note: array contents affect how we iterate over a provided data source. If only complex numbers, we can extract real and imaginary components. Otherwise, we assume a strided array where real and imaginary components are interleaved. In the former case, we expect a callback to return real and imaginary components (possibly as a complex number). In the latter case, we expect a callback to return *either* a real or imaginary component. + + // Detect whether we've been provided an array of complex numbers... + len = src.length; + for ( i = 0; i < len; i++ ) { + if ( !isComplexLike( src[ i ] ) ) { + flg = true; + break; + } + } + // If an array does not contain only complex numbers, then we assume interleaved real and imaginary components... + if ( flg ) { + if ( !isEven( len ) ) { + throw new RangeError( 'invalid argument. First argument must have a length which is a multiple of two. Length: `'+len+'`.' ); + } + out = new this( len/2 ); + buf = out._buffer; // eslint-disable-line no-underscore-dangle + for ( i = 0; i < len; i++ ) { + buf[ i ] = clbk.call( thisArg, src[ i ], i ); + } + } + // If an array contains only complex numbers, then we need to extract real and imaginary components... + else { + out = new this( len ); + buf = out._buffer; // eslint-disable-line no-underscore-dangle + j = 0; + for ( i = 0; i < len; i++ ) { + v = clbk.call( thisArg, src[ i ], i ); + if ( isComplexLike( v ) ) { + buf[ j ] = real( v ); + buf[ j+1 ] = imag( v ); + } else if ( isArrayLikeObject( v ) && v.length >= 2 ) { + buf[ j ] = v[ 0 ]; + buf[ j+1 ] = v[ 1 ]; + } else { + throw new TypeError( 'invalid argument. Callback must return either a two-element array containing real and imaginary components or a complex number. Value: `'+v+'`.' ); + } + j += 2; // stride + } + } + } else { + out = new this( src ); + } + } else if ( isObject( src ) && HAS_ITERATOR_SYMBOL && isFunction( src[ ITERATOR_SYMBOL ] ) ) { // eslint-disable-line max-len + buf = src[ ITERATOR_SYMBOL ](); + if ( !isFunction( buf.next ) ) { + throw new TypeError( 'invalid argument. First argument must be an array-like object or an iterable.' ); + } + if ( clbk ) { + tmp = fromIteratorMap( buf, clbk, thisArg ); + } else { + tmp = fromIterator( buf ); + } + if ( tmp instanceof Error ) { + throw tmp; + } + len = tmp.length / 2; + out = new this( len ); + buf = out._buffer; // eslint-disable-line no-underscore-dangle + for ( i = 0; i < len; i++ ) { + buf[ i ] = tmp[ i ]; + } + } else { + throw new TypeError( 'invalid argument. First argument must be an array-like object or an iterable. Value: `'+src+'`.' ); + } + return out; + } +}); + +/** +* Creates a new 64-bit complex number array from a variable number of arguments. +* +* @name of +* @memberof Complex64Array +* @type {Function} +* @param {...*} element - array elements +* @throws {TypeError} `this` context must be a constructor +* @throws {TypeError} `this` must be a complex number array +* @returns {Complex64Array} 64-bit complex number array +* +* @example +* var arr = Complex64Array.of( 1.0, 1.0, 1.0, 1.0 ); +* // returns +* +* var len = arr.length; +* // returns 2 +*/ +defineProperty( Complex64Array, 'of', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': function of() { + var args; + var i; + if ( !isFunction( this ) ) { + throw new TypeError( 'invalid invocation. `this` context must be a constructor.' ); + } + if ( !isComplexArrayConstructor( this ) ) { + throw new TypeError( 'invalid invocation. `this` is not a complex number array.' ); + } + args = []; + for ( i = 0; i < arguments.length; i++ ) { + args.push( arguments[ i ] ); + } + return new this( args ); + } +}); + +/** +* Pointer to the underlying data buffer. +* +* @name buffer +* @memberof Complex64Array.prototype +* @type {ArrayBuffer} +* +* @example +* var arr = new Complex64Array( 10 ); +* +* var buf = arr.buffer; +* // returns +*/ +defineProperty( Complex64Array.prototype, 'buffer', { + 'configurable': false, + 'enumerable': false, + 'get': function get() { + return this._buffer.buffer; + } +}); + +/** +* Size (in bytes) of the array. +* +* @name byteLength +* @memberof Complex64Array.prototype +* @type {NonNegativeInteger} +* +* @example +* var arr = new Complex64Array( 10 ); +* +* var byteLength = arr.byteLength; +* // returns 80 +*/ +defineProperty( Complex64Array.prototype, 'byteLength', { + 'configurable': false, + 'enumerable': false, + 'get': function get() { + return this._buffer.byteLength; + } +}); + +/** +* Offset (in bytes) of the array from the start of its underlying `ArrayBuffer`. +* +* @name byteOffset +* @memberof Complex64Array.prototype +* @type {NonNegativeInteger} +* +* @example +* var arr = new Complex64Array( 10 ); +* +* var byteOffset = arr.byteOffset; +* // returns 0 +*/ +defineProperty( Complex64Array.prototype, 'byteOffset', { + 'configurable': false, + 'enumerable': false, + 'get': function get() { + return this._buffer.byteOffset; + } +}); + +/** +* Size (in bytes) of each array element. +* +* @name BYTES_PER_ELEMENT +* @memberof Complex64Array.prototype +* @type {PositiveInteger} +* @default 8 +* +* @example +* var arr = new Complex64Array( 10 ); +* +* var nbytes = arr.BYTES_PER_ELEMENT; +* // returns 8 +*/ +defineProperty( Complex64Array.prototype, 'BYTES_PER_ELEMENT', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': Complex64Array.BYTES_PER_ELEMENT +}); + +/** +* Copies a sequence of elements within the array to the position starting at `target`. +* +* @name copyWithin +* @memberof Complex64Array.prototype +* @type {Function} +* @param {integer} target - index at which to start copying elements +* @param {integer} start - source index at which to copy elements from +* @param {integer} [end] - source index at which to stop copying elements from +* @throws {TypeError} `this` must be a complex number array +* @returns {Complex64Array} modified array +* +* @example +* var Complex64 = require( '@stdlib/complex/float32' ); +* var real = require( '@stdlib/complex/real' ); +* var imag = require( '@stdlib/complex/imag' ); +* +* var arr = new Complex64Array( 4 ); +* +* // Set the array elements: +* arr.set( new Complex64( 1.0, 1.0 ), 0 ); +* arr.set( new Complex64( 2.0, 2.0 ), 1 ); +* arr.set( new Complex64( 3.0, 3.0 ), 2 ); +* arr.set( new Complex64( 4.0, 4.0 ), 3 ); +* +* // Copy the first two elements to the last two elements: +* arr.copyWithin( 2, 0, 2 ); +* +* // Get the last array element: +* var z = arr.get( 3 ); +* +* var re = real( z ); +* // returns 2.0 +* +* var im = imag( z ); +* // returns 2.0 +*/ +defineProperty( Complex64Array.prototype, 'copyWithin', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': function copyWithin( target, start ) { + if ( !isComplexArray( this ) ) { + throw new TypeError( 'invalid invocation. `this` is not a complex number array.' ); + } + // FIXME: prefer a functional `copyWithin` implementation which addresses lack of universal browser support (e.g., IE11 and Safari) or ensure that typed arrays are polyfilled + if ( arguments.length === 2 ) { + this._buffer.copyWithin( target*2, start*2 ); + } else { + this._buffer.copyWithin( target*2, start*2, arguments[2]*2 ); + } + return this; + } +}); + +/** +* Returns an iterator for iterating over array key-value pairs. +* +* @name entries +* @memberof Complex64Array.prototype +* @type {Function} +* @throws {TypeError} `this` must be a complex number array +* @returns {Iterator} iterator +* +* @example +* var Complex64 = require( '@stdlib/complex/float32' ); +* +* var arr = [ +* new Complex64( 1.0, 1.0 ), +* new Complex64( 2.0, 2.0 ), +* new Complex64( 3.0, 3.0 ) +* ]; +* arr = new Complex64Array( arr ); +* +* // Create an iterator: +* var it = arr.entries(); +* +* // Iterate over the key-value pairs... +* var v = it.next().value; +* // returns [ 0, ] +* +* v = it.next().value; +* // returns [ 1, ] +* +* v = it.next().value; +* // returns [ 2, ] +* +* var bool = it.next().done; +* // returns true +*/ +defineProperty( Complex64Array.prototype, 'entries', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': function entries() { + var buffer; + var self; + var iter; + var len; + var FLG; + var i; + var j; + if ( !isComplexArray( this ) ) { + throw new TypeError( 'invalid invocation. `this` is not a complex number array.' ); + } + self = this; + buffer = this._buffer; + len = this._length; + + // Initialize the iteration indices: + i = -1; + j = -2; + + // Create an iterator protocol-compliant object: + iter = {}; + defineProperty( iter, 'next', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': next + }); + defineProperty( iter, 'return', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': end + }); + if ( ITERATOR_SYMBOL ) { + defineProperty( iter, ITERATOR_SYMBOL, { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': factory + }); + } + return iter; + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next() { + var z; + i += 1; + if ( FLG || i >= len ) { + return { + 'done': true + }; + } + j += 2; + z = new Complex64( buffer[ j ], buffer[ j+1 ] ); + return { + 'value': [ i, z ], + 'done': false + }; + } + + /** + * Finishes an iterator. + * + * @private + * @param {*} [value] - value to return + * @returns {Object} iterator protocol-compliant object + */ + function end( value ) { + FLG = true; + if ( arguments.length ) { + return { + 'value': value, + 'done': true + }; + } + return { + 'done': true + }; + } + + /** + * Returns a new iterator. + * + * @private + * @returns {Iterator} iterator + */ + function factory() { + return self.entries(); + } + } +}); + +/** +* Returns an array element. +* +* @name get +* @memberof Complex64Array.prototype +* @type {Function} +* @param {ArrayLikeObject} [out] - output array +* @param {NonNegativeInteger} i - element index +* @throws {TypeError} `this` must be a complex number array +* @throws {TypeError} index argument must be a nonnegative integer +* @throws {TypeError} output argument must be an array-like object +* @returns {(Complex64|ArrayLikeObject|void)} array element +* +* @example +* var arr = new Complex64Array( 10 ); +* +* var z = arr.get( 0 ); +* // returns +* +* arr.set( [ 1.0, -1.0 ], 0 ); +* +* z = arr.get( [ 0.0, 0.0 ], 0 ); +* // returns [ 1.0, -1.0 ] +* +* z = arr.get( 100 ); +* // returns undefined +*/ +defineProperty( Complex64Array.prototype, 'get', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': function get( i ) { + var idx; + var out; + var buf; + + if ( !isComplexArray( this ) ) { + throw new TypeError( 'invalid invocation. `this` is not a complex number array.' ); + } + buf = this._buffer; + if ( arguments.length > 1 ) { + idx = arguments[ 1 ]; + out = i; + if ( !isArrayLikeObject( out ) || out.length < 2 ) { + throw new TypeError( 'invalid argument. Output argument must be an array-like object. Value: `'+out+'`.' ); + } + } else { + idx = i; + } + if ( !isNonNegativeInteger( idx ) ) { + throw new TypeError( 'invalid argument. Index argument must be a nonnegative integer. Value: `'+idx+'`.' ); + } + if ( idx >= this._length ) { + return; + } + idx *= 2; + if ( out ) { + out[ 0 ] = buf[ idx ]; + out[ 1 ] = buf[ idx+1 ]; + return out; + } + return new Complex64( buf[ idx ], buf[ idx+1 ] ); + } +}); + +/** +* Number of array elements. +* +* @name length +* @memberof Complex64Array.prototype +* @type {NonNegativeInteger} +* +* @example +* var arr = new Complex64Array( 10 ); +* +* var len = arr.length; +* // returns 10 +*/ +defineProperty( Complex64Array.prototype, 'length', { + 'configurable': false, + 'enumerable': false, + 'get': function get() { + return this._length; + } +}); + +/** +* Sets an array element. +* +* ## Notes +* +* - When provided a typed array, real or complex, we must check whether the source array shares the same buffer as the target array and whether the underlying memory overlaps. In particular, we are concerned with the following scenario: +* +* ```text +* buf: --------------------- +* src: --------------------- +* ``` +* +* In the above, as we copy values from `src`, we will overwrite values in the `src` view, resulting in duplicated values copied into the end of `buf`, which is not intended. Hence, to avoid overwriting source values, we must **copy** source values to a temporary array. +* +* In the other overlapping scenario, +* +* ```text +* buf: --------------------- +* src: --------------------- +* ``` +* +* by the time we begin copying into the overlapping region, we are copying from the end of `src`, a non-overlapping region, which means we don't run the risk of copying copied values, rather than the original `src` values as intended. +* +* +* @name set +* @memberof Complex64Array.prototype +* @type {Function} +* @param {(Collection|Complex|ComplexArray)} value - value(s) +* @param {NonNegativeInteger} [i=0] - element index at which to start writing values +* @throws {TypeError} `this` must be a complex number array +* @throws {TypeError} first argument must be either a complex number, an array-like object, or a complex number array +* @throws {TypeError} index argument must be a nonnegative integer +* @throws {RangeError} array-like objects must have a length which is a multiple of two +* @throws {RangeError} index argument is out-of-bounds +* @throws {RangeError} target array lacks sufficient storage to accommodate source values +* @returns {void} +* +* @example +* var real = require( '@stdlib/complex/real' ); +* var imag = require( '@stdlib/complex/imag' ); +* +* var arr = new Complex64Array( 10 ); +* +* var z = arr.get( 0 ); +* // returns +* +* var re = real( z ); +* // returns 0.0 +* +* var im = imag( z ); +* // returns 0.0 +* +* arr.set( [ 1.0, -1.0 ], 0 ); +* +* z = arr.get( 0 ); +* // returns +* +* re = real( z ); +* // returns 1.0 +* +* im = imag( z ); +* // returns -1.0 +*/ +defineProperty( Complex64Array.prototype, 'set', { + 'configurable': false, + 'enumerable': false, + 'writable': false, + 'value': function set( value ) { + /* eslint-disable no-underscore-dangle */ + var sbuf; + var idx; + var buf; + var tmp; + var flg; + var N; + var v; + var i; + var j; + if ( !isComplexArray( this ) ) { + throw new TypeError( 'invalid invocation. `this` is not a complex number array.' ); + } + buf = this._buffer; + if ( arguments.length > 1 ) { + idx = arguments[ 1 ]; + if ( !isNonNegativeInteger( idx ) ) { + throw new TypeError( 'invalid argument. Index argument must be a nonnegative integer. Value: `'+idx+'`.' ); + } + } else { + idx = 0; + } + if ( isComplexLike( value ) ) { + if ( idx >= this._length ) { + throw new RangeError( 'invalid argument. Index argument is out-of-bounds. Value: `'+idx+'`.' ); + } + idx *= 2; + buf[ idx ] = real( value ); + buf[ idx+1 ] = imag( value ); + return; + } + if ( isComplexArray( value ) ) { + N = value._length; + if ( idx+N > this._length ) { + throw new RangeError( 'invalid arguments. Target array lacks sufficient storage to accommodate source values.' ); + } + sbuf = value._buffer; + + // Check for overlapping memory... + j = buf.byteOffset + (idx*BYTES_PER_ELEMENT); + if ( + sbuf.buffer === buf.buffer && + ( + sbuf.byteOffset < j && + sbuf.byteOffset+sbuf.byteLength > j + ) + ) { + // We need to copy source values... + tmp = new Float32Array( sbuf.length ); + for ( i = 0; i < sbuf.length; i++ ) { + tmp[ i ] = sbuf[ i ]; + } + sbuf = tmp; + } + idx *= 2; + j = 0; + for ( i = 0; i < N; i++ ) { + buf[ idx ] = sbuf[ j ]; + buf[ idx+1 ] = sbuf[ j+1 ]; + idx += 2; // stride + j += 2; // stride + } + return; + } + if ( isCollection( value ) ) { + // Detect whether we've been provided an array of complex numbers... + N = value.length; + for ( i = 0; i < N; i++ ) { + if ( !isComplexLike( value[ i ] ) ) { + flg = true; + break; + } + } + // If an array does not contain only complex numbers, then we assume interleaved real and imaginary components... + if ( flg ) { + if ( !isEven( N ) ) { + throw new RangeError( 'invalid argument. Array-like object arguments must have a length which is a multiple of two. Length: `'+N+'`.' ); + } + if ( idx+(N/2) > this._length ) { + throw new RangeError( 'invalid arguments. Target array lacks sufficient storage to accommodate source values.' ); + } + sbuf = value; + + // Check for overlapping memory... + j = buf.byteOffset + (idx*BYTES_PER_ELEMENT); + if ( + sbuf.buffer === buf.buffer && + ( + sbuf.byteOffset < j && + sbuf.byteOffset+sbuf.byteLength > j + ) + ) { + // We need to copy source values... + tmp = new Float32Array( N ); + for ( i = 0; i < N; i++ ) { + tmp[ i ] = sbuf[ i ]; + } + sbuf = tmp; + } + idx *= 2; + N /= 2; + j = 0; + for ( i = 0; i < N; i++ ) { + buf[ idx ] = sbuf[ j ]; + buf[ idx+1 ] = sbuf[ j+1 ]; + idx += 2; // stride + j += 2; // stride + } + return; + } + // If an array contains only complex numbers, then we need to extract real and imaginary components... + if ( idx+N > this._length ) { + throw new RangeError( 'invalid arguments. Target array lacks sufficient storage to accommodate source values.' ); + } + idx *= 2; + for ( i = 0; i < N; i++ ) { + v = value[ i ]; + buf[ idx ] = real( v ); + buf[ idx+1 ] = imag( v ); + idx += 2; // stride + } + return; + } + throw new TypeError( 'invalid argument. First argument must be either a complex number, an array-like object, or a complex number array. Value: `'+value+'`.' ); + + /* eslint-enable no-underscore-dangle */ + } +}); + + +// EXPORTS // + +module.exports = Complex64Array; diff --git a/complex64/package.json b/complex64/package.json new file mode 100644 index 00000000..f8c7b759 --- /dev/null +++ b/complex64/package.json @@ -0,0 +1,72 @@ +{ + "name": "@stdlib/array/complex64", + "version": "0.0.0", + "description": "Complex64Array.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structure", + "array", + "typed", + "typed array", + "typed-array", + "complex64array", + "complex64", + "complex", + "cmplx", + "real", + "imaginary", + "imag", + "float", + "single-precision", + "ieee754" + ] +} diff --git a/complex64/test/test.copy_within.js b/complex64/test/test.copy_within.js new file mode 100644 index 00000000..7f7318d4 --- /dev/null +++ b/complex64/test/test.copy_within.js @@ -0,0 +1,379 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var hasOwnProp = require( '@stdlib/assert/has-own-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var isPositiveZero = require( '@stdlib/assert/is-positive-zero' ).isPrimitive; +var isNegativeZero = require( '@stdlib/assert/is-negative-zero' ).isPrimitive; +var Complex64 = require( '@stdlib/complex/float32' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Complex64Array = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof Complex64Array, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'attached to the prototype of the main export is a `copyWithin` method for copying a sequence of array elements within a complex number array', function test( t ) { + t.strictEqual( hasOwnProp( Complex64Array.prototype, 'copyWithin' ), true, 'has property' ); + t.strictEqual( isFunction( Complex64Array.prototype.copyWithin ), true, 'has method' ); + t.end(); +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a complex number array instance', function test( t ) { + var values; + var arr; + var i; + + arr = new Complex64Array( 5 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0 ); + }; + } +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a complex number array instance (end)', function test( t ) { + var values; + var arr; + var i; + + arr = new Complex64Array( 5 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0, 5 ); + }; + } +}); + +tape( 'the method copies a sequence of elements within an array', function test( t ) { + var arr; + var buf; + + arr = [ + new Complex64( 0.0, -0.0 ), + new Complex64( 1.0, -1.0 ), + new Complex64( 2.0, -2.0 ), + new Complex64( 3.0, -3.0 ), + new Complex64( 4.0, -4.0 ) + ]; + arr = new Complex64Array( arr ); + + arr.copyWithin( 0, 3 ); + + buf = new Float32Array( arr.buffer ); + + // Overwritten: + t.strictEqual( buf[ 0 ], 3.0, 'returns expected real for complex number 0' ); + t.strictEqual( buf[ 1 ], -3.0, 'returns expected imag for complex number 0' ); + t.strictEqual( buf[ 2 ], 4.0, 'returns expected real for complex number 1' ); + t.strictEqual( buf[ 3 ], -4.0, 'returns expected imag for complex number 1' ); + + // Remain the same: + t.strictEqual( buf[ 4 ], 2.0, 'returns expected real for complex number 2' ); + t.strictEqual( buf[ 5 ], -2.0, 'returns expected imag for complex number 2' ); + t.strictEqual( buf[ 6 ], 3.0, 'returns expected real for complex number 3' ); + t.strictEqual( buf[ 7 ], -3.0, 'returns expected imag for complex number 3' ); + t.strictEqual( buf[ 8 ], 4.0, 'returns expected real for complex number 4' ); + t.strictEqual( buf[ 9 ], -4.0, 'returns expected imag for complex number 4' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within an array (negative target)', function test( t ) { + var arr; + var buf; + + arr = [ + new Complex64( 0.0, -0.0 ), + new Complex64( 1.0, -1.0 ), + new Complex64( 2.0, -2.0 ), + new Complex64( 3.0, -3.0 ), + new Complex64( 4.0, -4.0 ) + ]; + arr = new Complex64Array( arr ); + + arr.copyWithin( -arr.length, 3 ); + + buf = new Float32Array( arr.buffer ); + + // Overwritten: + t.strictEqual( buf[ 0 ], 3.0, 'returns expected real for complex number 0' ); + t.strictEqual( buf[ 1 ], -3.0, 'returns expected imag for complex number 0' ); + t.strictEqual( buf[ 2 ], 4.0, 'returns expected real for complex number 1' ); + t.strictEqual( buf[ 3 ], -4.0, 'returns expected imag for complex number 1' ); + + // Remain the same: + t.strictEqual( buf[ 4 ], 2.0, 'returns expected real for complex number 2' ); + t.strictEqual( buf[ 5 ], -2.0, 'returns expected imag for complex number 2' ); + t.strictEqual( buf[ 6 ], 3.0, 'returns expected real for complex number 3' ); + t.strictEqual( buf[ 7 ], -3.0, 'returns expected imag for complex number 3' ); + t.strictEqual( buf[ 8 ], 4.0, 'returns expected real for complex number 4' ); + t.strictEqual( buf[ 9 ], -4.0, 'returns expected imag for complex number 4' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within an array (negative start)', function test( t ) { + var arr; + var buf; + + arr = [ + new Complex64( 0.0, -0.0 ), + new Complex64( 1.0, -1.0 ), + new Complex64( 2.0, -2.0 ), + new Complex64( 3.0, -3.0 ), + new Complex64( 4.0, -4.0 ) + ]; + arr = new Complex64Array( arr ); + + arr.copyWithin( 0, -2 ); + + buf = new Float32Array( arr.buffer ); + + // Overwritten: + t.strictEqual( buf[ 0 ], 3.0, 'returns expected real for complex number 0' ); + t.strictEqual( buf[ 1 ], -3.0, 'returns expected imag for complex number 0' ); + t.strictEqual( buf[ 2 ], 4.0, 'returns expected real for complex number 1' ); + t.strictEqual( buf[ 3 ], -4.0, 'returns expected imag for complex number 1' ); + + // Remain the same: + t.strictEqual( buf[ 4 ], 2.0, 'returns expected real for complex number 2' ); + t.strictEqual( buf[ 5 ], -2.0, 'returns expected imag for complex number 2' ); + t.strictEqual( buf[ 6 ], 3.0, 'returns expected real for complex number 3' ); + t.strictEqual( buf[ 7 ], -3.0, 'returns expected imag for complex number 3' ); + t.strictEqual( buf[ 8 ], 4.0, 'returns expected real for complex number 4' ); + t.strictEqual( buf[ 9 ], -4.0, 'returns expected imag for complex number 4' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within an array (end=length)', function test( t ) { + var arr; + var buf; + + arr = [ + new Complex64( 0.0, -0.0 ), + new Complex64( 1.0, -1.0 ), + new Complex64( 2.0, -2.0 ), + new Complex64( 3.0, -3.0 ), + new Complex64( 4.0, -4.0 ) + ]; + arr = new Complex64Array( arr ); + + arr.copyWithin( 0, 3, arr.length ); + + buf = new Float32Array( arr.buffer ); + + // Overwritten: + t.strictEqual( buf[ 0 ], 3.0, 'returns expected real for complex number 0' ); + t.strictEqual( buf[ 1 ], -3.0, 'returns expected imag for complex number 0' ); + t.strictEqual( buf[ 2 ], 4.0, 'returns expected real for complex number 1' ); + t.strictEqual( buf[ 3 ], -4.0, 'returns expected imag for complex number 1' ); + + // Remain the same: + t.strictEqual( buf[ 4 ], 2.0, 'returns expected real for complex number 2' ); + t.strictEqual( buf[ 5 ], -2.0, 'returns expected imag for complex number 2' ); + t.strictEqual( buf[ 6 ], 3.0, 'returns expected real for complex number 3' ); + t.strictEqual( buf[ 7 ], -3.0, 'returns expected imag for complex number 3' ); + t.strictEqual( buf[ 8 ], 4.0, 'returns expected real for complex number 4' ); + t.strictEqual( buf[ 9 ], -4.0, 'returns expected imag for complex number 4' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within an array (non-inclusive end)', function test( t ) { + var arr; + var buf; + + arr = [ + new Complex64( 0.0, -0.0 ), + new Complex64( 1.0, -1.0 ), + new Complex64( 2.0, -2.0 ), + new Complex64( 3.0, -3.0 ), + new Complex64( 4.0, -4.0 ) + ]; + arr = new Complex64Array( arr ); + + arr.copyWithin( 2, 0, 2 ); + + buf = new Float32Array( arr.buffer ); + + // Remain the same: + t.strictEqual( isPositiveZero( buf[ 0 ] ), true, 'returns expected real for complex number 0' ); + t.strictEqual( isNegativeZero( buf[ 1 ] ), true, 'returns expected imag for complex number 0' ); + t.strictEqual( buf[ 2 ], 1.0, 'returns expected real for complex number 1' ); + t.strictEqual( buf[ 3 ], -1.0, 'returns expected imag for complex number 1' ); + + // Overwritten: + t.strictEqual( isPositiveZero( buf[ 4 ] ), true, 'returns expected real for complex number 2' ); + t.strictEqual( isNegativeZero( buf[ 5 ] ), true, 'returns expected imag for complex number 2' ); + t.strictEqual( buf[ 6 ], 1.0, 'returns expected real for complex number 3' ); + t.strictEqual( buf[ 7 ], -1.0, 'returns expected imag for complex number 3' ); + + // Remain the same: + t.strictEqual( buf[ 8 ], 4.0, 'returns expected real for complex number 4' ); + t.strictEqual( buf[ 9 ], -4.0, 'returns expected imag for complex number 4' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within an array (negative end)', function test( t ) { + var arr; + var buf; + + arr = [ + new Complex64( 0.0, -0.0 ), + new Complex64( 1.0, -1.0 ), + new Complex64( 2.0, -2.0 ), + new Complex64( 3.0, -3.0 ), + new Complex64( 4.0, -4.0 ) + ]; + arr = new Complex64Array( arr ); + + arr.copyWithin( 2, 0, -3 ); + + buf = new Float32Array( arr.buffer ); + + // Remain the same: + t.strictEqual( isPositiveZero( buf[ 0 ] ), true, 'returns expected real for complex number 0' ); + t.strictEqual( isNegativeZero( buf[ 1 ] ), true, 'returns expected imag for complex number 0' ); + t.strictEqual( buf[ 2 ], 1.0, 'returns expected real for complex number 1' ); + t.strictEqual( buf[ 3 ], -1.0, 'returns expected imag for complex number 1' ); + + // Overwritten: + t.strictEqual( isPositiveZero( buf[ 4 ] ), true, 'returns expected real for complex number 2' ); + t.strictEqual( isNegativeZero( buf[ 5 ] ), true, 'returns expected imag for complex number 2' ); + t.strictEqual( buf[ 6 ], 1.0, 'returns expected real for complex number 3' ); + t.strictEqual( buf[ 7 ], -1.0, 'returns expected imag for complex number 3' ); + + // Remain the same: + t.strictEqual( buf[ 8 ], 4.0, 'returns expected real for complex number 4' ); + t.strictEqual( buf[ 9 ], -4.0, 'returns expected imag for complex number 4' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within an array (target >= length)', function test( t ) { + var arr; + var buf; + + arr = [ + new Complex64( 0.0, -0.0 ), + new Complex64( 1.0, -1.0 ), + new Complex64( 2.0, -2.0 ), + new Complex64( 3.0, -3.0 ), + new Complex64( 4.0, -4.0 ) + ]; + arr = new Complex64Array( arr ); + + arr.copyWithin( arr.length, 3 ); + + buf = new Float32Array( arr.buffer ); + + // Remain the same: + t.strictEqual( isPositiveZero( buf[ 0 ] ), true, 'returns expected real for complex number 0' ); + t.strictEqual( isNegativeZero( buf[ 1 ] ), true, 'returns expected imag for complex number 0' ); + t.strictEqual( buf[ 2 ], 1.0, 'returns expected real for complex number 1' ); + t.strictEqual( buf[ 3 ], -1.0, 'returns expected imag for complex number 1' ); + t.strictEqual( buf[ 4 ], 2.0, 'returns expected real for complex number 2' ); + t.strictEqual( buf[ 5 ], -2.0, 'returns expected imag for complex number 2' ); + t.strictEqual( buf[ 6 ], 3.0, 'returns expected real for complex number 3' ); + t.strictEqual( buf[ 7 ], -3.0, 'returns expected imag for complex number 3' ); + t.strictEqual( buf[ 8 ], 4.0, 'returns expected real for complex number 4' ); + t.strictEqual( buf[ 9 ], -4.0, 'returns expected imag for complex number 4' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within an array (target > start)', function test( t ) { + var arr; + var buf; + + arr = [ + new Complex64( 0.0, -0.0 ), + new Complex64( 1.0, -1.0 ), + new Complex64( 2.0, -2.0 ), + new Complex64( 3.0, -3.0 ), + new Complex64( 4.0, -4.0 ) + ]; + arr = new Complex64Array( arr ); + + arr.copyWithin( 2, 0 ); + + buf = new Float32Array( arr.buffer ); + + // Remain the same: + t.strictEqual( isPositiveZero( buf[ 0 ] ), true, 'returns expected real for complex number 0' ); + t.strictEqual( isNegativeZero( buf[ 1 ] ), true, 'returns expected imag for complex number 0' ); + t.strictEqual( buf[ 2 ], 1.0, 'returns expected real for complex number 1' ); + t.strictEqual( buf[ 3 ], -1.0, 'returns expected imag for complex number 1' ); + + // Overwritten: + t.strictEqual( isPositiveZero( buf[ 4 ] ), true, 'returns expected real for complex number 2' ); + t.strictEqual( isNegativeZero( buf[ 5 ] ), true, 'returns expected imag for complex number 2' ); + t.strictEqual( buf[ 6 ], 1.0, 'returns expected real for complex number 3' ); + t.strictEqual( buf[ 7 ], -1.0, 'returns expected imag for complex number 3' ); + t.strictEqual( buf[ 8 ], 2.0, 'returns expected real for complex number 4' ); + t.strictEqual( buf[ 9 ], -2.0, 'returns expected imag for complex number 4' ); + + t.end(); +}); diff --git a/complex64/test/test.entries.js b/complex64/test/test.entries.js new file mode 100644 index 00000000..ab8040bb --- /dev/null +++ b/complex64/test/test.entries.js @@ -0,0 +1,249 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var hasOwnProp = require( '@stdlib/assert/has-own-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var isArray = require( '@stdlib/assert/is-array' ); +var isComplex64 = require( '@stdlib/assert/is-complex64' ); +var real = require( '@stdlib/complex/real' ); +var imag = require( '@stdlib/complex/imag' ); +var ITERATOR_SYMBOL = require( '@stdlib/symbol/iterator' ); +var Complex64Array = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof Complex64Array, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'attached to the prototype of the main export is an `entries` method for returning an iterator for iterating over array key-value pairs', function test( t ) { + t.strictEqual( hasOwnProp( Complex64Array.prototype, 'entries' ), true, 'has property' ); + t.strictEqual( isFunction( Complex64Array.prototype.entries ), true, 'has method' ); + t.end(); +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a complex number array instance', function test( t ) { + var values; + var arr; + var i; + + arr = new Complex64Array( 5 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.entries.call( value ); + }; + } +}); + +tape( 'the method returns an iterator protocol-compliant object', function test( t ) { + var buf; + var arr; + var it; + var v; + var i; + var j; + + buf = [ 1.0, -1.0, 2.0, -2.0, 3.0, -3.0, 4.0, -4.0 ]; + arr = new Complex64Array( buf ); + + it = arr.entries(); + t.strictEqual( it.next.length, 0, 'has zero arity' ); + + j = 0; + for ( i = 0; i < arr.length; i++ ) { + v = it.next(); + t.strictEqual( isArray( v.value ), true, 'returns an array' ); + t.strictEqual( v.value[ 0 ], i, 'returns an index' ); + t.strictEqual( isComplex64( v.value[ 1 ] ), true, 'returns a complex number' ); + t.strictEqual( real( v.value[ 1 ] ), buf[ j ], 'returns expected real component' ); + t.strictEqual( imag( v.value[ 1 ] ), buf[ j+1 ], 'returns expected imaginary component' ); + t.strictEqual( typeof v.done, 'boolean', 'returns a boolean' ); + + j += 2; // stride + } + t.end(); +}); + +tape( 'the method returns an iterator which has a `return` method for closing an iterator (no argument)', function test( t ) { + var buf; + var arr; + var it; + var v; + + buf = [ 1.0, -1.0, 2.0, -2.0, 3.0, -3.0, 4.0, -4.0 ]; + arr = new Complex64Array( buf ); + + it = arr.entries(); + + v = it.next(); + t.strictEqual( real( v.value[ 1 ] ), buf[ 0 ], 'returns expected value' ); + t.strictEqual( imag( v.value[ 1 ] ), buf[ 1 ], 'returns expected value' ); + t.strictEqual( v.done, false, 'returns expected value' ); + + v = it.next(); + t.strictEqual( real( v.value[ 1 ] ), buf[ 2 ], 'returns expected value' ); + t.strictEqual( imag( v.value[ 1 ] ), buf[ 3 ], 'returns expected value' ); + t.strictEqual( v.done, false, 'returns expected value' ); + + v = it.return(); + t.strictEqual( v.value, void 0, 'returns expected value' ); + t.strictEqual( v.done, true, 'returns expected value' ); + + v = it.next(); + t.strictEqual( v.value, void 0, 'returns expected value' ); + t.strictEqual( v.done, true, 'returns expected value' ); + + v = it.next(); + t.strictEqual( v.value, void 0, 'returns expected value' ); + t.strictEqual( v.done, true, 'returns expected value' ); + + v = it.next(); + t.strictEqual( v.value, void 0, 'returns expected value' ); + t.strictEqual( v.done, true, 'returns expected value' ); + + v = it.next(); + t.strictEqual( v.value, void 0, 'returns expected value' ); + t.strictEqual( v.done, true, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method returns an iterator which has a `return` method for closing an iterator (argument)', function test( t ) { + var buf; + var arr; + var it; + var v; + + buf = [ 1.0, -1.0, 2.0, -2.0, 3.0, -3.0, 4.0, -4.0 ]; + arr = new Complex64Array( buf ); + + it = arr.entries(); + + v = it.next(); + t.strictEqual( real( v.value[ 1 ] ), buf[ 0 ], 'returns expected value' ); + t.strictEqual( imag( v.value[ 1 ] ), buf[ 1 ], 'returns expected value' ); + t.strictEqual( v.done, false, 'returns expected value' ); + + v = it.next(); + t.strictEqual( real( v.value[ 1 ] ), buf[ 2 ], 'returns expected value' ); + t.strictEqual( imag( v.value[ 1 ] ), buf[ 3 ], 'returns expected value' ); + t.strictEqual( v.done, false, 'returns expected value' ); + + v = it.return( 'finished' ); + t.strictEqual( v.value, 'finished', 'returns expected value' ); + t.strictEqual( v.done, true, 'returns expected value' ); + + v = it.next(); + t.strictEqual( v.value, void 0, 'returns expected value' ); + t.strictEqual( v.done, true, 'returns expected value' ); + + v = it.next(); + t.strictEqual( v.value, void 0, 'returns expected value' ); + t.strictEqual( v.done, true, 'returns expected value' ); + + v = it.next(); + t.strictEqual( v.value, void 0, 'returns expected value' ); + t.strictEqual( v.done, true, 'returns expected value' ); + + v = it.next(); + t.strictEqual( v.value, void 0, 'returns expected value' ); + t.strictEqual( v.done, true, 'returns expected value' ); + + t.end(); +}); + +tape( 'if an environment supports `Symbol.iterator`, the method returns an iterable', function test( t ) { + var Complex64Array; + var arr; + var buf; + var it1; + var it2; + var v1; + var v2; + var i; + + Complex64Array = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + buf = [ 1.0, -1.0, 2.0, -2.0, 3.0, -3.0, 4.0, -4.0 ]; + arr = new Complex64Array( buf ); + + it1 = arr.entries(); + t.strictEqual( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.strictEqual( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.strictEqual( typeof it2, 'object', 'returns an object' ); + t.strictEqual( typeof it2.next, 'function', 'has `next` method' ); + t.strictEqual( typeof it2.return, 'function', 'has `return` method' ); + + for ( i = 0; i < arr.length; i++ ) { + v1 = it1.next().value; + v2 = it2.next().value; + t.strictEqual( v1[ 0 ], v2[ 0 ], 'returns expected value' ); + t.strictEqual( real( v1[ 1 ] ), real( v2[ 1 ] ), 'returns expected value' ); + t.strictEqual( imag( v1[ 1 ] ), imag( v2[ 1 ] ), 'returns expected value' ); + } + t.end(); +}); + +tape( 'if an environment does not support `Symbol.iterator`, the method does not return an "iterable"', function test( t ) { + var Complex64Array; + var arr; + var buf; + var it; + + Complex64Array = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + buf = [ 1.0, -1.0, 2.0, -2.0, 3.0, -3.0, 4.0, -4.0 ]; + arr = new Complex64Array( buf ); + + it = arr.entries(); + t.strictEqual( it[ ITERATOR_SYMBOL ], void 0, 'does not have property' ); + + t.end(); +}); diff --git a/complex64/test/test.from.js b/complex64/test/test.from.js new file mode 100644 index 00000000..4aeb2f16 --- /dev/null +++ b/complex64/test/test.from.js @@ -0,0 +1,1099 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var Float32Array = require( '@stdlib/array/float32' ); +var hasOwnProp = require( '@stdlib/assert/has-own-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var Complex64 = require( '@stdlib/complex/float32' ); +var real = require( '@stdlib/complex/real' ); +var imag = require( '@stdlib/complex/imag' ); +var Complex64Array = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof Complex64Array, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'attached to the main export is a `from` method for creating a complex number array from an array-like object or iterable', function test( t ) { + var arr; + + t.strictEqual( hasOwnProp( Complex64Array, 'from' ), true, 'has property' ); + t.strictEqual( isFunction( Complex64Array.from ), true, 'has method' ); + + arr = Complex64Array.from( [] ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns an instance' ); + + t.end(); +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a constructor', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return Complex64Array.from.call( value, [] ); + }; + } +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a complex array constructor', function test( t ) { + var values; + var i; + + values = [ + Complex64, + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return Complex64Array.from.call( value, [] ); + }; + } +}); + +tape( 'the method throws an error if not provided an iterable or array-like object', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return Complex64Array.from( value ); + }; + } +}); + +tape( 'the method throws an error if not provided an iterable or array-like object (callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return Complex64Array.from( value, clbk ); + }; + } + + function clbk() { + return [ 1.0, 1.0 ]; + } +}); + +tape( 'the method throws an error if not provided an iterable or array-like object (callback, thisArg)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return Complex64Array.from( value, clbk, {} ); + }; + } + + function clbk() { + return [ 1.0, 1.0 ]; + } +}); + +tape( 'the method throws an error if provided a second argument which is not a function', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return Complex64Array.from( [], value ); + }; + } +}); + +tape( 'the method throws an error if provided a second argument which is not a function (thisArg)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return Complex64Array.from( [], value, {} ); + }; + } +}); + +tape( 'the method returns a complex number array', function test( t ) { + var arr; + var z; + var v; + + // Generic array: + arr = Complex64Array.from( [] ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 0, 'returns expected value' ); + + arr = Complex64Array.from( [ 1.0, 2.0, 3.0, 4.0 ] ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 2, 'returns expected value' ); + + // Generic array containing complex numbers: + arr = Complex64Array.from( [ new Complex64( 1.0, 1.0 ) ] ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 1, 'returns expected value' ); + + z = new Complex64( 1.0, 0.0 ); + z.valueOf = valueOf( z ); + arr = Complex64Array.from( [ z, 1.0 ] ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 1, 'returns expected value' ); + + z = new Complex64( 1.0, 0.0 ); + z.valueOf = valueOf( z ); + arr = Complex64Array.from( [ 1.0, z ] ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 1, 'returns expected value' ); + + // Typed array: + arr = Complex64Array.from( new Float32Array( 0 ) ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 0, 'returns expected value' ); + + arr = Complex64Array.from( new Float32Array( [ 1.0, 1.0 ] ) ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 1, 'returns expected value' ); + + t.end(); + + function valueOf( z ) { + return function valueOf() { + return real( z ); + }; + } +}); + +tape( 'the method returns a complex number array (iterable)', function test( t ) { + var Complex64Array; + var iter1; + var iter2; + var arr; + var v; + + Complex64Array = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport, + '@stdlib/symbol/iterator': '__SYMBOL_ITERATOR__' + }); + + iter1 = { + 'next': next1, + 'i': 0, + 'N': 4 + }; + arr = Complex64Array.from( createIterable( iter1 ) ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, iter1.N, 'returns expected value' ); + + iter2 = { + 'next': next2, + 'i': 0, + 'N': 4 + }; + arr = Complex64Array.from( createIterable( iter2 ) ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, iter2.N, 'returns expected value' ); + + t.end(); + + function hasSupport() { + return true; + } + + function createIterable( iterator ) { + var it = {}; + it[ '__SYMBOL_ITERATOR__' ] = iterable; + return it; + + function iterable() { + return iterator; + } + } + + function next1() { + iter1.i += 1; + if ( iter1.i <= iter1.N ) { + return { + 'value': [ 1.0, 1.0 ] + }; + } + return { + 'done': true + }; + } + + function next2() { + iter2.i += 1; + if ( iter2.i <= iter2.N ) { + return { + 'value': new Complex64( 1.0, 1.0 ) + }; + } + return { + 'done': true + }; + } +}); + +tape( 'the method supports providing a "map" function which is invoked for each source element', function test( t ) { + var arr; + var z; + var v; + + // Generic array: + arr = Complex64Array.from( [], clbk1 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 0, 'returns expected value' ); + + arr = Complex64Array.from( [ 1.0, 2.0, 3.0, 4.0 ], clbk1 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 2, 'returns expected value' ); + + // Generic array containing complex numbers: + arr = Complex64Array.from( [ new Complex64( 1.0, 1.0 ) ], clbk2 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 1, 'returns expected value' ); + + arr = Complex64Array.from( [ new Complex64( 1.0, 1.0 ) ], clbk3 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 1, 'returns expected value' ); + + z = new Complex64( 1.0, 0.0 ); + z.valueOf = valueOf( z ); + arr = Complex64Array.from( [ z, 1.0 ], clbk1 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 1, 'returns expected value' ); + + z = new Complex64( 1.0, 0.0 ); + z.valueOf = valueOf( z ); + arr = Complex64Array.from( [ 1.0, z ], clbk1 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 1, 'returns expected value' ); + + // Typed array: + arr = Complex64Array.from( new Float32Array( 0 ), clbk1 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 0, 'returns expected value' ); + + arr = Complex64Array.from( new Float32Array( [ 1.0, 1.0 ] ), clbk1 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 1, 'returns expected value' ); + + t.end(); + + function valueOf( z ) { + return function valueOf() { + return real( z ); + }; + } + + function clbk1( v ) { + return v; + } + + function clbk2() { + return [ 1.0, 1.0 ]; + } + + function clbk3( v ) { + return new Complex64( real(v)*2.0, imag(v)*2.0 ); + } +}); + +tape( 'the method supports providing a "map" function which is invoked for each iterated value', function test( t ) { + var Complex64Array; + var iter1; + var iter2; + var arr; + var v; + + Complex64Array = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport, + '@stdlib/symbol/iterator': '__SYMBOL_ITERATOR__' + }); + + iter1 = { + 'next': next1, + 'i': 0, + 'N': 4 + }; + arr = Complex64Array.from( createIterable( iter1 ), clbk1 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, iter1.N, 'returns expected value' ); + + iter2 = { + 'next': next2, + 'i': 0, + 'N': 4 + }; + arr = Complex64Array.from( createIterable( iter2 ), clbk2 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, iter2.N, 'returns expected value' ); + + t.end(); + + function hasSupport() { + return true; + } + + function createIterable( iterator ) { + var it = {}; + it[ '__SYMBOL_ITERATOR__' ] = iterable; + return it; + + function iterable() { + return iterator; + } + } + + function next1() { + iter1.i += 1; + if ( iter1.i <= iter1.N ) { + return { + 'value': [ 1.0, 1.0 ] + }; + } + return { + 'done': true + }; + } + + function clbk1( v ) { + v[ 0 ] += 1.0; + v[ 1 ] += 1.0; + return v; + } + + function next2() { + iter2.i += 1; + if ( iter2.i <= iter2.N ) { + return { + 'value': new Complex64( 1.0, 1.0 ) + }; + } + return { + 'done': true + }; + } + + function clbk2( v ) { + return new Complex64( real(v)*2.0, imag(v)*2.0 ); + } +}); + +tape( 'the method supports providing a `this` context for a provided map function', function test( t ) { + var arr; + var ctx; + + ctx = { + 'count': 0 + }; + arr = Complex64Array.from( [ 1.0, 2.0, 3.0, 4.0 ], clbk1, ctx ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + t.strictEqual( ctx.count, 4, 'returns expected value' ); + + ctx = { + 'count': 0 + }; + arr = [ new Complex64( 1.0, 1.0 ), new Complex64( -1.0, -1.0 ) ]; + arr = Complex64Array.from( arr, clbk2, ctx ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + t.strictEqual( ctx.count, 2, 'returns expected value' ); + + t.end(); + + function clbk1( v ) { + this.count += 1; // eslint-disable-line no-invalid-this + return v; + } + + function clbk2( v ) { + this.count += 1; // eslint-disable-line no-invalid-this + return new Complex64( real(v)*2.0, imag(v)*2.0 ); + } +}); + +tape( 'the method supports providing a `this` context for a provided map function (iterable)', function test( t ) { + var Complex64Array; + var iter; + var ctx; + var arr; + + Complex64Array = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport, + '@stdlib/symbol/iterator': '__SYMBOL_ITERATOR__' + }); + + iter = { + 'next': next, + 'i': 0, + 'N': 4 + }; + ctx = { + 'count': 0 + }; + + arr = Complex64Array.from( createIterable( iter ), clbk, ctx ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + t.strictEqual( ctx.count, 4, 'returns expected value' ); + + t.end(); + + function hasSupport() { + return true; + } + + function createIterable( iterator ) { + var it = {}; + it[ '__SYMBOL_ITERATOR__' ] = iterable; + return it; + + function iterable() { + return iterator; + } + } + + function next() { + iter.i += 1; + if ( iter.i <= iter.N ) { + return { + 'value': [ 1.0, 1.0 ] + }; + } + return { + 'done': true + }; + } + + function clbk( v ) { + this.count += 1; // eslint-disable-line no-invalid-this + v[ 0 ] += 1.0; + v[ 1 ] += 1.0; + return v; + } +}); + +tape( 'the method throws an error if provided a generic array-like object having an odd length', function test( t ) { + var values; + var i; + + values = [ + [ 1, 2, 3 ], + new Float32Array( [ 1, 2, 3 ] ), + { + 'length': 3, + '0': 1, + '1': 2, + '2': 3 + }, + [ new Complex64( 1.0, 1.0 ), 1.0, 1.0 ] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), RangeError, 'throws an error when provided an array-like object having a length equal to '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return Complex64Array.from( value ); + }; + } +}); + +tape( 'the method throws an error if provided a generic array-like object having an odd length (clbk)', function test( t ) { + var values; + var i; + + values = [ + [ 1, 2, 3 ], + new Float32Array( [ 1, 2, 3 ] ), + { + 'length': 3, + '0': 1, + '1': 2, + '2': 3 + }, + [ new Complex64( 1.0, 1.0 ), 1.0, 1.0 ] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), RangeError, 'throws an error when provided an array-like object having a length equal to '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return Complex64Array.from( value, clbk ); + }; + } + + function clbk() { + return [ 1.0, 1.0 ]; + } +}); + +tape( 'the method throws an error if provided a non-iterable object (non-ES2015+)', function test( t ) { + var Complex64Array; + var values; + var i; + + Complex64Array = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport + }); + + values = [ + {}, + { + '0': 1, + '1': 2, + '2': 3 + } + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return Complex64Array.from( value ); + }; + } + + function hasSupport() { + return false; + } +}); + +tape( 'the method throws an error if provided a non-iterable object (ES2015+)', function test( t ) { + var Complex64Array; + var values; + var i; + + Complex64Array = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport, + '@stdlib/symbol/iterator': '__SYMBOL_ITERATOR__' + }); + + values = [ + {}, + { + '0': 1, + '1': 2, + '2': 3 + }, + { + '__SYMBOL_ITERATOR__': null + }, + { + '__SYMBOL_ITERATOR__': 'beep' + }, + { + '__SYMBOL_ITERATOR__': nonIterable1 + }, + { + '__SYMBOL_ITERATOR__': nonIterable2 + } + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return Complex64Array.from( value ); + }; + } + + function hasSupport() { + return true; + } + + function nonIterable1() { + return null; + } + + function nonIterable2() { + return {}; + } +}); + +tape( 'the method throws an error if provided an iterable object which does not return complex numbers or arrays of real and imaginary components', function test( t ) { + var Complex64Array; + var values; + var i; + + Complex64Array = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport, + '@stdlib/symbol/iterator': '__SYMBOL_ITERATOR__' + }); + + values = [ + { + '__SYMBOL_ITERATOR__': createIterable( next1 ) + }, + { + '__SYMBOL_ITERATOR__': createIterable( next2 ) + } + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return Complex64Array.from( value ); + }; + } + + function hasSupport() { + return true; + } + + function createIterable( next ) { + return iterable; + + function iterable() { + return { + 'next': next + }; + } + } + + function next1() { + return { + 'value': 1.0 + }; + } + + function next2() { + return { + 'value': '1.0 + 1.0i' + }; + } +}); + +tape( 'the method throws an error if provided an iterable object which does not return an array-like object containing at least two elements', function test( t ) { + var Complex64Array; + var values; + var i; + + Complex64Array = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport, + '@stdlib/symbol/iterator': '__SYMBOL_ITERATOR__' + }); + + values = [ + { + '__SYMBOL_ITERATOR__': createIterable( next1 ) + }, + { + '__SYMBOL_ITERATOR__': createIterable( next2 ) + } + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return Complex64Array.from( value ); + }; + } + + function hasSupport() { + return true; + } + + function createIterable( next ) { + return iterable; + + function iterable() { + return { + 'next': next + }; + } + } + + function next1() { + return { + 'value': [] + }; + } + + function next2() { + return { + 'value': [ 1.0 ] + }; + } +}); + +tape( 'the method throws an error if provided a complex number source array and a "map" function which does not return complex numbers or arrays of real and imaginary components', function test( t ) { + var values; + var clbks; + var i; + + values = [ + [ new Complex64( 1.0, 1.0 ) ], + [ new Complex64( 1.0, 1.0 ), new Complex64( -1.0, -1.0 ) ] + ]; + clbks = [ + clbk1, + clbk2 + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i], clbks[i] ), TypeError, 'throws an error when provided callback '+i ); + } + t.end(); + + function badValue( value, clbk ) { + return function badValue() { + return Complex64Array.from( value, clbk ); + }; + } + + function clbk1() { + return 1.0; + } + + function clbk2() { + return {}; + } +}); + +tape( 'the method throws an error if provided a complex number source array and a "map" function which does not return an array containing at least two elements', function test( t ) { + var values; + var clbks; + var i; + + values = [ + [ new Complex64( 1.0, 1.0 ) ], + [ new Complex64( 1.0, 1.0 ), new Complex64( -1.0, -1.0 ) ] + ]; + clbks = [ + clbk1, + clbk2 + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i], clbks[i] ), TypeError, 'throws an error when provided callback '+i ); + } + t.end(); + + function badValue( value, clbk ) { + return function badValue() { + return Complex64Array.from( value, clbk ); + }; + } + + function clbk1() { + return []; + } + + function clbk2() { + return [ 1.0 ]; + } +}); + +tape( 'the method throws an error if provided a "map" function which does not return complex numbers or arrays of real and imaginary components (iterable)', function test( t ) { + var Complex64Array; + var values; + var clbks; + var i; + + Complex64Array = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport, + '@stdlib/symbol/iterator': '__SYMBOL_ITERATOR__' + }); + + values = [ + { + '__SYMBOL_ITERATOR__': createIterable( next1 ) + }, + { + '__SYMBOL_ITERATOR__': createIterable( next2 ) + } + ]; + clbks = [ + clbk1, + clbk2 + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i], clbks[i] ), TypeError, 'throws an error when provided callback '+i ); + } + t.end(); + + function badValue( value, clbk ) { + return function badValue() { + return Complex64Array.from( value, clbk ); + }; + } + + function hasSupport() { + return true; + } + + function createIterable( next ) { + return iterable; + + function iterable() { + return { + 'next': next + }; + } + } + + function next1() { + return { + 'value': [ 1.0, 1.0 ] + }; + } + + function clbk1() { + return 1.0; + } + + function next2() { + return { + 'value': new Complex64( 1.0, 1.0 ) + }; + } + + function clbk2() { + return '1.0 - 1.0j'; + } +}); + +tape( 'the method throws an error if provided a "map" function which does not return an array containing at least two elements (iterable)', function test( t ) { + var Complex64Array; + var values; + var clbks; + var i; + + Complex64Array = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport, + '@stdlib/symbol/iterator': '__SYMBOL_ITERATOR__' + }); + + values = [ + { + '__SYMBOL_ITERATOR__': createIterable( next1 ) + }, + { + '__SYMBOL_ITERATOR__': createIterable( next2 ) + } + ]; + clbks = [ + clbk1, + clbk2 + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i], clbks[i] ), TypeError, 'throws an error when provided callback '+i ); + } + t.end(); + + function badValue( value, clbk ) { + return function badValue() { + return Complex64Array.from( value, clbk ); + }; + } + + function hasSupport() { + return true; + } + + function createIterable( next ) { + return iterable; + + function iterable() { + return { + 'next': next + }; + } + } + + function next1() { + return { + 'value': [ 1.0, 1.0 ] + }; + } + + function clbk1() { + return []; + } + + function next2() { + return { + 'value': new Complex64( 1.0, 1.0 ) + }; + } + + function clbk2() { + return [ 1.0 ]; + } +}); diff --git a/complex64/test/test.get.js b/complex64/test/test.get.js new file mode 100644 index 00000000..1043eaef --- /dev/null +++ b/complex64/test/test.get.js @@ -0,0 +1,258 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var hasOwnProp = require( '@stdlib/assert/has-own-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var Complex64 = require( '@stdlib/complex/float32' ); +var real = require( '@stdlib/complex/real' ); +var imag = require( '@stdlib/complex/imag' ); +var Complex64Array = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof Complex64Array, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'attached to the prototype of the main export is a `get` method for returning an array element', function test( t ) { + t.strictEqual( hasOwnProp( Complex64Array.prototype, 'get' ), true, 'has property' ); + t.strictEqual( isFunction( Complex64Array.prototype.get ), true, 'has method' ); + t.end(); +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a complex number array instance', function test( t ) { + var values; + var arr; + var i; + + arr = new Complex64Array( 5 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.get.call( value, 0 ); + }; + } +}); + +tape( 'the method throws an error if provided an index argument which is not a nonnegative integer', function test( t ) { + var values; + var arr; + var i; + + arr = new Complex64Array( 10 ); + + values = [ + '5', + -5, + 3.14, + NaN, + true, + false, + null, + void 0, + {}, + [], + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.get( value ); + }; + } +}); + +tape( 'the method throws an error if provided an index argument which is not a nonnegative integer (output argument)', function test( t ) { + var values; + var arr; + var i; + + arr = new Complex64Array( 10 ); + + values = [ + '5', + -5, + 3.14, + NaN, + true, + false, + null, + void 0, + {}, + [], + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.get( [ 0.0, 0.0 ], value ); + }; + } +}); + +tape( 'the method throws an error if provided an output argument which is not an array-like object', function test( t ) { + var values; + var arr; + var i; + + arr = new Complex64Array( 10 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.get( value, 0 ); + }; + } +}); + +tape( 'the method throws an error if provided an output argument which does not contain at least two elements', function test( t ) { + var values; + var arr; + var i; + + arr = new Complex64Array( 10 ); + + values = [ + [], + [ 1.0 ] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.get( value, 0 ); + }; + } +}); + +tape( 'the method returns `undefined` if provided an index which exceeds array dimensions', function test( t ) { + var arr; + var v; + var i; + + arr = new Complex64Array( 10 ); + for ( i = 0; i < arr.length; i++ ) { + v = arr.get( arr.length+i ); + t.strictEqual( v, void 0, 'returns expected value for index '+(arr.length+i) ); + } + t.end(); +}); + +tape( 'the method returns `undefined` if provided an index which exceeds array dimensions (output argument)', function test( t ) { + var arr; + var v; + var i; + + arr = new Complex64Array( 10 ); + for ( i = 0; i < arr.length; i++ ) { + v = arr.get( [ 0.0, 0.0 ], arr.length+i ); + t.strictEqual( v, void 0, 'returns expected value for index '+(arr.length+i) ); + } + t.end(); +}); + +tape( 'the method returns an array element', function test( t ) { + var arr; + var v; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( new Complex64( i, -i ) ); + } + arr = new Complex64Array( arr ); + + for ( i = 0; i < arr.length; i++ ) { + v = arr.get( i ); + t.strictEqual( real( v ), i, 'returns expected real component for index '+i ); + t.strictEqual( imag( v ), -i, 'returns expected imaginary component for index '+i ); + } + t.end(); +}); + +tape( 'the method returns an array element (output argument)', function test( t ) { + var arr; + var out; + var v; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( new Complex64( i, -i ) ); + } + arr = new Complex64Array( arr ); + + out = [ 0.0, 0.0 ]; + for ( i = 0; i < arr.length; i++ ) { + v = arr.get( out, i ); + t.strictEqual( v, out, 'returns expected value for index '+i ); + t.strictEqual( v[ 0 ], i, 'returns expected real component for index '+i ); + t.strictEqual( v[ 1 ], -i, 'returns expected imaginary component for index '+i ); + } + t.end(); +}); diff --git a/complex64/test/test.js b/complex64/test/test.js new file mode 100644 index 00000000..371245e7 --- /dev/null +++ b/complex64/test/test.js @@ -0,0 +1,923 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var ArrayBuffer = require( '@stdlib/array/buffer' ); +var Float32Array = require( '@stdlib/array/float32' ); +var hasOwnProp = require( '@stdlib/assert/has-own-property' ); +var isArrayBuffer = require( '@stdlib/assert/is-arraybuffer' ); +var Complex64 = require( '@stdlib/complex/float32' ); +var real = require( '@stdlib/complex/real' ); +var Complex64Array = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof Complex64Array, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function is a constructor', function test( t ) { + var arr = new Complex64Array( 0 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns an instance' ); + t.end(); +}); + +tape( 'the constructor does not require the `new` keyword', function test( t ) { + var ctor; + var arr; + + ctor = Complex64Array; + + arr = ctor( 0 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns an instance' ); + + t.end(); +}); + +tape( 'the constructor returns a 64-bit complex number array (no argument)', function test( t ) { + var arr = new Complex64Array(); + t.strictEqual( arr instanceof Complex64Array, true, 'returns an instance' ); + t.end(); +}); + +tape( 'the constructor returns a 64-bit complex number array (no argument, no new)', function test( t ) { + var ctor; + var arr; + + ctor = Complex64Array; + + arr = ctor(); + t.strictEqual( arr instanceof Complex64Array, true, 'returns an instance' ); + + t.end(); +}); + +tape( 'the constructor returns a 64-bit complex number array (length)', function test( t ) { + var arr = new Complex64Array( 10 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns an instance' ); + t.end(); +}); + +tape( 'the constructor returns a 64-bit complex number array (length, no new)', function test( t ) { + var ctor; + var arr; + + ctor = Complex64Array; + + arr = ctor( 10 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns an instance' ); + + t.end(); +}); + +tape( 'the constructor returns a 64-bit complex number array (array)', function test( t ) { + var arr = new Complex64Array( [] ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns an instance' ); + t.end(); +}); + +tape( 'the constructor returns a 64-bit complex number array (array, no new)', function test( t ) { + var ctor; + var arr; + + ctor = Complex64Array; + + arr = ctor( [] ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns an instance' ); + + t.end(); +}); + +tape( 'the constructor returns a 64-bit complex number array (typed array)', function test( t ) { + var arr = new Complex64Array( new Float32Array( 0 ) ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns an instance' ); + t.end(); +}); + +tape( 'the constructor returns a 64-bit complex number array (typed array, no new)', function test( t ) { + var ctor; + var arr; + + ctor = Complex64Array; + + arr = ctor( new Float32Array( 0 ) ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns an instance' ); + + t.end(); +}); + +tape( 'the constructor returns a 64-bit complex number array (iterable)', function test( t ) { + var Complex64Array; + var arr; + + Complex64Array = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport, + '@stdlib/symbol/iterator': '__SYMBOL_ITERATOR__' + }); + + arr = new Complex64Array( createIterable() ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns an instance' ); + + t.end(); + + function hasSupport() { + return true; + } + + function createIterable() { + var it = {}; + it[ '__SYMBOL_ITERATOR__' ] = iterable; + return it; + + function iterable() { + return { + 'next': next + }; + } + + function next() { + return { + 'done': true + }; + } + } +}); + +tape( 'the constructor returns a 64-bit complex number array (iterable, no new)', function test( t ) { + var ctor; + var arr; + + ctor = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport, + '@stdlib/symbol/iterator': '__SYMBOL_ITERATOR__' + }); + + arr = ctor( createIterable() ); + t.strictEqual( arr instanceof ctor, true, 'returns an instance' ); + + t.end(); + + function hasSupport() { + return true; + } + + function createIterable() { + var it = {}; + it[ '__SYMBOL_ITERATOR__' ] = iterable; + return it; + + function iterable() { + return { + 'next': next + }; + } + + function next() { + return { + 'done': true + }; + } + } +}); + +tape( 'the constructor returns a 64-bit complex number array (ArrayBuffer)', function test( t ) { + var arr = new Complex64Array( new ArrayBuffer( 0 ) ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns an instance' ); + t.end(); +}); + +tape( 'the constructor returns a 64-bit complex number array (ArrayBuffer, no new)', function test( t ) { + var ctor; + var arr; + + ctor = Complex64Array; + + arr = ctor( new ArrayBuffer( 0 ) ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns an instance' ); + + t.end(); +}); + +tape( 'the constructor returns a 64-bit complex number array (ArrayBuffer, byte offset)', function test( t ) { + var arr = new Complex64Array( new ArrayBuffer( 8 ), 8 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns an instance' ); + t.end(); +}); + +tape( 'the constructor returns a 64-bit complex number array (ArrayBuffer, byte offset, no new)', function test( t ) { + var ctor; + var arr; + + ctor = Complex64Array; + + arr = ctor( new ArrayBuffer( 8 ), 8 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns an instance' ); + + t.end(); +}); + +tape( 'the constructor returns a 64-bit complex number array (ArrayBuffer, byte offset, length)', function test( t ) { + var arr = new Complex64Array( new ArrayBuffer( 8 ), 8, 0 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns an instance' ); + t.end(); +}); + +tape( 'the constructor returns a 64-bit complex number array (ArrayBuffer, byte offset, length, no new)', function test( t ) { + var ctor; + var arr; + + ctor = Complex64Array; + + arr = ctor( new ArrayBuffer( 8 ), 8, 0 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns an instance' ); + + t.end(); +}); + +tape( 'attached to the constructor is a property returning the number of bytes per array element', function test( t ) { + t.strictEqual( hasOwnProp( Complex64Array, 'BYTES_PER_ELEMENT' ), true, 'has property' ); + t.strictEqual( Complex64Array.BYTES_PER_ELEMENT, 8, 'returns expected value' ); + t.end(); +}); + +tape( 'attached to the constructor is a property returning the constructor name', function test( t ) { + t.strictEqual( hasOwnProp( Complex64Array, 'name' ), true, 'has property' ); + t.strictEqual( Complex64Array.name, 'Complex64Array', 'returns expected value' ); + t.end(); +}); + +tape( 'the constructor returns an instance having a `BYTES_PER_ELEMENT` property returning the number of bytes per array element', function test( t ) { + var arr; + + t.strictEqual( hasOwnProp( Complex64Array.prototype, 'BYTES_PER_ELEMENT' ), true, 'has property' ); + t.strictEqual( Complex64Array.prototype.BYTES_PER_ELEMENT, 8, 'returns expected value' ); + + arr = new Complex64Array( 0 ); + t.strictEqual( arr.BYTES_PER_ELEMENT, 8, 'returns expected value' ); + + t.end(); +}); + +tape( 'the constructor returns an instance having a `buffer` property for returning the underlying memory (i.e., ArrayBuffer)', function test( t ) { + var arr; + var buf; + + arr = new Complex64Array( 0 ); + buf = arr.buffer; + t.strictEqual( isArrayBuffer( buf ), true, 'returns expected value' ); + t.end(); +}); + +tape( 'the constructor returns an instance having a `byteLength` property for returning the number of bytes belonging to the array view', function test( t ) { + var arr; + var v; + + arr = new Complex64Array( 0 ); + v = arr.byteLength; + t.strictEqual( v, 0, 'returns expected value' ); + + arr = new Complex64Array( new ArrayBuffer( 64 ), 8 ); + v = arr.byteLength; + t.strictEqual( v, 56, 'returns expected value' ); + + arr = new Complex64Array( new ArrayBuffer( 64 ), 64 ); + v = arr.byteLength; + t.strictEqual( v, 0, 'returns expected value' ); + + t.end(); +}); + +tape( 'the constructor returns an instance having a `byteOffset` property for returning the byte offset pointing to the first array element in the underlying memory', function test( t ) { + var arr; + var v; + + arr = new Complex64Array( 0 ); + v = arr.byteOffset; + t.strictEqual( v, 0, 'returns expected value' ); + + arr = new Complex64Array( new ArrayBuffer( 64 ), 32 ); + v = arr.byteOffset; + t.strictEqual( v, 32, 'returns expected value' ); + + arr = new Complex64Array( new ArrayBuffer( 64 ), 64 ); + v = arr.byteOffset; + t.strictEqual( v, 64, 'returns expected value' ); + + t.end(); +}); + +tape( 'the constructor returns an instance having a `length` property for returning the number of array elements', function test( t ) { + var arr; + var z; + var v; + + // No arguments: + arr = new Complex64Array(); + v = arr.length; + t.strictEqual( v, 0, 'returns expected value' ); + + // Explicit array length: + arr = new Complex64Array( 0 ); + v = arr.length; + t.strictEqual( v, 0, 'returns expected value' ); + + arr = new Complex64Array( 10 ); + v = arr.length; + t.strictEqual( v, 10, 'returns expected value' ); + + // Generic array: + arr = new Complex64Array( [] ); + v = arr.length; + t.strictEqual( v, 0, 'returns expected value' ); + + arr = new Complex64Array( [ 1.0, 2.0, 3.0, 4.0 ] ); + v = arr.length; + t.strictEqual( v, 2, 'returns expected value' ); + + // Generic array containing complex numbers: + arr = new Complex64Array( [ new Complex64( 1.0, 1.0 ) ] ); + v = arr.length; + t.strictEqual( v, 1, 'returns expected value' ); + + z = new Complex64( 1.0, 0.0 ); + z.valueOf = valueOf( z ); + arr = new Complex64Array( [ z, 1.0 ] ); + v = arr.length; + t.strictEqual( v, 1, 'returns expected value' ); + + z = new Complex64( 1.0, 0.0 ); + z.valueOf = valueOf( z ); + arr = new Complex64Array( [ 1.0, z ] ); + v = arr.length; + t.strictEqual( v, 1, 'returns expected value' ); + + // Typed array: + arr = new Complex64Array( new Float32Array( 0 ) ); + v = arr.length; + t.strictEqual( v, 0, 'returns expected value' ); + + arr = new Complex64Array( new Float32Array( [ 1.0, 1.0 ] ) ); + v = arr.length; + t.strictEqual( v, 1, 'returns expected value' ); + + // ArrayBuffer: + arr = new Complex64Array( new ArrayBuffer( 64 ), 32 ); + v = arr.length; + t.strictEqual( v, 4, 'returns expected value' ); + + arr = new Complex64Array( new ArrayBuffer( 64 ), 64 ); + v = arr.length; + t.strictEqual( v, 0, 'returns expected value' ); + + arr = new Complex64Array( new ArrayBuffer( 64 ), 32, 2 ); + v = arr.length; + t.strictEqual( v, 2, 'returns expected value' ); + + t.end(); + + function valueOf( z ) { + return function valueOf() { + return real( z ); + }; + } +}); + +tape( 'the constructor returns an instance having a `length` property for returning the number of array elements (iterable)', function test( t ) { + var Complex64Array; + var iter1; + var iter2; + var arr; + var v; + + Complex64Array = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport, + '@stdlib/symbol/iterator': '__SYMBOL_ITERATOR__' + }); + + iter1 = { + 'next': next1, + 'i': 0, + 'N': 4 + }; + arr = new Complex64Array( createIterable( iter1 ) ); + v = arr.length; + t.strictEqual( v, iter1.N, 'returns expected value' ); + + iter2 = { + 'next': next2, + 'i': 0, + 'N': 4 + }; + arr = new Complex64Array( createIterable( iter2 ) ); + v = arr.length; + t.strictEqual( v, iter2.N, 'returns expected value' ); + + t.end(); + + function hasSupport() { + return true; + } + + function createIterable( iterator ) { + var it = {}; + it[ '__SYMBOL_ITERATOR__' ] = iterable; + return it; + + function iterable() { + return iterator; + } + } + + function next1() { + iter1.i += 1; + if ( iter1.i <= iter1.N ) { + return { + 'value': [ 1.0, 1.0 ] + }; + } + return { + 'done': true + }; + } + + function next2() { + iter2.i += 1; + if ( iter2.i <= iter2.N ) { + return { + 'value': new Complex64( 1.0, 1.0 ) + }; + } + return { + 'done': true + }; + } +}); + +tape( 'the constructor throws an error if provided an ArrayBuffer which is a multiple of 8', function test( t ) { + var values; + var i; + + values = [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 9, + 74, + 801 + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), RangeError, 'throws an error when provided an ArrayBuffer having a byte length equal to '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return new Complex64Array( new ArrayBuffer( value ) ); + }; + } +}); + +tape( 'the constructor throws an error if provided an array-like object having an odd length', function test( t ) { + var values; + var i; + + values = [ + [ 1, 2, 3 ], + new Float32Array( [ 1, 2, 3 ] ), + { + 'length': 3, + '0': 1, + '1': 2, + '2': 3 + }, + [ new Complex64( 1.0, 1.0 ), 1.0, 1.0 ] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), RangeError, 'throws an error when provided an array-like object having a length equal to '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return new Complex64Array( value ); + }; + } +}); + +tape( 'the constructor throws an error if provided a non-iterable object (non-ES2015+)', function test( t ) { + var Complex64Array; + var values; + var i; + + Complex64Array = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport + }); + + values = [ + {}, + { + '0': 1, + '1': 2, + '2': 3 + } + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return new Complex64Array( value ); + }; + } + + function hasSupport() { + return false; + } +}); + +tape( 'the constructor throws an error if provided a non-iterable object (ES2015+)', function test( t ) { + var Complex64Array; + var values; + var i; + + Complex64Array = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport, + '@stdlib/symbol/iterator': '__SYMBOL_ITERATOR__' + }); + + values = [ + {}, + { + '0': 1, + '1': 2, + '2': 3 + }, + { + '__SYMBOL_ITERATOR__': null + }, + { + '__SYMBOL_ITERATOR__': 'beep' + }, + { + '__SYMBOL_ITERATOR__': nonIterable1 + }, + { + '__SYMBOL_ITERATOR__': nonIterable2 + } + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return new Complex64Array( value ); + }; + } + + function hasSupport() { + return true; + } + + function nonIterable1() { + return null; + } + + function nonIterable2() { + return {}; + } +}); + +tape( 'the constructor throws an error if provided an iterable object which does not return complex numbers or arrays of real and imaginary components', function test( t ) { + var Complex64Array; + var values; + var i; + + Complex64Array = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport, + '@stdlib/symbol/iterator': '__SYMBOL_ITERATOR__' + }); + + values = [ + { + '__SYMBOL_ITERATOR__': createIterable( next1 ) + }, + { + '__SYMBOL_ITERATOR__': createIterable( next2 ) + } + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return new Complex64Array( value ); + }; + } + + function hasSupport() { + return true; + } + + function createIterable( next ) { + return iterable; + + function iterable() { + return { + 'next': next + }; + } + } + + function next1() { + return { + 'value': 1.0 + }; + } + + function next2() { + return { + 'value': '1.0 + 1.0i' + }; + } +}); + +tape( 'the constructor throws an error if provided an iterable object which does not return array containing at least two elements', function test( t ) { + var Complex64Array; + var values; + var i; + + Complex64Array = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport, + '@stdlib/symbol/iterator': '__SYMBOL_ITERATOR__' + }); + + values = [ + { + '__SYMBOL_ITERATOR__': createIterable( next1 ) + }, + { + '__SYMBOL_ITERATOR__': createIterable( next2 ) + } + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return new Complex64Array( value ); + }; + } + + function hasSupport() { + return true; + } + + function createIterable( next ) { + return iterable; + + function iterable() { + return { + 'next': next + }; + } + } + + function next1() { + return { + 'value': [] + }; + } + + function next2() { + return { + 'value': [ 1.0 ] + }; + } +}); + +tape( 'the constructor throws an error if not provided a length, iterable, array-like object, or ArrayBuffer', function test( t ) { + var values; + var i; + + values = [ + '5', + 3.14, + -1, + NaN, + true, + false, + null, + void 0, + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return new Complex64Array( value ); + }; + } +}); + +tape( 'the constructor throws an error if provided more than one argument and the first argument is not an ArrayBuffer', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + [], + {}, + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return new Complex64Array( value, 0 ); + }; + } +}); + +tape( 'the constructor throws an error if provided a byte offset argument which is not a nonnegative integer', function test( t ) { + var values; + var i; + + values = [ + '5', + -1, + 3.14, + NaN, + true, + false, + null, + void 0, + [], + {}, + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return new Complex64Array( new ArrayBuffer( 64 ), value ); + }; + } +}); + +tape( 'the constructor throws an error if provided a byte offset argument which is not a multiple of 8', function test( t ) { + var values; + var i; + + values = [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 9, + 65, + 78, + 801 + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), RangeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return new Complex64Array( new ArrayBuffer( 1e3 ), value ); + }; + } +}); + +tape( 'the constructor throws an error if provided a byte offset argument such that the view byte length is not a multiple of 8', function test( t ) { + var values; + var i; + + values = [ + 8, + 16, + 24, + 32, + 48, + 56, + 64, + 72, + 80, + 88 + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), RangeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return new Complex64Array( new ArrayBuffer( 102 ), value ); + }; + } +}); + +tape( 'the constructor throws an error if provided a length argument which is not a nonnegative integer (ArrayBuffer)', function test( t ) { + var values; + var i; + + values = [ + '5', + -1, + 3.14, + NaN, + true, + false, + null, + void 0, + [], + {}, + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return new Complex64Array( new ArrayBuffer( 64 ), 0, value ); + }; + } +}); + +tape( 'the constructor throws an error if provided insufficient memory to accommodate byte offset and length arguments', function test( t ) { + var values; + var i; + + values = [ + 8, + 16, + 24, + 32 + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), RangeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return new Complex64Array( new ArrayBuffer( 100 ), value, 1e3 ); + }; + } +}); diff --git a/complex64/test/test.of.js b/complex64/test/test.of.js new file mode 100644 index 00000000..df5db8ac --- /dev/null +++ b/complex64/test/test.of.js @@ -0,0 +1,149 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var hasOwnProp = require( '@stdlib/assert/has-own-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var Complex64 = require( '@stdlib/complex/float32' ); +var real = require( '@stdlib/complex/real' ); +var Complex64Array = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof Complex64Array, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'attached to the main export is an `of` method for creating a complex number array from a variable number of arguments', function test( t ) { + var arr; + + t.strictEqual( hasOwnProp( Complex64Array, 'of' ), true, 'has property' ); + t.strictEqual( isFunction( Complex64Array.of ), true, 'has method' ); + + arr = Complex64Array.of(); + t.strictEqual( arr instanceof Complex64Array, true, 'returns an instance' ); + + t.end(); +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a constructor', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return Complex64Array.of.call( value, 1.0, 1.0 ); + }; + } +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a complex array constructor', function test( t ) { + var values; + var i; + + values = [ + Complex64, + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return Complex64Array.of.call( value, 1.0, 1.0 ); + }; + } +}); + +tape( 'the method returns a complex number array', function test( t ) { + var arr; + var z; + var v; + + // No arguments: + arr = Complex64Array.of(); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 0, 'returns expected value' ); + + // Interleaved real and imaginary components: + arr = Complex64Array.of( 1.0, 2.0, 3.0, 4.0 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 2, 'returns expected value' ); + + // Complex numbers: + z = new Complex64( 1.0, 1.0 ); + arr = Complex64Array.of( z, z, z, z, z ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 5, 'returns expected value' ); + + // Mixed arguments: + z = new Complex64( 1.0, 0.0 ); + z.valueOf = valueOf( z ); + arr = Complex64Array.of( z, 1.0 ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 1, 'returns expected value' ); + + z = new Complex64( 1.0, 0.0 ); + z.valueOf = valueOf( z ); + arr = Complex64Array.of( 1.0, z ); + t.strictEqual( arr instanceof Complex64Array, true, 'returns expected value' ); + + v = arr.length; + t.strictEqual( v, 1, 'returns expected value' ); + + t.end(); + + function valueOf( z ) { + return function valueOf() { + return real( z ); + }; + } +}); diff --git a/complex64/test/test.set.js b/complex64/test/test.set.js new file mode 100644 index 00000000..f1c0705d --- /dev/null +++ b/complex64/test/test.set.js @@ -0,0 +1,714 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var hasOwnProp = require( '@stdlib/assert/has-own-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var ArrayBuffer = require( '@stdlib/array/buffer' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Complex64 = require( '@stdlib/complex/float32' ); +var real = require( '@stdlib/complex/real' ); +var imag = require( '@stdlib/complex/imag' ); +var Complex64Array = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof Complex64Array, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'attached to the prototype of the main export is a `set` method for setting one or more array elements', function test( t ) { + t.strictEqual( hasOwnProp( Complex64Array.prototype, 'set' ), true, 'has property' ); + t.strictEqual( isFunction( Complex64Array.prototype.set ), true, 'has method' ); + t.end(); +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a complex number array instance', function test( t ) { + var values; + var arr; + var i; + + arr = new Complex64Array( 5 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.set.call( value, 0 ); + }; + } +}); + +tape( 'the method throws an error if provided a first argument which is not a complex number, a complex number array, or an array-like object', function test( t ) { + var values; + var arr; + var i; + + arr = new Complex64Array( 10 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.set( value ); + }; + } +}); + +tape( 'the method throws an error if provided a first argument which is not a complex number, a complex number array, or an array-like object (index argument)', function test( t ) { + var values; + var arr; + var i; + + arr = new Complex64Array( 10 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.set( value, 0 ); + }; + } +}); + +tape( 'the method throws an error if provided an index argument which is not a nonnegative integer', function test( t ) { + var values; + var arr; + var i; + + arr = new Complex64Array( 10 ); + + values = [ + '5', + -5, + 3.14, + NaN, + true, + false, + null, + void 0, + {}, + [], + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.set( new Complex64( 1.0, -1.0 ), value ); + }; + } +}); + +tape( 'the method throws an error if provided an index argument which is out-of-bounds (complex number)', function test( t ) { + var values; + var arr; + var i; + + arr = new Complex64Array( 10 ); + + values = [ + arr.length, + arr.length + 1, + arr.length + 2, + arr.length + 3 + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), RangeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.set( new Complex64( 1.0, -1.0 ), value ); + }; + } +}); + +tape( 'the method throws an error if provided an index argument which is out-of-bounds (complex typed array)', function test( t ) { + var values; + var arr1; + var arr2; + var i; + + arr1 = new Complex64Array( 10 ); + arr2 = new Complex64Array( 10 ); + + values = [ + 1, + 2, + 3, + 4, + 5 + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), RangeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr1.set( arr2, value ); + }; + } +}); + +tape( 'the method throws an error if provided an index argument which is out-of-bounds (array-like object containing complex numbers)', function test( t ) { + var values; + var arr1; + var arr2; + var i; + + arr1 = new Complex64Array( 10 ); + arr2 = []; + for ( i = 0; i < arr1.length; i++ ) { + arr2.push( new Complex64( i, -i ) ); + } + + values = [ + 1, + 2, + 3, + 4, + 5 + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), RangeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr1.set( arr2, value ); + }; + } +}); + +tape( 'the method throws an error if provided an index argument which is out-of-bounds (array-like object containing interleaved components)', function test( t ) { + var values; + var arr1; + var arr2; + var i; + + arr1 = new Complex64Array( 10 ); + arr2 = []; + for ( i = 0; i < arr1.length; i++ ) { + arr2.push( i ); + arr2.push( -i ); + } + + values = [ + 1, + 2, + 3, + 4, + 5 + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), RangeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr1.set( arr2, value ); + }; + } +}); + +tape( 'the method throws an error if provided an array-like object containing interleaved components which has an odd length', function test( t ) { + var values; + var arr; + var i; + + arr = new Complex64Array( 10 ); + + values = [ + [ 1 ], + [ 1, 2, 3 ], + [ 1, 2, 3, 4, 5 ], + [ 1, 2, 3, 4, 5, 6, 7 ] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), RangeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.set( value ); + }; + } +}); + +tape( 'the method throws an error if provided an array-like object containing interleaved components which has an odd length (index argument)', function test( t ) { + var values; + var arr; + var i; + + arr = new Complex64Array( 10 ); + + values = [ + [ 1 ], + [ 1, 2, 3 ], + [ 1, 2, 3, 4, 5 ], + [ 1, 2, 3, 4, 5, 6, 7 ] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), RangeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.set( value, 0 ); + }; + } +}); + +tape( 'the method sets an array element (complex number)', function test( t ) { + var arr; + var v; + var i; + + arr = new Complex64Array( 10 ); + + v = arr.get( 0 ); + t.strictEqual( real( v ), 0.0, 'returns expected real component for index '+0 ); + t.strictEqual( imag( v ), 0.0, 'returns expected imaginary component for index '+0 ); + + // No index argument: + arr.set( new Complex64( 20.0, -20.0 ) ); + + v = arr.get( 0 ); + t.strictEqual( real( v ), 20.0, 'returns expected real component for index '+0 ); + t.strictEqual( imag( v ), -20.0, 'returns expected imaginary component for index '+0 ); + + arr.set( new Complex64( 0.0, 0.0 ) ); + + // Index argument: + for ( i = 0; i < arr.length; i++ ) { + v = arr.get( i ); + t.strictEqual( real( v ), 0.0, 'returns expected real component for index '+i ); + t.strictEqual( imag( v ), 0.0, 'returns expected imaginary component for index '+i ); + + arr.set( new Complex64( i, -i ), i ); + + v = arr.get( i ); + t.strictEqual( real( v ), i, 'returns expected real component for index '+i ); + t.strictEqual( imag( v ), -i, 'returns expected imaginary component for index '+i ); + } + t.end(); +}); + +tape( 'the method sets an array element (complex typed array)', function test( t ) { + var arr; + var buf; + var v; + var i; + + arr = new Complex64Array( 10 ); + + v = arr.get( 0 ); + t.strictEqual( real( v ), 0.0, 'returns expected real component for index '+0 ); + t.strictEqual( imag( v ), 0.0, 'returns expected imaginary component for index '+0 ); + + // No index argument: + buf = [ 20.0, -20.0 ]; + arr.set( new Complex64Array( buf ) ); + + v = arr.get( 0 ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+0 ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+0 ); + + buf = [ 0.0, 0.0 ]; + arr.set( new Complex64Array( buf ) ); + + // Index argument: + for ( i = 0; i < arr.length; i++ ) { + v = arr.get( i ); + t.strictEqual( real( v ), 0.0, 'returns expected real component for index '+i ); + t.strictEqual( imag( v ), 0.0, 'returns expected imaginary component for index '+i ); + + buf = [ i, -i ]; + arr.set( new Complex64Array( buf ), i ); + + v = arr.get( i ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+i ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+i ); + } + + // Multiple values, no index argument: + buf = [ 20.0, -20.0, -40.0, 40.0 ]; + arr.set( new Complex64Array( buf ) ); + + v = arr.get( 0 ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+0 ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+0 ); + + v = arr.get( 1 ); + t.strictEqual( real( v ), buf[ 2 ], 'returns expected real component for index '+1 ); + t.strictEqual( imag( v ), buf[ 3 ], 'returns expected imaginary component for index '+1 ); + + // Multiple values, index argument: + buf = [ -100.0, -200.0, -300.0, -400.0 ]; + arr.set( new Complex64Array( buf ), 2 ); + + v = arr.get( 2 ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+2 ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+2 ); + + v = arr.get( 3 ); + t.strictEqual( real( v ), buf[ 2 ], 'returns expected real component for index '+3 ); + t.strictEqual( imag( v ), buf[ 3 ], 'returns expected imaginary component for index '+3 ); + + t.end(); +}); + +tape( 'the method sets an array element (array-like object containing complex numbers)', function test( t ) { + var arr; + var buf; + var v; + var i; + + arr = new Complex64Array( 10 ); + + v = arr.get( 0 ); + t.strictEqual( real( v ), 0.0, 'returns expected real component for index '+0 ); + t.strictEqual( imag( v ), 0.0, 'returns expected imaginary component for index '+0 ); + + // No index argument: + buf = [ 20.0, -20.0 ]; + arr.set( [ new Complex64( buf[0], buf[1] ) ] ); + + v = arr.get( 0 ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+0 ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+0 ); + + buf = [ 0.0, 0.0 ]; + arr.set( [ new Complex64( buf[0], buf[1] ) ] ); + + // Index argument: + for ( i = 0; i < arr.length; i++ ) { + v = arr.get( i ); + t.strictEqual( real( v ), 0.0, 'returns expected real component for index '+i ); + t.strictEqual( imag( v ), 0.0, 'returns expected imaginary component for index '+i ); + + buf = [ i, -i ]; + arr.set( [ new Complex64( buf[ 0 ], buf[ 1 ] ) ], i ); + + v = arr.get( i ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+i ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+i ); + } + + // Multiple values, no index argument: + buf = [ 20.0, -20.0, -40.0, 40.0 ]; + arr.set( [ new Complex64( buf[0], buf[1] ), new Complex64( buf[2], buf[3] ) ] ); // eslint-disable-line max-len + + v = arr.get( 0 ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+0 ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+0 ); + + v = arr.get( 1 ); + t.strictEqual( real( v ), buf[ 2 ], 'returns expected real component for index '+1 ); + t.strictEqual( imag( v ), buf[ 3 ], 'returns expected imaginary component for index '+1 ); + + // Multiple values, index argument: + buf = [ -100.0, -200.0, -300.0, -400.0 ]; + arr.set( [ new Complex64( buf[0], buf[1] ), new Complex64( buf[2], buf[3] ) ], 2 ); // eslint-disable-line max-len + + v = arr.get( 2 ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+2 ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+2 ); + + v = arr.get( 3 ); + t.strictEqual( real( v ), buf[ 2 ], 'returns expected real component for index '+3 ); + t.strictEqual( imag( v ), buf[ 3 ], 'returns expected imaginary component for index '+3 ); + + t.end(); +}); + +tape( 'the method sets an array element (array-like object containing interleaved components)', function test( t ) { + var arr; + var buf; + var v; + var i; + + arr = new Complex64Array( 10 ); + + v = arr.get( 0 ); + t.strictEqual( real( v ), 0.0, 'returns expected real component for index '+0 ); + t.strictEqual( imag( v ), 0.0, 'returns expected imaginary component for index '+0 ); + + // No index argument: + buf = [ 20.0, -20.0 ]; + arr.set( buf ); + + v = arr.get( 0 ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+0 ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+0 ); + + buf = [ 0.0, 0.0 ]; + arr.set( buf ); + + // Index argument: + for ( i = 0; i < arr.length; i++ ) { + v = arr.get( i ); + t.strictEqual( real( v ), 0.0, 'returns expected real component for index '+i ); + t.strictEqual( imag( v ), 0.0, 'returns expected imaginary component for index '+i ); + + buf = [ i, -i ]; + arr.set( buf, i ); + + v = arr.get( i ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+i ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+i ); + } + + // Multiple values, no index argument: + buf = [ 20.0, -20.0, -40.0, 40.0 ]; + arr.set( buf ); + + v = arr.get( 0 ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+0 ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+0 ); + + v = arr.get( 1 ); + t.strictEqual( real( v ), buf[ 2 ], 'returns expected real component for index '+1 ); + t.strictEqual( imag( v ), buf[ 3 ], 'returns expected imaginary component for index '+1 ); + + // Multiple values, index argument: + buf = [ -100.0, -200.0, -300.0, -400.0 ]; + arr.set( buf, 2 ); + + v = arr.get( 2 ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+2 ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+2 ); + + v = arr.get( 3 ); + t.strictEqual( real( v ), buf[ 2 ], 'returns expected real component for index '+3 ); + t.strictEqual( imag( v ), buf[ 3 ], 'returns expected imaginary component for index '+3 ); + + t.end(); +}); + +tape( 'the method sets an array element (complex typed array; shared buffer)', function test( t ) { + var byteOffset; + var arr; + var src; + var buf; + var ab; + var v; + + byteOffset = 112; + + ab = new ArrayBuffer( 240 ); + arr = new Complex64Array( ab, byteOffset, 10 ); + + // Overlapping (requires copy), multiple values, no index argument: + buf = [ 20.0, -20.0, -40.0, 40.0 ]; + src = new Complex64Array( ab, byteOffset-(1*arr.BYTES_PER_ELEMENT), 2 ); + src.set( buf ); + arr.set( src ); + + v = arr.get( 0 ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+0 ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+0 ); + + v = arr.get( 1 ); + t.strictEqual( real( v ), buf[ 2 ], 'returns expected real component for index '+1 ); + t.strictEqual( imag( v ), buf[ 3 ], 'returns expected imaginary component for index '+1 ); + + // Overlapping (requires copy), multiple values, index argument: + buf = [ -100.0, -200.0, -300.0, -400.0 ]; + src = new Complex64Array( ab, byteOffset+(1*arr.BYTES_PER_ELEMENT), 2 ); + src.set( buf ); + arr.set( src, 2 ); + + v = arr.get( 2 ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+2 ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+2 ); + + v = arr.get( 3 ); + t.strictEqual( real( v ), buf[ 2 ], 'returns expected real component for index '+3 ); + t.strictEqual( imag( v ), buf[ 3 ], 'returns expected imaginary component for index '+3 ); + + // Overlapping (no copy), multiple values, no index argument: + buf = [ 25.0, -25.0, -45.0, 45.0 ]; + src = new Complex64Array( ab, byteOffset+(1*arr.BYTES_PER_ELEMENT), 2 ); + src.set( buf ); + arr.set( src ); + + v = arr.get( 0 ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+0 ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+0 ); + + v = arr.get( 1 ); + t.strictEqual( real( v ), buf[ 2 ], 'returns expected real component for index '+1 ); + t.strictEqual( imag( v ), buf[ 3 ], 'returns expected imaginary component for index '+1 ); + + // Overlapping (no copy), multiple values, index argument: + buf = [ -105.0, -205.0, -305.0, -405.0 ]; + src = new Complex64Array( ab, byteOffset+(3*arr.BYTES_PER_ELEMENT), 2 ); + src.set( buf ); + arr.set( src, 2 ); + + v = arr.get( 2 ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+2 ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+2 ); + + v = arr.get( 3 ); + t.strictEqual( real( v ), buf[ 2 ], 'returns expected real component for index '+3 ); + t.strictEqual( imag( v ), buf[ 3 ], 'returns expected imaginary component for index '+3 ); + + t.end(); +}); + +tape( 'the method sets an array element (typed array; shared buffer)', function test( t ) { + var byteOffset; + var arr; + var src; + var buf; + var ab; + var v; + var i; + + byteOffset = 112; + + ab = new ArrayBuffer( 240 ); + arr = new Complex64Array( ab, byteOffset, 10 ); + + // Overlapping (requires copy), multiple values, no index argument: + buf = [ 20.0, -20.0, -40.0, 40.0 ]; + src = new Float32Array( ab, byteOffset-(1*arr.BYTES_PER_ELEMENT), 4 ); + for ( i = 0; i < buf.length; i++ ) { + src[ i ] = buf[ i ]; + } + arr.set( src ); + + v = arr.get( 0 ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+0 ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+0 ); + + v = arr.get( 1 ); + t.strictEqual( real( v ), buf[ 2 ], 'returns expected real component for index '+1 ); + t.strictEqual( imag( v ), buf[ 3 ], 'returns expected imaginary component for index '+1 ); + + // Overlapping (requires copy), multiple values, index argument: + buf = [ -100.0, -200.0, -300.0, -400.0 ]; + src = new Float32Array( ab, byteOffset+(1*arr.BYTES_PER_ELEMENT), 4 ); + for ( i = 0; i < buf.length; i++ ) { + src[ i ] = buf[ i ]; + } + arr.set( src, 2 ); + + v = arr.get( 2 ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+2 ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+2 ); + + v = arr.get( 3 ); + t.strictEqual( real( v ), buf[ 2 ], 'returns expected real component for index '+3 ); + t.strictEqual( imag( v ), buf[ 3 ], 'returns expected imaginary component for index '+3 ); + + // Overlapping (no copy), multiple values, no index argument: + buf = [ 25.0, -25.0, -45.0, 45.0 ]; + src = new Float32Array( ab, byteOffset+(1*arr.BYTES_PER_ELEMENT), 4 ); + for ( i = 0; i < buf.length; i++ ) { + src[ i ] = buf[ i ]; + } + arr.set( src ); + + v = arr.get( 0 ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+0 ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+0 ); + + v = arr.get( 1 ); + t.strictEqual( real( v ), buf[ 2 ], 'returns expected real component for index '+1 ); + t.strictEqual( imag( v ), buf[ 3 ], 'returns expected imaginary component for index '+1 ); + + // Overlapping (no copy), multiple values, index argument: + buf = [ -105.0, -205.0, -305.0, -405.0 ]; + src = new Float32Array( ab, byteOffset+(3*arr.BYTES_PER_ELEMENT), 4 ); + for ( i = 0; i < buf.length; i++ ) { + src[ i ] = buf[ i ]; + } + arr.set( src, 2 ); + + v = arr.get( 2 ); + t.strictEqual( real( v ), buf[ 0 ], 'returns expected real component for index '+2 ); + t.strictEqual( imag( v ), buf[ 1 ], 'returns expected imaginary component for index '+2 ); + + v = arr.get( 3 ); + t.strictEqual( real( v ), buf[ 2 ], 'returns expected real component for index '+3 ); + t.strictEqual( imag( v ), buf[ 3 ], 'returns expected imaginary component for index '+3 ); + + t.end(); +}); diff --git a/convert-same/README.md b/convert-same/README.md new file mode 100644 index 00000000..02d0a95c --- /dev/null +++ b/convert-same/README.md @@ -0,0 +1,139 @@ + + +# Convert + +> Convert an array to the same data type as a second input array. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var convertArraySame = require( '@stdlib/array/convert-same' ); +``` + +#### convertArraySame( x, y ) + +Converts an `array` to the same data type as a second input `array`. + +```javascript +var Float32Array = require( '@stdlib/array/float32' ); + +var y = new Float32Array( 0 ); + +var x = [ 1.0, 2.0, 3.0 ]; +var out = convertArraySame( x, y ); +// returns [ 1.0, 2.0, 3.0 ] +``` + +The function supports input arrays having the following data types: + +- `float32`: single-precision floating-point numbers. +- `float64`: double-precision floating-point numbers. +- `generic`: values of any type. +- `int16`: signed 16-bit integers. +- `int32`: signed 32-bit integers. +- `int8`: signed 8-bit integers. +- `uint16`: unsigned 16-bit integers. +- `uint32`: unsigned 32-bit integers. +- `uint8`: unsigned 8-bit integers. +- `uint8c`: unsigned clamped 8-bit integers. + +
+ + + + + +
+ +
+ + + + + +
+ +## Examples + + + + + +```javascript +var dtypes = require( '@stdlib/array/dtypes' ); +var ctors = require( '@stdlib/array/ctors' ); +var randu = require( '@stdlib/random/base/randu' ); +var floor = require( '@stdlib/math/base/special/floor' ); +var convertArraySame = require( '@stdlib/array/convert-same' ); + +// Create a generic array: +var x = []; +var i; +for ( i = 0; i < 5; i++ ) { + x.push( floor( randu()*1.0e25 ) - 5.0e24 ); +} + +// Get a list of array data types: +var DTYPES = dtypes(); + +// Convert the generic array to each array data type: +var ctor; +var out; +var y; +for ( i = 0; i < DTYPES.length; i++ ) { + ctor = ctors( DTYPES[ i ] ); + y = new ctor( 0 ); + out = convertArraySame( x, y ); + console.log( out ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/convert-same/benchmark/benchmark.js b/convert-same/benchmark/benchmark.js new file mode 100644 index 00000000..8a988c8a --- /dev/null +++ b/convert-same/benchmark/benchmark.js @@ -0,0 +1,315 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isCollection = require( '@stdlib/assert/is-collection' ); +var Float64Array = require( '@stdlib/array/float64' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Int8Array = require( '@stdlib/array/int8' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); +var pkg = require( './../package.json' ).name; +var convertArraySame = require( './../lib' ); + + +// MAIN // + +bench( pkg+':dtype=generic', function benchmark( b ) { + var arr; + var out; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArraySame( arr, arr ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=float64', function benchmark( b ) { + var arr; + var out; + var v; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + v = new Float64Array( 0 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArraySame( arr, v ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=float32', function benchmark( b ) { + var arr; + var out; + var v; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + v = new Float32Array( 0 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArraySame( arr, v ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=int32', function benchmark( b ) { + var arr; + var out; + var v; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + v = new Int32Array( 0 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArraySame( arr, v ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=int16', function benchmark( b ) { + var arr; + var out; + var v; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + v = new Int16Array( 0 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArraySame( arr, v ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=int8', function benchmark( b ) { + var arr; + var out; + var v; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + v = new Int8Array( 0 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArraySame( arr, v ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint32', function benchmark( b ) { + var arr; + var out; + var v; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + v = new Uint32Array( 0 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArraySame( arr, v ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint16', function benchmark( b ) { + var arr; + var out; + var v; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + v = new Uint16Array( 0 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArraySame( arr, v ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint8', function benchmark( b ) { + var arr; + var out; + var v; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + v = new Uint8Array( 0 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArraySame( arr, v ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint8c', function benchmark( b ) { + var arr; + var out; + var v; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + v = new Uint8ClampedArray( 0 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArraySame( arr, v ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/convert-same/benchmark/benchmark.length.js b/convert-same/benchmark/benchmark.length.js new file mode 100644 index 00000000..d29f4c34 --- /dev/null +++ b/convert-same/benchmark/benchmark.length.js @@ -0,0 +1,138 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isCollection = require( '@stdlib/assert/is-collection' ); +var Float64Array = require( '@stdlib/array/float64' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Int8Array = require( '@stdlib/array/int8' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); +var pkg = require( './../package.json' ).name; +var convertArraySame = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @param {(Array|TypedArray)} v - value having desired data type +* @returns {Function} benchmark function +*/ +function createBenchmark( len, v ) { + var arr; + var i; + + arr = []; + for ( i = 0; i < len; i++ ) { + arr[ i ] = i; + } + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = convertArraySame( arr, v ); + if ( out.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + + f = createBenchmark( len, [] ); + bench( pkg+':len='+len+',dtype=generic', f ); + + f = createBenchmark( len, new Float64Array( 0 ) ); + bench( pkg+':len='+len+',dtype=float64', f ); + + f = createBenchmark( len, new Float32Array( 0 ) ); + bench( pkg+':len='+len+',dtype=float32', f ); + + f = createBenchmark( len, new Int32Array( 0 ) ); + bench( pkg+':len='+len+',dtype=int32', f ); + + f = createBenchmark( len, new Int16Array( 0 ) ); + bench( pkg+':len='+len+',dtype=int16', f ); + + f = createBenchmark( len, new Int8Array( 0 ) ); + bench( pkg+':len='+len+',dtype=int8', f ); + + f = createBenchmark( len, new Uint32Array( 0 ) ); + bench( pkg+':len='+len+',dtype=uint32', f ); + + f = createBenchmark( len, new Uint16Array( 0 ) ); + bench( pkg+':len='+len+',dtype=uint16', f ); + + f = createBenchmark( len, new Uint8Array( 0 ) ); + bench( pkg+':len='+len+',dtype=uint8', f ); + + f = createBenchmark( len, new Uint8ClampedArray( 0 ) ); + bench( pkg+':len='+len+',dtype=uint8c', f ); + } +} + +main(); diff --git a/convert-same/benchmark/julia/REQUIRE b/convert-same/benchmark/julia/REQUIRE new file mode 100644 index 00000000..98645e19 --- /dev/null +++ b/convert-same/benchmark/julia/REQUIRE @@ -0,0 +1,2 @@ +julia 1.5 +BenchmarkTools 0.5.0 diff --git a/convert-same/benchmark/julia/benchmark.jl b/convert-same/benchmark/julia/benchmark.jl new file mode 100644 index 00000000..b317a19b --- /dev/null +++ b/convert-same/benchmark/julia/benchmark.jl @@ -0,0 +1,193 @@ +#!/usr/bin/env julia +# +# @license Apache-2.0 +# +# Copyright (c) 2018 The Stdlib Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import BenchmarkTools +using Printf + +# Benchmark variables: +repeats = 3; +samples = 1e3; +count = 0; + +""" + print_version() + +Prints the TAP version. + +# Examples + +``` julia +julia> print_version() +``` +""" +function print_version() + @printf( "TAP version 13\n" ); +end + +""" + print_summary( total, passing ) + +Print the benchmark summary. + +# Arguments + +* `total`: total number of tests +* `passing`: number of passing tests + +# Examples + +``` julia +julia> print_summary( 3, 3 ) +``` +""" +function print_summary( total, passing ) + @printf( "#\n" ); + @printf( "1..%d\n", total ); # TAP plan + @printf( "# total %d\n", total ); + @printf( "# pass %d\n", passing ); + @printf( "#\n" ); + @printf( "# ok\n" ); +end + +""" + print_results( iterations, elapsed ) + +Print benchmark results. + +# Arguments + +* `iterations`: number of iterations +* `elapsed`: elapsed time (in seconds) + +# Examples + +``` julia +julia> print_results( 1000000, 0.131009101868 ) +``` +""" +function print_results( iterations, elapsed ) + rate = iterations / elapsed + + @printf( " ---\n" ); + @printf( " iterations: %d\n", iterations ); + @printf( " elapsed: %0.9f\n", elapsed ); + @printf( " rate: %0.9f\n", rate ); + @printf( " ...\n" ); +end + +""" + benchmark( setup, expr ) + +Run a benchmark. + +# Notes + +* Benchmark results are returned as a two-element array: [ iterations, elapsed ]. +* The number of iterations is not the true number of iterations. Instead, an 'iteration' is defined as a 'sample', which is a computed estimate for a single evaluation. +* The elapsed time is in seconds. + +# Arguments + +* `setup`: setup expression +* `expr`: expression to benchmark + +# Examples + +``` julia +julia> out = benchmark( :(), :( sin( 3.14 ) ) ); +``` +""" +function benchmark( setup, expr ) + t = eval( :( BenchmarkTools.@benchmark $expr samples=$samples setup=($setup) ) ) + + # Compute the total "elapsed" time and convert from nanoseconds to seconds: + s = sum( t.times ) / 1.0e9; + + # Determine the number of "iterations": + iter = length( t.times ); + + # Return the results: + [ iter, s ]; +end + +""" + bench( name, setup, expr ) + +Run a named benchmark. + +# Arguments + +* `name`: benchmark name (suffix) +* `setup`: setup expression +* `expr`: expression to benchmark + +# Examples + +``` julia +julia> bench( "sin", :(), :( sin( 3.14 ) ) ); +``` +""" +function bench( name, setup, expr ) + for i in 1:repeats + @printf( "# julia::%s\n", name ); + global count += 1; + results = benchmark( setup, expr ); + print_results( results[ 1 ], results[ 2 ] ); + @printf( "ok %d benchmark finished\n", count ); + end +end + +""" + main() + +Run benchmarks. + +# Examples + +``` julia +julia> main(); +``` +""" +function main() + print_version(); + + dtypes = [ + Float64, + Float32, + Int32, + Int16, + Int8, + UInt32, + UInt16, + UInt8 + ]; + n = 1; + while n < 1e7 + n *= 10; + for i in 1:length( dtypes ) + name = string( "convert-same:len=", n, ",dtype=", lowercase( string( dtypes[i] ) ) ); + setup = :(A = ones( Float64, $n, 1 ); B = ones( $dtypes[$i], 1, 1 ) ); + stmt = :( C = oftype( B, A ) ); + bench( name, setup, stmt ); + end + end + + print_summary( count, count ); +end + +main(); diff --git a/convert-same/benchmark/python/numpy/benchmark.py b/convert-same/benchmark/python/numpy/benchmark.py new file mode 100644 index 00000000..f23f1258 --- /dev/null +++ b/convert-same/benchmark/python/numpy/benchmark.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python +# +# @license Apache-2.0 +# +# Copyright (c) 2018 The Stdlib Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Benchmark numpy.ndarray.astype.""" + +from __future__ import print_function, division +import timeit + +NAME = "convert-same" +REPEATS = 3 +ITERATIONS = 1000000 +COUNT = [0] # use a list to allow modification within nested scopes + + +def print_version(): + """Print the TAP version.""" + print("TAP version 13") + + +def print_summary(total, passing): + """Print the benchmark summary. + + # Arguments + + * `total`: total number of tests + * `passing`: number of passing tests + + """ + print("#") + print("1.." + str(total)) # TAP plan + print("# total " + str(total)) + print("# pass " + str(passing)) + print("#") + print("# ok") + + +def print_results(iterations, elapsed): + """Print benchmark results. + + # Arguments + + * `iterations`: number of iterations + * `elapsed`: elapsed time (in seconds) + + # Examples + + ``` python + python> print_results(100000, 0.131009101868) + ``` + """ + rate = iterations / elapsed + + print(" ---") + print(" iterations: " + str(iterations)) + print(" elapsed: " + str(elapsed)) + print(" rate: " + str(rate)) + print(" ...") + + +def benchmark(name, setup, stmt, iterations): + """Run the benchmark and print benchmark results. + + # Arguments + + * `name`: benchmark name (suffix) + * `setup`: benchmark setup + * `stmt`: statement to benchmark + * `iterations`: number of iterations + + # Examples + + ``` python + python> benchmark("::random", "from random import random;", "y = random()", 1000000) + ``` + """ + t = timeit.Timer(stmt, setup=setup) + + i = 0 + while i < REPEATS: + print("# python::numpy::" + NAME + name) + COUNT[0] += 1 + elapsed = t.timeit(number=iterations) + print_results(iterations, elapsed) + print("ok " + str(COUNT[0]) + " benchmark finished") + i += 1 + + +def main(): + """Run the benchmarks.""" + print_version() + + dtypes = [ + "float64", + "float32", + "int32", + "int16", + "int8", + "uint32", + "uint16", + "uint8" + ] + iters = ITERATIONS + n = 1 + while n < 1e7: + n *= 10 + for i in range(0, len(dtypes)): + dtype = dtypes[i] + name = ":len="+str(n)+",dtype="+dtype + setup = "import numpy as np;" + setup += "A = np.ones([1,"+str(n)+"], dtype='float64');" + setup += "B = np.ones([1,1], dtype='"+dtype+"');" + stmt = "C = A.astype(B.dtype)" + benchmark(name, setup, stmt, iters) + iters //= 4 + + print_summary(COUNT[0], COUNT[0]) + + +if __name__ == "__main__": + main() diff --git a/convert-same/docs/repl.txt b/convert-same/docs/repl.txt new file mode 100644 index 00000000..d30e7992 --- /dev/null +++ b/convert-same/docs/repl.txt @@ -0,0 +1,40 @@ + +{{alias}}( x, y ) + Converts an input array to the same data type as a second input array. + + The function supports input arrays having the following data types: + + - float32: single-precision floating-point numbers. + - float64: double-precision floating-point numbers. + - generic: values of any type. + - int16: signed 16-bit integers. + - int32: signed 32-bit integers. + - int8: signed 8-bit integers. + - uint16: unsigned 16-bit integers. + - uint32: unsigned 32-bit integers. + - uint8: unsigned 8-bit integers. + - uint8c: unsigned clamped 8-bit integers. + + Parameters + ---------- + x: Array|TypedArray + Array to convert. + + y: Array|TypedArray + Array having desired output data type. + + Returns + ------- + out: Array|TypedArray + Output array. + + Examples + -------- + > var x = [ 1.0, 2.0, 3.0, 4.0 ]; + > var y = new {{alias:@stdlib/array/float32}}( 0 ); + > var out = {{alias}}( x, y ) + [ 1.0, 2.0, 3.0, 4.0 ] + + See Also + -------- + diff --git a/convert-same/docs/types/index.d.ts b/convert-same/docs/types/index.d.ts new file mode 100644 index 00000000..520e5607 --- /dev/null +++ b/convert-same/docs/types/index.d.ts @@ -0,0 +1,53 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/// + +import { TypedArray } from '@stdlib/types/array'; +import { Collection } from '@stdlib/types/object'; + + +/** +* Array or typed array. +*/ +type ArrayOrTypedArray = Array | TypedArray; + +/** +* Converts an array to the same data type as a second input array. +* +* @param x - array to convert +* @param y - array having the desired output data type +* @returns output array +* +* @example +* var Float64Array = require( `@stdlib/array/float64` ); +* +* var y = new Float64Array( 0 ); +* +* var x = [ 1.0, 2.0, 3.0, 4.0 ]; +* var out = convertSame( x, y ); +* // returns [ 1.0, 2.0, 3.0, 4.0 ] +*/ +declare function convertSame( x: Collection, y: ArrayOrTypedArray ): ArrayOrTypedArray; // tslint:disable-line:max-line-length unified-signatures + + +// EXPORTS // + +export = convertSame; diff --git a/convert-same/docs/types/test.ts b/convert-same/docs/types/test.ts new file mode 100644 index 00000000..f702889f --- /dev/null +++ b/convert-same/docs/types/test.ts @@ -0,0 +1,64 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import convertSame = require( './index' ); + + +// TESTS // + +// The function returns an array or typed array... +{ + const y = new Float64Array( 0 ); + + convertSame( [ 1.0, 2.0, 3.0, 4.0 ], y ); // $ExpectType ArrayOrTypedArray +} + +// The compiler throws an error if the function is provided a first argument which is not array-like... +{ + const y = new Float64Array( 0 ); + + convertSame( 123, y ); // $ExpectError + convertSame( true, y ); // $ExpectError + convertSame( false, y ); // $ExpectError + convertSame( {}, y ); // $ExpectError + convertSame( null, y ); // $ExpectError + convertSame( undefined, y ); // $ExpectError +} + +// The compiler throws an error if the function is provided a second argument which is not an array or typed array... +{ + const x = [ 1.0, 2.0, 3.0, 4.0 ]; + + convertSame( x, 'abc' ); // $ExpectError + convertSame( x, 123 ); // $ExpectError + convertSame( x, true ); // $ExpectError + convertSame( x, false ); // $ExpectError + convertSame( x, {} ); // $ExpectError + convertSame( x, null ); // $ExpectError + convertSame( x, undefined ); // $ExpectError +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + const x = [ 1.0, 2.0, 3.0, 4.0 ]; + const y = new Float64Array( 0 ); + + convertSame(); // $ExpectError + convertSame( x ); // $ExpectError + convertSame( x, y, 2 ); // $ExpectError +} diff --git a/convert-same/examples/index.js b/convert-same/examples/index.js new file mode 100644 index 00000000..23f37706 --- /dev/null +++ b/convert-same/examples/index.js @@ -0,0 +1,46 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var dtypes = require( '@stdlib/array/dtypes' ); +var ctors = require( '@stdlib/array/ctors' ); +var randu = require( '@stdlib/random/base/randu' ); +var floor = require( '@stdlib/math/base/special/floor' ); +var convertArraySame = require( './../lib' ); + +// Create a generic array: +var x = []; +var i; +for ( i = 0; i < 5; i++ ) { + x.push( floor( randu()*1.0e25 ) - 5.0e24 ); +} + +// Get a list of array data types: +var DTYPES = dtypes(); + +// Convert the generic array to each array data type: +var ctor; +var out; +var y; +for ( i = 0; i < DTYPES.length; i++ ) { + ctor = ctors( DTYPES[ i ] ); + y = new ctor( 0 ); + out = convertArraySame( x, y ); + console.log( out ); +} diff --git a/convert-same/lib/index.js b/convert-same/lib/index.js new file mode 100644 index 00000000..76fa1b63 --- /dev/null +++ b/convert-same/lib/index.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Convert an array to the same data type as a second input array. +* +* @module @stdlib/array/convert-same +* +* @example +* var convertSame = require( '@stdlib/array/convert-same' ); +* var Float64Array = require( '@stdlib/array/float64' ); +* +* var y = new Float64Array( 0 ); +* +* var x = [ 1.0, 2.0, 3.0, 4.0 ]; +* var out = convertSame( x, y ); +* // returns [ 1.0, 2.0, 3.0, 4.0 ] +*/ + +// MODULES // + +var convertSame = require( './main.js' ); + + +// EXPORTS // + +module.exports = convertSame; diff --git a/convert-same/lib/main.js b/convert-same/lib/main.js new file mode 100644 index 00000000..5b147f23 --- /dev/null +++ b/convert-same/lib/main.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isCollection = require( '@stdlib/assert/is-collection' ); +var getType = require( '@stdlib/array/dtype' ); +var ctors = require( '@stdlib/array/ctors' ); + + +// MAIN // + +/** +* Converts an array to the same data type as a second input array. +* +* @param {Collection} x - array to convert +* @param {(Array|TypedArray)} y - array having the desired output data type +* @throws {TypeError} first argument must be an array-like object +* @throws {TypeError} second argument must have a recognized data type +* @returns {(Array|TypedArray)} output array +* +* @example +* var Float64Array = require( '@stdlib/array/float64' ); +* +* var y = new Float64Array( 0 ); +* +* var x = [ 1.0, 2.0, 3.0, 4.0 ]; +* var out = convertSame( x, y ); +* // returns [ 1.0, 2.0, 3.0, 4.0 ] +*/ +function convertSame( x, y ) { + var dtype; + var ctor; + var out; + var len; + var i; + if ( !isCollection( x ) ) { + throw new TypeError( 'invalid argument. First argument must be an array-like object. Value: `' + x + '`.' ); + } + dtype = getType( y ); + ctor = ctors( dtype ); + if ( ctor === null ) { + throw new TypeError( 'invalid argument. Second argument must have a recognized data type. Value: `' + dtype + '`.' ); + } + len = x.length; + if ( dtype === 'generic' ) { + out = []; + for ( i = 0; i < len; i++ ) { + out.push( x[ i ] ); // ensure "fast" elements + } + return out; + } + out = new ctor( len ); + for ( i = 0; i < len; i++ ) { + out[ i ] = x[ i ]; + } + return out; +} + + +// EXPORTS // + +module.exports = convertSame; diff --git a/convert-same/package.json b/convert-same/package.json new file mode 100644 index 00000000..4c1db69c --- /dev/null +++ b/convert-same/package.json @@ -0,0 +1,67 @@ +{ + "name": "@stdlib/array/convert-same", + "version": "0.0.0", + "description": "Convert an array to the same data type as a second input array.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structure", + "array", + "typed", + "typed array", + "typed-array", + "convert", + "cast", + "transform", + "copy", + "duplicate" + ] +} diff --git a/convert-same/test/test.js b/convert-same/test/test.js new file mode 100644 index 00000000..19031b9b --- /dev/null +++ b/convert-same/test/test.js @@ -0,0 +1,217 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var dtype = require( '@stdlib/array/dtype' ); +var Float64Array = require( '@stdlib/array/float64' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Int8Array = require( '@stdlib/array/int8' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); +var isArray = require( '@stdlib/assert/is-array' ); +var isFloat64Array = require( '@stdlib/assert/is-float64array' ); +var isFloat32Array = require( '@stdlib/assert/is-float32array' ); +var isInt16Array = require( '@stdlib/assert/is-int16array' ); +var isInt32Array = require( '@stdlib/assert/is-int32array' ); +var isInt8Array = require( '@stdlib/assert/is-int8array' ); +var isUint16Array = require( '@stdlib/assert/is-uint16array' ); +var isUint32Array = require( '@stdlib/assert/is-uint32array' ); +var isUint8Array = require( '@stdlib/assert/is-uint8array' ); +var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); +var convertArraySame = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof convertArraySame, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'if not provided an array-like object as its first argument, the function throws an error', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[ i ] ), TypeError, 'throws an error when provided ' + values[ i ] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + convertArraySame( value, 'float64' ); + }; + } +}); + +tape( 'if provided an argument having an unknown/unsupported data type, the function throws an error', function test( t ) { + var values; + var i; + + values = [ + 'binary', + 'buffer', + 'buf', + 'float', + 'double', + 'single', + 'int', + 'integer', + 'uint', + 'uinteger', + 'byte', + 'bits', + 'float64', + 'float32', + 'int32', + 'int16', + 'int8', + 'uint32', + 'uint16', + 'uint8', + 'uint8c', + 'generic', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[ i ] ), TypeError, 'throws an error when provided ' + values[ i ] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + convertArraySame( [ 1, 2, 3 ], value ); + }; + } +}); + +tape( 'the function converts an array to the same data type as a second input array', function test( t ) { + var expected; + var out; + var dt; + var x; + var y; + var i; + var j; + + y = [ + new Float64Array( 0 ), + new Float32Array( 0 ), + [], + new Int16Array( 0 ), + new Int32Array( 0 ), + new Int8Array( 0 ), + new Uint16Array( 0 ), + new Uint32Array( 0 ), + new Uint8Array( 0 ), + new Uint8ClampedArray( 0 ) + ]; + x = [ -1, 0, 1 ]; + expected = [ + [ new Float64Array( [ -1.0, 0.0, 1.0 ] ), isFloat64Array ], + [ new Float32Array( [ -1.0, 0.0, 1.0 ] ), isFloat32Array ], + [ x, isArray ], + [ new Int16Array( [ -1, 0, 1 ] ), isInt16Array ], + [ new Int32Array( [ -1, 0, 1 ] ), isInt32Array ], + [ new Int8Array( [ -1, 0, 1 ] ), isInt8Array ], + [ new Uint16Array( [ 65535, 0, 1 ] ), isUint16Array ], + [ new Uint32Array( [ 4294967295, 0, 1 ] ), isUint32Array ], + [ new Uint8Array( [ 255, 0, 1 ] ), isUint8Array ], + [ new Uint8ClampedArray( [ 0, 0, 1 ] ), isUint8ClampedArray ] + ]; + for ( i = 0; i < y.length; i++ ) { + dt = dtype( y[ i ] ); + out = convertArraySame( x, y[ i ] ); + t.strictEqual( expected[ i ][ 1 ]( out ), true, 'returns expected value type for ' + dt ); + for ( j = 0; j < x.length; j++ ) { + t.strictEqual( out[ j ], expected[ i ][ 0 ][ j ], 'returns expected element ' + j + ' for ' + dt ); + } + } + t.end(); +}); + +tape( 'the function converts an array to the same data type as a second input array (large allocations)', function test( t ) { + var expected; + var out; + var dt; + var x; + var y; + var i; + + y = [ + new Float64Array( 0 ), + new Float32Array( 0 ), + [], + new Int16Array( 0 ), + new Int32Array( 0 ), + new Int8Array( 0 ), + new Uint16Array( 0 ), + new Uint32Array( 0 ), + new Uint8Array( 0 ), + new Uint8ClampedArray( 0 ) + ]; + x = []; + for ( i = 0; i < 1e6; i++ ) { + x.push( 0 ); + } + expected = [ + isFloat64Array, + isFloat32Array, + isArray, + isInt16Array, + isInt32Array, + isInt8Array, + isUint16Array, + isUint32Array, + isUint8Array, + isUint8ClampedArray + ]; + for ( i = 0; i < y.length; i++ ) { + dt = dtype( y[ i ] ); + out = convertArraySame( x, y[ i ] ); + t.strictEqual( expected[ i ]( out ), true, 'returns expected value type for ' + dt ); + } + t.end(); +}); diff --git a/convert/README.md b/convert/README.md new file mode 100644 index 00000000..7a82dc49 --- /dev/null +++ b/convert/README.md @@ -0,0 +1,128 @@ + + +# Convert + +> Convert an array to an array of a different data type. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var convertArray = require( '@stdlib/array/convert' ); +``` + +#### convertArray( arr, dtype ) + +Converts an `array` to an array of a different data type. + +```javascript +var arr = [ 1.0, 2.0, 3.0 ]; +var out = convertArray( arr, 'float32' ); +// returns [ 1.0, 2.0, 3.0 ] +``` + +The function supports the following data types: + +- `float32`: single-precision floating-point numbers. +- `float64`: double-precision floating-point numbers. +- `generic`: values of any type. +- `int16`: signed 16-bit integers. +- `int32`: signed 32-bit integers. +- `int8`: signed 8-bit integers. +- `uint16`: unsigned 16-bit integers. +- `uint32`: unsigned 32-bit integers. +- `uint8`: unsigned 8-bit integers. +- `uint8c`: unsigned clamped 8-bit integers. + +
+ + + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var dtypes = require( '@stdlib/array/dtypes' ); +var randu = require( '@stdlib/random/base/randu' ); +var floor = require( '@stdlib/math/base/special/floor' ); +var convertArray = require( '@stdlib/array/convert' ); + +// Create a generic array: +var arr = []; +var i; +for ( i = 0; i < 5; i++ ) { + arr.push( floor( randu()*1.0e25 ) - 5.0e24 ); +} + +// Get a list of array data types: +var DTYPES = dtypes(); + +// Convert the generic array to each array data type: +var out; +for ( i = 0; i < DTYPES.length; i++ ) { + out = convertArray( arr, DTYPES[ i ] ); + console.log( out ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/convert/benchmark/benchmark.js b/convert/benchmark/benchmark.js new file mode 100644 index 00000000..7f0b11c2 --- /dev/null +++ b/convert/benchmark/benchmark.js @@ -0,0 +1,279 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isCollection = require( '@stdlib/assert/is-collection' ); +var pkg = require( './../package.json' ).name; +var convertArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':dtype=generic', function benchmark( b ) { + var arr; + var out; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArray( arr, 'generic' ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=float64', function benchmark( b ) { + var arr; + var out; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArray( arr, 'float64' ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=float32', function benchmark( b ) { + var arr; + var out; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArray( arr, 'float32' ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=int32', function benchmark( b ) { + var arr; + var out; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArray( arr, 'int32' ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=int16', function benchmark( b ) { + var arr; + var out; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArray( arr, 'int16' ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=int8', function benchmark( b ) { + var arr; + var out; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArray( arr, 'int8' ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint32', function benchmark( b ) { + var arr; + var out; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArray( arr, 'uint32' ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint16', function benchmark( b ) { + var arr; + var out; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArray( arr, 'uint16' ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint8', function benchmark( b ) { + var arr; + var out; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArray( arr, 'uint8' ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint8c', function benchmark( b ) { + var arr; + var out; + var i; + + arr = []; + for ( i = 0; i < 10; i++ ) { + arr.push( i ); + } + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] += 1; + out = convertArray( arr, 'uint8c' ); + if ( out.length !== arr.length ) { + b.fail( 'should have expected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/convert/benchmark/benchmark.length.js b/convert/benchmark/benchmark.length.js new file mode 100644 index 00000000..a88fca1f --- /dev/null +++ b/convert/benchmark/benchmark.length.js @@ -0,0 +1,129 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isCollection = require( '@stdlib/assert/is-collection' ); +var pkg = require( './../package.json' ).name; +var convertArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @param {string} dtype - data type +* @returns {Function} benchmark function +*/ +function createBenchmark( len, dtype ) { + var arr; + var i; + + arr = []; + for ( i = 0; i < len; i++ ) { + arr[ i ] = i; + } + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = convertArray( arr, dtype ); + if ( out.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isCollection( out ) ) { + b.fail( 'should return an array-like object' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + + f = createBenchmark( len, 'generic' ); + bench( pkg+':len='+len+',dtype=generic', f ); + + f = createBenchmark( len, 'float64' ); + bench( pkg+':len='+len+',dtype=float64', f ); + + f = createBenchmark( len, 'float32' ); + bench( pkg+':len='+len+',dtype=float32', f ); + + f = createBenchmark( len, 'int32' ); + bench( pkg+':len='+len+',dtype=int32', f ); + + f = createBenchmark( len, 'int16' ); + bench( pkg+':len='+len+',dtype=int16', f ); + + f = createBenchmark( len, 'int8' ); + bench( pkg+':len='+len+',dtype=int8', f ); + + f = createBenchmark( len, 'uint32' ); + bench( pkg+':len='+len+',dtype=uint32', f ); + + f = createBenchmark( len, 'uint16' ); + bench( pkg+':len='+len+',dtype=uint16', f ); + + f = createBenchmark( len, 'uint8' ); + bench( pkg+':len='+len+',dtype=uint8', f ); + + f = createBenchmark( len, 'uint8c' ); + bench( pkg+':len='+len+',dtype=uint8c', f ); + } +} + +main(); diff --git a/convert/benchmark/julia/REQUIRE b/convert/benchmark/julia/REQUIRE new file mode 100644 index 00000000..98645e19 --- /dev/null +++ b/convert/benchmark/julia/REQUIRE @@ -0,0 +1,2 @@ +julia 1.5 +BenchmarkTools 0.5.0 diff --git a/convert/benchmark/julia/benchmark.jl b/convert/benchmark/julia/benchmark.jl new file mode 100644 index 00000000..c4e50f81 --- /dev/null +++ b/convert/benchmark/julia/benchmark.jl @@ -0,0 +1,193 @@ +#!/usr/bin/env julia +# +# @license Apache-2.0 +# +# Copyright (c) 2018 The Stdlib Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import BenchmarkTools +using Printf + +# Benchmark variables: +repeats = 3; +samples = 1e3; +count = 0; + +""" + print_version() + +Prints the TAP version. + +# Examples + +``` julia +julia> print_version() +``` +""" +function print_version() + @printf( "TAP version 13\n" ); +end + +""" + print_summary( total, passing ) + +Print the benchmark summary. + +# Arguments + +* `total`: total number of tests +* `passing`: number of passing tests + +# Examples + +``` julia +julia> print_summary( 3, 3 ) +``` +""" +function print_summary( total, passing ) + @printf( "#\n" ); + @printf( "1..%d\n", total ); # TAP plan + @printf( "# total %d\n", total ); + @printf( "# pass %d\n", passing ); + @printf( "#\n" ); + @printf( "# ok\n" ); +end + +""" + print_results( iterations, elapsed ) + +Print benchmark results. + +# Arguments + +* `iterations`: number of iterations +* `elapsed`: elapsed time (in seconds) + +# Examples + +``` julia +julia> print_results( 1000000, 0.131009101868 ) +``` +""" +function print_results( iterations, elapsed ) + rate = iterations / elapsed + + @printf( " ---\n" ); + @printf( " iterations: %d\n", iterations ); + @printf( " elapsed: %0.9f\n", elapsed ); + @printf( " rate: %0.9f\n", rate ); + @printf( " ...\n" ); +end + +""" + benchmark( setup, expr ) + +Run a benchmark. + +# Notes + +* Benchmark results are returned as a two-element array: [ iterations, elapsed ]. +* The number of iterations is not the true number of iterations. Instead, an 'iteration' is defined as a 'sample', which is a computed estimate for a single evaluation. +* The elapsed time is in seconds. + +# Arguments + +* `setup`: setup expression +* `expr`: expression to benchmark + +# Examples + +``` julia +julia> out = benchmark( :(), :( sin( 3.14 ) ) ); +``` +""" +function benchmark( setup, expr ) + t = eval( :( BenchmarkTools.@benchmark $expr samples=$samples setup=($setup) ) ) + + # Compute the total "elapsed" time and convert from nanoseconds to seconds: + s = sum( t.times ) / 1.0e9; + + # Determine the number of "iterations": + iter = length( t.times ); + + # Return the results: + [ iter, s ]; +end + +""" + bench( name, setup, expr ) + +Run a named benchmark. + +# Arguments + +* `name`: benchmark name (suffix) +* `setup`: setup expression +* `expr`: expression to benchmark + +# Examples + +``` julia +julia> bench( "sin", :(), :( sin( 3.14 ) ) ); +``` +""" +function bench( name, setup, expr ) + for i in 1:repeats + @printf( "# julia::%s\n", name ); + global count += 1; + results = benchmark( setup, expr ); + print_results( results[ 1 ], results[ 2 ] ); + @printf( "ok %d benchmark finished\n", count ); + end +end + +""" + main() + +Run benchmarks. + +# Examples + +``` julia +julia> main(); +``` +""" +function main() + print_version(); + + dtypes = [ + Float64, + Float32, + Int32, + Int16, + Int8, + UInt32, + UInt16, + UInt8 + ]; + n = 1; + while n < 1e7 + n *= 10; + for i in 1:length( dtypes ) + name = string( "convert:len=", n, ",dtype=", lowercase( string( dtypes[i] ) ) ); + setup = :(A = ones( Float64, $n, 1 )); + stmt = :( B = convert( Array{ $dtypes[$i] }, A ) ); + bench( name, setup, stmt ); + end + end + + print_summary( count, count ); +end + +main(); diff --git a/convert/benchmark/python/numpy/benchmark.py b/convert/benchmark/python/numpy/benchmark.py new file mode 100644 index 00000000..ddf9cba8 --- /dev/null +++ b/convert/benchmark/python/numpy/benchmark.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python +# +# @license Apache-2.0 +# +# Copyright (c) 2018 The Stdlib Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Benchmark numpy.ndarray.astype.""" + +from __future__ import print_function, division +import timeit + +NAME = "convert" +REPEATS = 3 +ITERATIONS = 1000000 +COUNT = [0] # use a list to allow modification within nested scopes + + +def print_version(): + """Print the TAP version.""" + print("TAP version 13") + + +def print_summary(total, passing): + """Print the benchmark summary. + + # Arguments + + * `total`: total number of tests + * `passing`: number of passing tests + + """ + print("#") + print("1.." + str(total)) # TAP plan + print("# total " + str(total)) + print("# pass " + str(passing)) + print("#") + print("# ok") + + +def print_results(iterations, elapsed): + """Print benchmark results. + + # Arguments + + * `iterations`: number of iterations + * `elapsed`: elapsed time (in seconds) + + # Examples + + ``` python + python> print_results(100000, 0.131009101868) + ``` + """ + rate = iterations / elapsed + + print(" ---") + print(" iterations: " + str(iterations)) + print(" elapsed: " + str(elapsed)) + print(" rate: " + str(rate)) + print(" ...") + + +def benchmark(name, setup, stmt, iterations): + """Run the benchmark and print benchmark results. + + # Arguments + + * `name`: benchmark name (suffix) + * `setup`: benchmark setup + * `stmt`: statement to benchmark + * `iterations`: number of iterations + + # Examples + + ``` python + python> benchmark("::random", "from random import random;", "y = random()", 1000000) + ``` + """ + t = timeit.Timer(stmt, setup=setup) + + i = 0 + while i < REPEATS: + print("# python::numpy::" + NAME + name) + COUNT[0] += 1 + elapsed = t.timeit(number=iterations) + print_results(iterations, elapsed) + print("ok " + str(COUNT[0]) + " benchmark finished") + i += 1 + + +def main(): + """Run the benchmarks.""" + print_version() + + dtypes = [ + "float64", + "float32", + "int32", + "int16", + "int8", + "uint32", + "uint16", + "uint8" + ] + iters = ITERATIONS + n = 1 + while n < 1e7: + n *= 10 + for i in range(0, len(dtypes)): + dtype = dtypes[i] + name = ":len="+str(n)+",dtype="+dtype + setup = "import numpy as np;" + setup += "A = np.ones([1,"+str(n)+"], dtype='float64');" + stmt = "B = A.astype('"+dtype+"')" + benchmark(name, setup, stmt, iters) + iters //= 4 + + print_summary(COUNT[0], COUNT[0]) + + +if __name__ == "__main__": + main() diff --git a/convert/docs/repl.txt b/convert/docs/repl.txt new file mode 100644 index 00000000..ba168d60 --- /dev/null +++ b/convert/docs/repl.txt @@ -0,0 +1,39 @@ + +{{alias}}( arr, dtype ) + Converts an input array to an array of a different data type. + + The function supports the following data types: + + - float32: single-precision floating-point numbers. + - float64: double-precision floating-point numbers. + - generic: values of any type. + - int16: signed 16-bit integers. + - int32: signed 32-bit integers. + - int8: signed 8-bit integers. + - uint16: unsigned 16-bit integers. + - uint32: unsigned 32-bit integers. + - uint8: unsigned 8-bit integers. + - uint8c: unsigned clamped 8-bit integers. + + Parameters + ---------- + arr: Array|TypedArray + Array to convert. + + dtype: string + Output data type. + + Returns + ------- + out: Array|TypedArray + Output array. + + Examples + -------- + > var arr = [ 1.0, 2.0, 3.0, 4.0 ]; + > var out = {{alias}}( arr, 'float32' ) + [ 1.0, 2.0, 3.0, 4.0 ] + + See Also + -------- + diff --git a/convert/docs/types/index.d.ts b/convert/docs/types/index.d.ts new file mode 100644 index 00000000..9322ac5b --- /dev/null +++ b/convert/docs/types/index.d.ts @@ -0,0 +1,53 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/// + +import { TypedArray } from '@stdlib/types/array'; +import { Collection } from '@stdlib/types/object'; + +/** +* Array data type. +*/ +type DataType = 'float32' | 'float64' | 'generic' | 'int16' | 'int32' | 'int8' | 'uint16' | 'uint32' | 'uint8' | 'uint8c'; // tslint:disable-line:max-line-length unified-signatures + +/** +* Array or typed array. +*/ +type ArrayOrTypedArray = Array | TypedArray; + +/** +* Converts an array to an array of a different data type. +* +* @param x - array to convert +* @param dtype - output data type +* @returns output array +* +* @example +* var arr = [ 1.0, 2.0, 3.0, 4.0 ]; +* var out = convert( arr, 'float64' ); +* // returns [ 1.0, 2.0, 3.0, 4.0 ] +*/ +declare function convert( x: Collection, dtype: DataType ): ArrayOrTypedArray; + + +// EXPORTS // + +export = convert; diff --git a/convert/docs/types/test.ts b/convert/docs/types/test.ts new file mode 100644 index 00000000..38a92b1b --- /dev/null +++ b/convert/docs/types/test.ts @@ -0,0 +1,56 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import convert = require( './index' ); + + +// TESTS // + +// The function returns an array or typed array... +{ + convert( [ 1.0, 2.0, 3.0, 4.0 ], 'int32' ); // $ExpectType ArrayOrTypedArray + convert( [ 1.0, 2.0, 3.0, 4.0 ], 'float32' ); // $ExpectType ArrayOrTypedArray +} + +// The compiler throws an error if the function is provided a first argument which is not array-like... +{ + convert( 123, 'float64' ); // $ExpectError + convert( true, 'float64' ); // $ExpectError + convert( false, 'float64' ); // $ExpectError + convert( {}, 'float64' ); // $ExpectError + convert( null, 'float64' ); // $ExpectError + convert( undefined, 'float64' ); // $ExpectError +} + +// The compiler throws an error if the function is provided a second argument which is not a known data type... +{ + convert( [ 1, 2, 3, 4 ], 'abc' ); // $ExpectError + convert( [ 1, 2, 3, 4 ], 123 ); // $ExpectError + convert( [ 1, 2, 3, 4 ], [] ); // $ExpectError + convert( [ 1, 2, 3, 4 ], {} ); // $ExpectError + convert( [ 1, 2, 3, 4 ], true ); // $ExpectError + convert( [ 1, 2, 3, 4 ], false ); // $ExpectError + convert( [ 1, 2, 3, 4 ], null ); // $ExpectError +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + convert(); // $ExpectError + convert( [ 1.0, 2.0, 3.0, 4.0 ] ); // $ExpectError + convert( [ 1.0, 2.0, 3.0, 4.0 ], 'float64', 2 ); // $ExpectError +} diff --git a/convert/examples/index.js b/convert/examples/index.js new file mode 100644 index 00000000..0eeb995c --- /dev/null +++ b/convert/examples/index.js @@ -0,0 +1,41 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var dtypes = require( '@stdlib/array/dtypes' ); +var randu = require( '@stdlib/random/base/randu' ); +var floor = require( '@stdlib/math/base/special/floor' ); +var convertArray = require( './../lib' ); + +// Create a generic array: +var arr = []; +var i; +for ( i = 0; i < 5; i++ ) { + arr.push( floor( randu()*1.0e25 ) - 5.0e24 ); +} + +// Get a list of array data types: +var DTYPES = dtypes(); + +// Convert the generic array to each array data type: +var out; +for ( i = 0; i < DTYPES.length; i++ ) { + out = convertArray( arr, DTYPES[ i ] ); + console.log( out ); +} diff --git a/convert/lib/index.js b/convert/lib/index.js new file mode 100644 index 00000000..2a68e794 --- /dev/null +++ b/convert/lib/index.js @@ -0,0 +1,41 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Convert an array to an array of a different data type. +* +* @module @stdlib/array/convert +* +* @example +* var convert = require( '@stdlib/array/convert' ); +* +* var arr = [ 1.0, 2.0, 3.0, 4.0 ]; +* var out = convert( arr, 'float64' ); +* // returns [ 1.0, 2.0, 3.0, 4.0 ] +*/ + +// MODULES // + +var convert = require( './main.js' ); + + +// EXPORTS // + +module.exports = convert; diff --git a/convert/lib/main.js b/convert/lib/main.js new file mode 100644 index 00000000..e9dec39d --- /dev/null +++ b/convert/lib/main.js @@ -0,0 +1,73 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isCollection = require( '@stdlib/assert/is-collection' ); +var ctors = require( '@stdlib/array/ctors' ); + + +// MAIN // + +/** +* Converts an array to an array of a different data type. +* +* @param {Collection} x - array to convert +* @param {string} dtype - output data type +* @throws {TypeError} first argument must be an array-like object +* @throws {TypeError} second argument must be a recognized array data type +* @returns {(Array|TypedArray)} output array +* +* @example +* var arr = [ 1.0, 2.0, 3.0, 4.0 ]; +* var out = convert( arr, 'float64' ); +* // returns [ 1.0, 2.0, 3.0, 4.0 ] +*/ +function convert( x, dtype ) { + var ctor; + var out; + var len; + var i; + if ( !isCollection( x ) ) { + throw new TypeError( 'invalid argument. First argument must be an array-like object. Value: `' + x + '`.' ); + } + len = x.length; + ctor = ctors( dtype ); + if ( ctor === null ) { + throw new TypeError( 'invalid argument. Second argument must be a recognized array data type. Value: `' + dtype + '`.' ); + } + if ( dtype === 'generic' ) { + out = []; + for ( i = 0; i < len; i++ ) { + out.push( x[ i ] ); // ensure "fast" elements + } + return out; + } + out = new ctor( len ); + for ( i = 0; i < len; i++ ) { + out[ i ] = x[ i ]; + } + return out; +} + + +// EXPORTS // + +module.exports = convert; diff --git a/convert/package.json b/convert/package.json new file mode 100644 index 00000000..41f391a2 --- /dev/null +++ b/convert/package.json @@ -0,0 +1,67 @@ +{ + "name": "@stdlib/array/convert", + "version": "0.0.0", + "description": "Convert an array to an array of a different data type.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structure", + "array", + "typed", + "typed array", + "typed-array", + "convert", + "cast", + "transform", + "copy", + "duplicate" + ] +} diff --git a/convert/test/test.js b/convert/test/test.js new file mode 100644 index 00000000..a40a6cdf --- /dev/null +++ b/convert/test/test.js @@ -0,0 +1,194 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var Float64Array = require( '@stdlib/array/float64' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Int8Array = require( '@stdlib/array/int8' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); +var isArray = require( '@stdlib/assert/is-array' ); +var isFloat64Array = require( '@stdlib/assert/is-float64array' ); +var isFloat32Array = require( '@stdlib/assert/is-float32array' ); +var isInt16Array = require( '@stdlib/assert/is-int16array' ); +var isInt32Array = require( '@stdlib/assert/is-int32array' ); +var isInt8Array = require( '@stdlib/assert/is-int8array' ); +var isUint16Array = require( '@stdlib/assert/is-uint16array' ); +var isUint32Array = require( '@stdlib/assert/is-uint32array' ); +var isUint8Array = require( '@stdlib/assert/is-uint8array' ); +var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); +var convertArray = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof convertArray, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'if not provided an array-like object as its first argument, the function throws an error', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[ i ] ), TypeError, 'throws an error when provided ' + values[ i ] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + convertArray( value, 'float64' ); + }; + } +}); + +tape( 'if provided an unknown/unsupported data type, the function throws an error', function test( t ) { + var values; + var i; + + values = [ + 'binary', + 'buffer', + 'buf', + 'float', + 'double', + 'single', + 'int', + 'integer', + 'uint', + 'uinteger', + 'byte', + 'bits' + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[ i ] ), TypeError, 'throws an error when provided ' + values[ i ] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + convertArray( [ 1, 2, 3 ], value ); + }; + } +}); + +tape( 'the function converts an array to an array of a different data type', function test( t ) { + var expected; + var dtypes; + var arr; + var out; + var i; + var j; + + dtypes = [ + 'float64', + 'float32', + 'generic', + 'int16', + 'int32', + 'int8', + 'uint16', + 'uint32', + 'uint8', + 'uint8c' + ]; + arr = [ -1, 0, 1 ]; + expected = [ + [ new Float64Array( [ -1.0, 0.0, 1.0 ] ), isFloat64Array ], + [ new Float32Array( [ -1.0, 0.0, 1.0 ] ), isFloat32Array ], + [ arr, isArray ], + [ new Int16Array( [ -1, 0, 1 ] ), isInt16Array ], + [ new Int32Array( [ -1, 0, 1 ] ), isInt32Array ], + [ new Int8Array( [ -1, 0, 1 ] ), isInt8Array ], + [ new Uint16Array( [ 65535, 0, 1 ] ), isUint16Array ], + [ new Uint32Array( [ 4294967295, 0, 1 ] ), isUint32Array ], + [ new Uint8Array( [ 255, 0, 1 ] ), isUint8Array ], + [ new Uint8ClampedArray( [ 0, 0, 1 ] ), isUint8ClampedArray ] + ]; + for ( i = 0; i < dtypes.length; i++ ) { + out = convertArray( arr, dtypes[ i ] ); + t.strictEqual( expected[ i ][ 1 ]( out ), true, 'returns expected value type for ' + dtypes[ i ] ); + for ( j = 0; j < arr.length; j++ ) { + t.strictEqual( out[ j ], expected[ i ][ 0 ][ j ], 'returns expected element ' + j + ' for ' + dtypes[ i ] ); + } + } + t.end(); +}); + +tape( 'the function converts an array to an array of a different data type (large allocations)', function test( t ) { + var expected; + var dtypes; + var out; + var arr; + var i; + + dtypes = [ + 'float64', + 'float32', + 'generic', + 'int16', + 'int32', + 'int8', + 'uint16', + 'uint32', + 'uint8', + 'uint8c' + ]; + arr = []; + for ( i = 0; i < 1e6; i++ ) { + arr.push( 0 ); + } + expected = [ + isFloat64Array, + isFloat32Array, + isArray, + isInt16Array, + isInt32Array, + isInt8Array, + isUint16Array, + isUint32Array, + isUint8Array, + isUint8ClampedArray + ]; + for ( i = 0; i < dtypes.length; i++ ) { + out = convertArray( arr, dtypes[ i ] ); + t.strictEqual( expected[ i ]( out ), true, 'returns expected value type for ' + dtypes[ i ] ); + } + t.end(); +}); diff --git a/ctors/README.md b/ctors/README.md new file mode 100644 index 00000000..eaf1252e --- /dev/null +++ b/ctors/README.md @@ -0,0 +1,124 @@ + + +# Constructors + +> Array constructors. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var ctors = require( '@stdlib/array/ctors' ); +``` + +#### ctors( dtype ) + +Returns an array constructor for a specified data type. + +```javascript +var ctor = ctors( 'float64' ); +// returns +``` + +The function returns constructors for the following data types: + +- `float32`: single-precision floating-point numbers. +- `float64`: double-precision floating-point numbers. +- `generic`: values of any type. +- `int16`: signed 16-bit integers. +- `int32`: signed 32-bit integers. +- `int8`: signed 8-bit integers. +- `uint16`: unsigned 16-bit integers. +- `uint32`: unsigned 32-bit integers. +- `uint8`: unsigned 8-bit integers. +- `uint8c`: unsigned clamped 8-bit integers. + +If provided an unknown or unsupported data type, the function returns `null`. + +```javascript +var ctor = ctors( 'float' ); +// returns null +``` + +
+ + + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var dtypes = require( '@stdlib/array/dtypes' ); +var ctors = require( '@stdlib/array/ctors' ); + +var DTYPES = dtypes(); +var ctor; +var i; + +for ( i = 0; i < DTYPES.length; i++ ) { + ctor = ctors( DTYPES[ i ] ); + console.log( ctor ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/ctors/benchmark/benchmark.js b/ctors/benchmark/benchmark.js new file mode 100644 index 00000000..4262c328 --- /dev/null +++ b/ctors/benchmark/benchmark.js @@ -0,0 +1,54 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var dtypes = require( '@stdlib/array/dtypes' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var pkg = require( './../package.json' ).name; +var ctors = require( './../lib' ); + + +// VARIABLES // + +var DTYPES = dtypes(); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var ctor; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + ctor = ctors( DTYPES[ i%DTYPES.length ] ); + if ( typeof ctor !== 'function' ) { + b.fail( 'should return a function' ); + } + } + b.toc(); + if ( !isFunction( ctor ) ) { + b.fail( 'should return a function' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/ctors/docs/repl.txt b/ctors/docs/repl.txt new file mode 100644 index 00000000..e317ce4c --- /dev/null +++ b/ctors/docs/repl.txt @@ -0,0 +1,37 @@ + +{{alias}}( dtype ) + Returns an array constructor. + + The function returns constructors for the following data types: + + - float32: single-precision floating-point numbers. + - float64: double-precision floating-point numbers. + - generic: values of any type. + - int16: signed 16-bit integers. + - int32: signed 32-bit integers. + - int8: signed 8-bit integers. + - uint16: unsigned 16-bit integers. + - uint32: unsigned 32-bit integers. + - uint8: unsigned 8-bit integers. + - uint8c: unsigned clamped 8-bit integers. + + Parameters + ---------- + dtype: string + Data type. + + Returns + ------- + out: Function|null + Constructor. + + Examples + -------- + > var ctor = {{alias}}( 'float64' ) + + > ctor = {{alias}}( 'float' ) + null + + See Also + -------- + diff --git a/ctors/docs/types/index.d.ts b/ctors/docs/types/index.d.ts new file mode 100644 index 00000000..4a66a27c --- /dev/null +++ b/ctors/docs/types/index.d.ts @@ -0,0 +1,40 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/** +* Returns an array constructor. +* +* @param dtype - data type +* @returns constructor or null +* +* @example +* var ctor = ctors( 'float64' ); +* // returns +* +* @example +* var ctor = ctors( 'float' ); +* // returns null +*/ +declare function ctors( dtype: string ): Function | null; + + +// EXPORTS // + +export = ctors; diff --git a/ctors/docs/types/test.ts b/ctors/docs/types/test.ts new file mode 100644 index 00000000..d853f896 --- /dev/null +++ b/ctors/docs/types/test.ts @@ -0,0 +1,33 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import ctors = require( './index' ); + +// TESTS // + +// The function returns a function or null.. +{ + ctors( 'float64' ); // $ExpectType Function | null + ctors( 'float' ); // $ExpectType Function | null +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + ctors(); // $ExpectError + ctors( 'int32', 3 ); // $ExpectError +} diff --git a/ctors/examples/index.js b/ctors/examples/index.js new file mode 100644 index 00000000..32dae9eb --- /dev/null +++ b/ctors/examples/index.js @@ -0,0 +1,31 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var dtypes = require( '@stdlib/array/dtypes' ); +var ctors = require( './../lib' ); + +var DTYPES = dtypes(); +var ctor; +var i; + +for ( i = 0; i < DTYPES.length; i++ ) { + ctor = ctors( DTYPES[ i ] ); + console.log( ctor ); +} diff --git a/ctors/lib/ctors.js b/ctors/lib/ctors.js new file mode 100644 index 00000000..708d666b --- /dev/null +++ b/ctors/lib/ctors.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var Float64Array = require( '@stdlib/array/float64' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Int8Array = require( '@stdlib/array/int8' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); + + +// MAIN // + +// Mapping from data types to constructors... +var ctors = { + 'float64': Float64Array, + 'float32': Float32Array, + 'generic': Array, // TODO: replace with `stdlib` pkg + 'int16': Int16Array, + 'int32': Int32Array, + 'int8': Int8Array, + 'uint16': Uint16Array, + 'uint32': Uint32Array, + 'uint8': Uint8Array, + 'uint8c': Uint8ClampedArray +}; + + +// EXPORTS // + +module.exports = ctors; diff --git a/ctors/lib/index.js b/ctors/lib/index.js new file mode 100644 index 00000000..12267ba5 --- /dev/null +++ b/ctors/lib/index.js @@ -0,0 +1,43 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Array constructors. +* +* @module @stdlib/array/ctors +* +* @example +* var ctors = require( '@stdlib/array/ctors' ); +* +* var ctor = ctors( 'float64' ); +* // returns +* +* ctor = ctors( 'int' ); +* // returns null +*/ + +// MODULES // + +var ctors = require( './main.js' ); + + +// EXPORTS // + +module.exports = ctors; diff --git a/ctors/lib/main.js b/ctors/lib/main.js new file mode 100644 index 00000000..c86c29e5 --- /dev/null +++ b/ctors/lib/main.js @@ -0,0 +1,49 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var table = require( './ctors.js' ); + + +// MAIN // + +/** +* Returns an array constructor. +* +* @param {string} dtype - data type +* @returns {(Function|null)} constructor or null +* +* @example +* var ctor = ctors( 'float64' ); +* // returns +* +* @example +* var ctor = ctors( 'float' ); +* // returns null +*/ +function ctors( dtype ) { + return table[ dtype ] || null; +} + + +// EXPORTS // + +module.exports = ctors; diff --git a/ctors/package.json b/ctors/package.json new file mode 100644 index 00000000..5812aafa --- /dev/null +++ b/ctors/package.json @@ -0,0 +1,71 @@ +{ + "name": "@stdlib/array/ctors", + "version": "0.0.0", + "description": "Array constructors.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "array", + "list", + "dtypes", + "dtype", + "data", + "structure", + "constructors", + "constructor", + "ctors", + "ctor", + "utilities", + "utility", + "utils", + "util" + ], + "__stdlib__": {} +} diff --git a/ctors/test/test.js b/ctors/test/test.js new file mode 100644 index 00000000..9dcc9ee7 --- /dev/null +++ b/ctors/test/test.js @@ -0,0 +1,120 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var dtypes = require( '@stdlib/array/dtypes' ); +var Float64Array = require( '@stdlib/array/float64' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Int8Array = require( '@stdlib/array/int8' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var ctors = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctors, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function returns array constructors', function test( t ) { + var expected; + var dtypes; + var ctor; + var i; + + dtypes = [ + 'float64', + 'float32', + 'generic', + 'int16', + 'int32', + 'int8', + 'uint16', + 'uint32', + 'uint8', + 'uint8c' + ]; + expected = [ + Float64Array, + Float32Array, + Array, // TODO: explicitly require + Int16Array, + Int32Array, + Int8Array, + Uint16Array, + Uint32Array, + Uint8Array, + Uint8ClampedArray + ]; + for ( i = 0; i < dtypes.length; i++ ) { + ctor = ctors( dtypes[ i ] ); + t.strictEqual( ctor, expected[ i ], 'returns expected value for ' + dtypes[ i ] ); + } + t.end(); +}); + +tape( 'the function returns a constructor for each supported array data type', function test( t ) { + var DTYPES; + var ctor; + var i; + + DTYPES = dtypes(); + for ( i = 0; i < DTYPES.length; i++ ) { + ctor = ctors( DTYPES[ i ] ); + + // Note: this is a weak test for a "constructor" + t.strictEqual( isFunction( ctor ), true, 'returns a function for ' + DTYPES[ i ] ); + } + t.end(); +}); + +tape( 'if provided an unknown/unsupported data type, the function returns `null`', function test( t ) { + var dtypes; + var i; + + dtypes = [ + 'binary', + 'buffer', + 'buf', + 'float', + 'double', + 'single', + 'int', + 'integer', + 'uint', + 'uinteger', + 'byte', + 'bits' + ]; + for ( i = 0; i < dtypes.length; i++ ) { + t.strictEqual( ctors( dtypes[i] ), null, 'returns expected value for ' + dtypes[ i ] ); + } + t.end(); +}); diff --git a/dataview/README.md b/dataview/README.md new file mode 100644 index 00000000..c79bc3af --- /dev/null +++ b/dataview/README.md @@ -0,0 +1,191 @@ + + +# DataView + +> [Constructor][mdn-dataview] which returns a data view representing a provided array buffer. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var DataView = require( '@stdlib/array/dataview' ); +``` + +#### DataView( buffer\[, byteOffset\[, byteLength]] ) + +Returns a [`DataView`][mdn-dataview] representing a provided array buffer. + + + +```javascript +var ArrayBuffer = require( '@stdlib/array/buffer' ); + +var buf = new ArrayBuffer( 5 ); +// returns + +var dv = new DataView( buf ); +// returns +``` + +* * * + +### Properties + +#### DataView.prototype.buffer + +**Read-only** property which returns the underlying array buffer. + + + +```javascript +var ArrayBuffer = require( '@stdlib/array/buffer' ); + +var buf1 = new ArrayBuffer( 5 ); +var dv = new DataView( buf1 ); + +var buf2 = dv.buffer; +// returns + +var bool = ( buf1 === buf2 ); +// returns true +``` + +#### DataView.prototype.byteLength + +**Read-only** property which returns the length (in bytes) of the [`DataView`][mdn-dataview]. + + + +```javascript +var ArrayBuffer = require( '@stdlib/array/buffer' ); + +var buf = new ArrayBuffer( 5 ); +var dv = new DataView( buf ); + +var byteLength = dv.byteLength; +// returns 5 +``` + +#### DataView.prototype.byteOffset + +**Read-only** property which returns the number of bytes from the [`DataView`][mdn-dataview] to the start of the underlying array buffer. + + + +```javascript +var ArrayBuffer = require( '@stdlib/array/buffer' ); + +var buf = new ArrayBuffer( 5 ); +var dv = new DataView( buf, 3 ); + +var byteOffset = dv.byteOffset; +// returns 3 +``` + +* * * + +### Methods + +TODO: document methods + +
+ + + +* * * + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var IS_LITTLE_ENDIAN = require( '@stdlib/assert/is-little-endian' ); +var toBinaryString = require( '@stdlib/number/uint8/base/to-binary-string' ); +var randu = require( '@stdlib/random/base/randu' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var ArrayBuffer = require( '@stdlib/array/buffer' ); +var DataView = require( '@stdlib/array/dataview' ); + +// Create a new ArrayBuffer: +var buf = new ArrayBuffer( 64 ); + +// Create a new DataView: +var dv = new DataView( buf ); + +// Set values in the view: +var i; +for ( i = 0; i < dv.byteLength/8; i++ ) { + dv.setFloat64( i*8, randu()*100.0, IS_LITTLE_ENDIAN ); +} + +// Create a "bytes" view of the underlying array buffer: +var bytes = new Uint8Array( dv.buffer ); + +// Print the bytes: +for ( i = 0; i < bytes.length; i++ ) { + console.log( 'byte %d: %s', i, toBinaryString( bytes[ i ] ) ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/dataview/benchmark/benchmark.js b/dataview/benchmark/benchmark.js new file mode 100644 index 00000000..fc889d24 --- /dev/null +++ b/dataview/benchmark/benchmark.js @@ -0,0 +1,60 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var hasDataViewSupport = require( '@stdlib/assert/has-dataview-support' ); +var isDataView = require( '@stdlib/assert/is-dataview' ); +var ArrayBuffer = require( '@stdlib/array/buffer' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// VARIABLES // + +var opts = { + 'skip': !hasDataViewSupport() // TODO: remove once DataView polyfill is written +}; + + +// MAIN // + +bench( pkg, opts, function benchmark( b ) { + var buf; + var dv; + var i; + + buf = new ArrayBuffer( 0 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + dv = new ctor( buf ); + if ( dv.byteLength !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isDataView( dv ) ) { + b.fail( 'should return a DataView' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/dataview/benchmark/benchmark.length.js b/dataview/benchmark/benchmark.length.js new file mode 100644 index 00000000..9889d468 --- /dev/null +++ b/dataview/benchmark/benchmark.length.js @@ -0,0 +1,104 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var hasDataViewSupport = require( '@stdlib/assert/has-dataview-support' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isDataView = require( '@stdlib/assert/is-dataview' ); +var ArrayBuffer = require( '@stdlib/array/buffer' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// VARIABLES // + +var opts = { + 'skip': !hasDataViewSupport() // TODO: remove once DataView polyfill is written +}; + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array buffer length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var buf; + var dv; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf = new ArrayBuffer( len ); + dv = new ctor( buf ); + if ( dv.byteLength !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isDataView( dv ) ) { + b.fail( 'should return a DataView' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':len='+len, opts, f ); + } +} + +main(); diff --git a/dataview/docs/repl.txt b/dataview/docs/repl.txt new file mode 100644 index 00000000..b58339cd --- /dev/null +++ b/dataview/docs/repl.txt @@ -0,0 +1,74 @@ + +{{alias}}( buffer[, byteOffset[, byteLength]] ) + Returns a data view representing a provided array buffer. + + Parameters + ---------- + buffer: ArrayBuffer|SharedArrayBuffer + Array buffer. + + byteOffset: integer (optional) + Offset (in bytes) to the first byte in the array buffer for the new view + to reference. Default: 0. + + byteLength: integer (optional) + Number of elements in the byte array. If not provided, the view's length + will equal the buffer's length. + + Returns + ------- + out: DataView + A data view. + + Examples + -------- + > var buf = new {{alias:@stdlib/array/buffer}}( 5 ) + + > var dv = new {{alias}}( buf ) + + + +{{alias}}.prototype.buffer + Read-only property which returns the underyling array buffer. + + Examples + -------- + > var buf1 = new {{alias:@stdlib/array/buffer}}( 5 ); + > var dv = new {{alias}}( buf1 ); + > var buf2 = dv.buffer + + > var b = ( buf1 === buf2 ) + true + + +{{alias}}.prototype.byteLength + Read-only property which returns the length (in bytes) of the view. + + Examples + -------- + > var buf = new {{alias:@stdlib/array/buffer}}( 5 ); + > var dv = new {{alias}}( buf ); + > dv.byteLength + 5 + + +{{alias}}.prototype.byteOffset + Read-only property which returns the offset (in bytes) of the view to the + start of the underlying array buffer. + + Examples + -------- + > var buf = new {{alias:@stdlib/array/buffer}}( 5 ); + > var dv = new {{alias}}( buf, 2 ); + > dv.byteLength + 3 + > dv.byteOffset + 2 + + +TODO: document properties/methods + + + See Also + -------- + diff --git a/dataview/docs/types/index.d.ts b/dataview/docs/types/index.d.ts new file mode 100644 index 00000000..495672e5 --- /dev/null +++ b/dataview/docs/types/index.d.ts @@ -0,0 +1,26 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +// EXPORTS // + +/** +* Constructor which returns a data view representing a provided array buffer. +*/ +export = DataView; diff --git a/dataview/docs/types/test.ts b/dataview/docs/types/test.ts new file mode 100644 index 00000000..c3c319f0 --- /dev/null +++ b/dataview/docs/types/test.ts @@ -0,0 +1,38 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// tslint:disable: no-construct +// tslint:disable: no-unused-expression + +import ArrayBuffer = require( '@stdlib/array/buffer' ); +import DataView = require( './index' ); + + +// TESTS // + +// The function returns a data view instance... +{ + const buf = new ArrayBuffer( 5 ); + new DataView( buf ); // $ExpectType DataView +} + +// The constructor function has to be invoked with `new`... +{ + const buf = new ArrayBuffer( 5 ); + DataView( buf ); // $ExpectError +} diff --git a/dataview/examples/index.js b/dataview/examples/index.js new file mode 100644 index 00000000..69cd17ed --- /dev/null +++ b/dataview/examples/index.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var proc = require( 'process' ); +var IS_LITTLE_ENDIAN = require( '@stdlib/assert/is-little-endian' ); +var toBinaryString = require( '@stdlib/number/uint8/base/to-binary-string' ); +var hasDataViewSupport = require( '@stdlib/assert/has-dataview-support' ); +var randu = require( '@stdlib/random/base/randu' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var ArrayBuffer = require( '@stdlib/array/buffer' ); +var DataView = require( './../lib' ); + +if ( !hasDataViewSupport() ) { + // TODO: remove once DataView polyfill is written + console.error( 'Environment does not provide DataView support.' ); + proc.exit( 0 ); +} +// Create a new ArrayBuffer: +var buf = new ArrayBuffer( 64 ); + +// Create a new DataView: +var dv = new DataView( buf ); + +// Set values in the view: +var i; +for ( i = 0; i < dv.byteLength/8; i++ ) { + dv.setFloat64( i*8, randu()*100.0, IS_LITTLE_ENDIAN ); +} + +// Create a "bytes" view of the underlying array buffer: +var bytes = new Uint8Array( dv.buffer ); + +// Print the bytes: +for ( i = 0; i < bytes.length; i++ ) { + console.log( 'byte %d: %s', i, toBinaryString( bytes[ i ] ) ); +} diff --git a/dataview/lib/index.js b/dataview/lib/index.js new file mode 100644 index 00000000..134dd9d2 --- /dev/null +++ b/dataview/lib/index.js @@ -0,0 +1,56 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Constructor which returns a data view representing a provided array buffer. +* +* @module @stdlib/array/dataview +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* var DataView = require( '@stdlib/array/dataview' ); +* +* var buf = new ArrayBuffer( 10 ); +* // returns +* +* var dv = new DataView( buf ); +* // returns +*/ + +// MODULES // + +var hasDataViewSupport = require( '@stdlib/assert/has-dataview-support' ); +var builtin = require( './main.js' ); +var polyfill = require( './polyfill.js' ); + + +// MAIN // + +var ctor; +if ( hasDataViewSupport() ) { + ctor = builtin; +} else { + ctor = polyfill; +} + + +// EXPORTS // + +module.exports = ctor; diff --git a/dataview/lib/main.js b/dataview/lib/main.js new file mode 100644 index 00000000..7ab9b219 --- /dev/null +++ b/dataview/lib/main.js @@ -0,0 +1,28 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MAIN // + +var ctor = ( typeof DataView === 'function' ) ? DataView : void 0; // eslint-disable-line stdlib/require-globals + + +// EXPORTS // + +module.exports = ctor; diff --git a/dataview/lib/polyfill.js b/dataview/lib/polyfill.js new file mode 100644 index 00000000..c229902e --- /dev/null +++ b/dataview/lib/polyfill.js @@ -0,0 +1,37 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// TODO: write polyfill + +// MAIN // + +/** +* Constructor which returns a data view representing a provided array buffer. +* +* @throws {Error} not implemented +*/ +function polyfill() { + throw new Error( 'not implemented' ); +} + + +// EXPORTS // + +module.exports = polyfill; diff --git a/dataview/package.json b/dataview/package.json new file mode 100644 index 00000000..8ae35a83 --- /dev/null +++ b/dataview/package.json @@ -0,0 +1,67 @@ +{ + "name": "@stdlib/array/dataview", + "version": "0.0.0", + "description": "DataView.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structure", + "array", + "typed", + "typed array", + "typed-array", + "arraybuffer", + "dataview", + "buffer", + "buf", + "binary" + ] +} diff --git a/dataview/test/test.js b/dataview/test/test.js new file mode 100644 index 00000000..d088f630 --- /dev/null +++ b/dataview/test/test.js @@ -0,0 +1,167 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var hasDataViewSupport = require( '@stdlib/assert/has-dataview-support' ); +var instanceOf = require( '@stdlib/assert/instance-of' ); +var hasOwnProp = require( '@stdlib/assert/has-own-property' ); +var hasProp = require( '@stdlib/assert/has-property' ); +var NODE_VERSION = require( '@stdlib/process/node-version' ); +var ArrayBuffer = require( '@stdlib/array/buffer' ); +var polyfill = require( './../lib/polyfill.js' ); +var Ctor = require( './../lib' ); + + +// VARIABLES // + +var FLG = hasDataViewSupport(); +var opts = { + 'skip': ( NODE_VERSION && NODE_VERSION.slice( 0, 4 ) === '0.10' ) // FIXME: remove once polyfill is written +}; + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof Ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'if an environment supports `DataView`, the export is an alias for `DataView`', function test( t ) { + var Foo = proxyquire( './../lib', { + '@stdlib/assert/has-dataview-support': isTrue, + './main.js': Mock + }); + t.strictEqual( Foo, Mock, 'returns builtin' ); + + if ( FLG ) { + t.strictEqual( Ctor, DataView, 'is alias' ); // eslint-disable-line stdlib/require-globals + } + + t.end(); + + function Mock() { + return this; + } + + function isTrue() { + return true; + } +}); + +tape( 'if an environment does not support `DataView`, the export is a polyfill', function test( t ) { + var Foo = proxyquire( './../lib', { + '@stdlib/assert/has-dataview-support': isFalse + }); + + t.strictEqual( Foo, polyfill, 'returns polyfill' ); + t.end(); + + function isFalse() { + return false; + } +}); + +tape( 'the main export is a constructor', opts, function test( t ) { + var buf; + var dv; + + buf = new ArrayBuffer( 10 ); + + dv = new Ctor( buf ); + t.strictEqual( instanceOf( dv, Ctor ), true, 'returns an instance' ); + + dv = new Ctor( buf, 4 ); + t.strictEqual( instanceOf( dv, Ctor ), true, 'returns an instance' ); + + dv = new Ctor( buf, 4, 2 ); + t.strictEqual( instanceOf( dv, Ctor ), true, 'returns an instance' ); + + t.end(); +}); + +tape( 'the constructor throws an error if not provided an array buffer', opts, function test( t ) { + t.throws( badValue, TypeError, 'throws an error' ); + t.end(); + + function badValue() { + return new Ctor(); + } +}); + +tape( 'the constructor returns a `DataView` instance having a `buffer` property, which returns the underlying an array buffer', opts, function test( t ) { + var buf; + var dv; + + t.strictEqual( hasOwnProp( Ctor.prototype, 'buffer' ), true, 'has prototype property' ); + + buf = new ArrayBuffer( 10 ); + dv = new Ctor( buf ); + t.strictEqual( hasOwnProp( dv, 'buffer' ), false, 'does not have own property' ); + t.strictEqual( hasProp( dv, 'buffer' ), true, 'has property' ); + t.strictEqual( dv.buffer, buf, 'returns expected value' ); + + t.end(); +}); + +tape( 'the constructor returns a `DataView` instance having a `byteLength` property, which returns the number of bytes in a `DataView`', opts, function test( t ) { + var buf; + var dv; + + t.strictEqual( hasOwnProp( Ctor.prototype, 'byteLength' ), true, 'has prototype property' ); + + buf = new ArrayBuffer( 10 ); + + dv = new Ctor( buf ); + t.strictEqual( hasOwnProp( dv, 'byteLength' ), false, 'does not have own property' ); + t.strictEqual( hasProp( dv, 'byteLength' ), true, 'has property' ); + t.strictEqual( dv.byteLength, 10, 'returns expected value' ); + + dv = new Ctor( buf, 4 ); + t.strictEqual( hasOwnProp( dv, 'byteLength' ), false, 'does not have own property' ); + t.strictEqual( hasProp( dv, 'byteLength' ), true, 'has property' ); + t.strictEqual( dv.byteLength, 6, 'returns expected value' ); + + dv = new Ctor( buf, 4, 2 ); + t.strictEqual( hasOwnProp( dv, 'byteLength' ), false, 'does not have own property' ); + t.strictEqual( hasProp( dv, 'byteLength' ), true, 'has property' ); + t.strictEqual( dv.byteLength, 2, 'returns expected value' ); + + t.end(); +}); + +tape( 'the constructor returns a `DataView` instance having a `byteOffset` property, which returns the number of bytes from the view to the start of the underlying an array buffer', opts, function test( t ) { + var buf; + var dv; + + t.strictEqual( hasOwnProp( Ctor.prototype, 'byteOffset' ), true, 'has prototype property' ); + + buf = new ArrayBuffer( 10 ); + dv = new Ctor( buf, 4 ); + t.strictEqual( hasOwnProp( dv, 'byteOffset' ), false, 'does not have own property' ); + t.strictEqual( hasProp( dv, 'byteOffset' ), true, 'has property' ); + t.strictEqual( dv.byteOffset, 4, 'returns expected value' ); + + t.end(); +}); diff --git a/dataview/test/test.polyfill.js b/dataview/test/test.polyfill.js new file mode 100644 index 00000000..6e846573 --- /dev/null +++ b/dataview/test/test.polyfill.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var ctor = require( './../lib/polyfill.js' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error when invoked', function test( t ) { + t.throws( foo, Error, 'throws an error' ); + t.end(); + + function foo() { + var f = new ctor(); // eslint-disable-line no-unused-vars + } +}); + +// TODO: tests diff --git a/datespace/README.md b/datespace/README.md new file mode 100644 index 00000000..f9876459 --- /dev/null +++ b/datespace/README.md @@ -0,0 +1,161 @@ + + +# Datespace + +> Generate an array of linearly spaced [dates][mdn-date-object]. + +
+ +## Usage + +```javascript +var datespace = require( '@stdlib/array/datespace' ); +``` + +#### datespace( start, stop\[, length]\[, opts] ) + +Generates an `array` of linearly spaced [`Date`][mdn-date-object] objects. If a `length` is not provided, the default output `array` length is `100`. + +```javascript +var end = '2014-12-02T07:00:54.973Z'; +var start = new Date( end ) - 60000; + +var arr = datespace( start, end, 6 ); +/* returns [ + 'Mon Dec 01 2014 22:59:54 GMT-0800 (PST)', + 'Mon Dec 01 2014 23:00:06 GMT-0800 (PST)', + 'Mon Dec 01 2014 23:00:18 GMT-0800 (PST)', + 'Mon Dec 01 2014 23:00:30 GMT-0800 (PST)', + 'Mon Dec 01 2014 23:00:42 GMT-0800 (PST)', + 'Mon Dec 01 2014 23:00:54 GMT-0800 (PST)' +] +*/ +``` + +The `start` and `stop` times may be either [`Date`][mdn-date-object] objects, date strings, Unix timestamps, or JavaScript timestamps. + +```javascript +// JavaScript timestamps: +var end = 1417503654973; +var start = new Date( end - 60000 ); + +var arr = datespace( start, end, 6 ); +/* returns [ + 'Mon Dec 01 2014 22:59:54 GMT-0800 (PST)', + 'Mon Dec 01 2014 23:00:06 GMT-0800 (PST)', + 'Mon Dec 01 2014 23:00:18 GMT-0800 (PST)', + 'Mon Dec 01 2014 23:00:30 GMT-0800 (PST)', + 'Mon Dec 01 2014 23:00:42 GMT-0800 (PST)', + 'Mon Dec 01 2014 23:00:54 GMT-0800 (PST)' +] +*/ + +// Unix timestamps: +end = 1417503655; +start = end - 60; + +arr = datespace( start, end, 6 ); +/* returns [ + 'Mon Dec 01 2014 22:59:54 GMT-0800 (PST)', + 'Mon Dec 01 2014 23:00:06 GMT-0800 (PST)', + 'Mon Dec 01 2014 23:00:18 GMT-0800 (PST)', + 'Mon Dec 01 2014 23:00:30 GMT-0800 (PST)', + 'Mon Dec 01 2014 23:00:42 GMT-0800 (PST)', + 'Mon Dec 01 2014 23:00:54 GMT-0800 (PST)' +] +*/ +``` + +The output `array` is guaranteed to include the `start` and `end` times. Beware, however, that values between the `start` and `end` are subject to rounding errors. For example, + +```javascript +var arr = datespace( 1417503655000, 1417503655001, 3 ); +// returns [ 1417503655000, 1417503655000, 1417503655001 ] +``` + +where sub-millisecond values are truncated by the [`Date`][mdn-date-object] constructor. Duplicate values should only be a problem when the interval separating consecutive times is less than a millisecond. As the interval separating consecutive dates goes to infinity, the quantization noise introduced by millisecond resolution is negligible. + +By default, fractional timestamps are floored. To specify that timestamps always be rounded up or to the nearest millisecond **when converted to [`Date`][mdn-date-object] objects**, set the `round` option (default: `floor`). + +```javascript +// Equivalent of Math.ceil(): +var arr = datespace( 1417503655000, 1417503655001, 3, { + 'round': 'ceil' +}); +// returns [ 1417503655000, 1417503655001, 1417503655001 ] + +// Equivalent of Math.round(): +arr = datespace( 1417503655000, 1417503655001, 3, { + 'round': 'round' +}); +// returns [ 1417503655000, 1417503655001, 1417503655001 ] +``` + +
+ + + +
+ +
+ + + +
+ +## Examples + +```javascript +var datespace = require( '@stdlib/array/datespace' ); +var start; +var arr; +var end; + +end = '2014-12-02T07:00:54.973Z'; +start = new Date( end ) - 100000; + +// Default behavior: +arr = datespace( start, end ); +console.log( arr.join( '\n' ) ); + +// Specify length: +arr = datespace( start, end, 10 ); +console.log( arr.join( '\n' ) ); + +arr = datespace( start, end, 11 ); +console.log( arr.join( '\n' ) ); + +// Create an array with decremented values: +arr = datespace( end, start, 11 ); +console.log( arr.join( '\n' ) ); +``` + +
+ + + + + + diff --git a/datespace/benchmark/benchmark.js b/datespace/benchmark/benchmark.js new file mode 100644 index 00000000..ece0779c --- /dev/null +++ b/datespace/benchmark/benchmark.js @@ -0,0 +1,54 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var randu = require( '@stdlib/random/base/randu' ); +var round = require( '@stdlib/math/base/special/round' ); +var isArray = require( '@stdlib/assert/is-array' ); +var pkg = require( './../package.json' ).name; +var datespace = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var start; + var end; + var i; + var v; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + end = '2014-12-02T07:00:54.973Z'; + start = new Date( end ) - round( randu()*100.0 ); + v = datespace( start, end ); + if ( typeof v !== 'object' ) { + b.fail( 'should return an array' ); + } + } + b.toc(); + if ( !isArray( v ) ) { + b.fail( 'should return an array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/datespace/benchmark/benchmark.length.js b/datespace/benchmark/benchmark.length.js new file mode 100644 index 00000000..22612f40 --- /dev/null +++ b/datespace/benchmark/benchmark.length.js @@ -0,0 +1,99 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randu = require( '@stdlib/random/base/randu' ); +var round = require( '@stdlib/math/base/special/round' ); +var isArray = require( '@stdlib/assert/is-array' ); +var pkg = require( './../package.json' ).name; +var datespace = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var start; + var end; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + end = '2014-12-02T07:00:54.973Z'; + start = new Date( end ) - round( randu()*100.0 ); + v = datespace( start, end, len ); + if ( typeof v !== 'object' ) { + b.fail( 'should return an array' ); + } + } + b.toc(); + if ( !isArray( v ) ) { + b.fail( 'should return an array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':len='+len, f ); + } +} + +main(); diff --git a/datespace/docs/repl.txt b/datespace/docs/repl.txt new file mode 100644 index 00000000..187bce84 --- /dev/null +++ b/datespace/docs/repl.txt @@ -0,0 +1,44 @@ + +{{alias}}( start, stop[, length][ , options] ) + Generates an array of linearly spaced dates. + + Parameters + ---------- + start: number + Start time as either a `Date` object, Unix timestamp, JavaScript + timestamp, or date string. + + stop: number + Stop time as either a `Date` object, Unix timestamp, JavaScript + timestamp, or date string. + + length: integer (optional) + Length of output array. Default: `100`. + + options: Object (optional) + Options. + + options.round: string (optional) + Specifies how sub-millisecond times should be rounded: + [ 'floor', 'ceil', 'round' ]. Default: 'floor'. + + Returns + ------- + arr: Array + Array of dates. + + Examples + -------- + > var stop = '2014-12-02T07:00:54.973Z'; + > var start = new Date( stop ) - 60000; + > var arr = {{alias}}( start, stop, 6 ) + [...] + + // Equivalent of Math.ceil(): + > var opts = { 'round': 'ceil' }; + > arr = {{alias}}( 1417503655000, 1417503655001, 3, opts ) + [...] + + See Also + -------- + diff --git a/datespace/docs/types/index.d.ts b/datespace/docs/types/index.d.ts new file mode 100644 index 00000000..e78af11f --- /dev/null +++ b/datespace/docs/types/index.d.ts @@ -0,0 +1,92 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/** +* Interface defining function options. +*/ +interface Options { + /** + * Specifies how sub-millisecond times should be rounded (default: 'floor' ). + */ + round?: 'floor' | 'round' | 'ceil'; +} + +/** +* Generates an array of linearly spaced dates. +* +* @param start - start time as either a `Date` object, Unix timestamp, JavaScript timestamp, or date string +* @param stop - stop time as either a `Date` object, Unix timestamp, JavaScript timestamp, or date string +* @param options - function options +* @param options.round - specifies how sub-millisecond times should be rounded: [ 'floor', 'ceil', 'round' ] (default: 'floor' ) +* @throws must provide valid options +* @returns array of dates +* +* @example +* var stop = '2014-12-02T07:00:54.973Z'; +* var start = new Date( stop ) - 60000; +* +* var arr = datespace( start, stop, 6 ); +* // returns [...] +* +* @example +* // Equivalent of Math.ceil(): +* var arr = datespace( 1417503655000, 1417503655001, 3, { 'round': 'ceil' } ); +* // returns [...] +* +* // Equivalent of Math.round(): +* var arr = datespace( 1417503655000, 1417503655001, 3, { 'round': 'round' } ); +* // returns [...] +*/ +declare function datespace( start: Date | number | string, stop: Date | number | string, options?: Options ): Array; // tslint-disable-line max-line-length + +/** +* Generates an array of linearly spaced dates. +* +* @param start - start time as either a `Date` object, Unix timestamp, JavaScript timestamp, or date string +* @param stop - stop time as either a `Date` object, Unix timestamp, JavaScript timestamp, or date string +* @param length - output array length (default: 100) +* @param options - function options +* @param options.round - specifies how sub-millisecond times should be rounded: [ 'floor', 'ceil', 'round' ] (default: 'floor' ) +* @throws length argument must a positive integer +* @throws must provide valid options +* @returns array of dates +* +* @example +* var stop = '2014-12-02T07:00:54.973Z'; +* var start = new Date( stop ) - 60000; +* +* var arr = datespace( start, stop, 6 ); +* // returns [...] +* +* @example +* // Equivalent of Math.ceil(): +* var arr = datespace( 1417503655000, 1417503655001, 3, { 'round': 'ceil' } ); +* // returns [...] +* +* // Equivalent of Math.round(): +* var arr = datespace( 1417503655000, 1417503655001, 3, { 'round': 'round' } ); +* // returns [...] +*/ +declare function datespace( start: Date | number | string, stop: Date | number | string, length: number, options?: Options ): Array; // tslint-disable-line max-line-length + + +// EXPORTS // + +export = datespace; diff --git a/datespace/docs/types/test.ts b/datespace/docs/types/test.ts new file mode 100644 index 00000000..2370b9c3 --- /dev/null +++ b/datespace/docs/types/test.ts @@ -0,0 +1,86 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import datespace = require( './index' ); + + +// TESTS // + +// The function returns an array of dates... +{ + const stop = '2014-12-02T07:00:54.973Z'; + const start = new Date( stop ).getTime() - 60000; + datespace( start, stop ); // $ExpectType Date[] + datespace( start, stop, 30 ); // $ExpectType Date[] + datespace( start, stop, { 'round': 'floor' } ); // $ExpectType Date[] + datespace( start, stop, 30, { 'round': 'floor' } ); // $ExpectType Date[] +} + +// The function does not compile if provided values other `Date` objects, Unix timestamps, JavaScript timestamps, or date strings for the first two parameters... +{ + const stop = '2014-12-02T07:00:54.973Z'; + const start = new Date( stop ).getTime() - 60000; + datespace( true, stop ); // $ExpectError + datespace( false, stop ); // $ExpectError + datespace( null, stop ); // $ExpectError + datespace( [], stop ); // $ExpectError + datespace( {}, stop ); // $ExpectError + datespace( ( x: number ): number => x, stop ); // $ExpectError + + datespace( start, true ); // $ExpectError + datespace( start, false ); // $ExpectError + datespace( start, [] ); // $ExpectError + datespace( start, {} ); // $ExpectError + datespace( start, ( x: number ): number => x ); // $ExpectError +} + +// The function does not compile if provided a value other than a number or object for the third parameter... +{ + const stop = '2014-12-02T07:00:54.973Z'; + const start = new Date( stop ).getTime() - 60000; + datespace( start, stop, true ); // $ExpectError + datespace( start, stop, false ); // $ExpectError + datespace( start, stop, '5' ); // $ExpectError + datespace( start, stop, [] ); // $ExpectError + datespace( start, stop, ( x: number ): number => x ); // $ExpectError +} + +// The compiler throws an error if the function is provided a `round` option which is not a recognized rounding procedure... +{ + const stop = '2014-12-02T07:00:54.973Z'; + const start = new Date( stop ).getTime() - 60000; + datespace( start, stop, { 'round': 'abc' } ); // $ExpectError + datespace( start, stop, { 'round': 123 } ); // $ExpectError + datespace( start, stop, { 'round': null } ); // $ExpectError + datespace( start, stop, { 'round': [] } ); // $ExpectError + datespace( start, stop, { 'round': {} } ); // $ExpectError + datespace( start, stop, { 'round': ( x: number ): number => x } ); // $ExpectError + + datespace( start, stop, 10, { 'round': 'abc' } ); // $ExpectError + datespace( start, stop, 10, { 'round': 123 } ); // $ExpectError + datespace( start, stop, 10, { 'round': null } ); // $ExpectError + datespace( start, stop, 10, { 'round': [] } ); // $ExpectError + datespace( start, stop, 10, { 'round': {} } ); // $ExpectError + datespace( start, stop, 10, { 'round': ( x: number ): number => x } ); // $ExpectError +} + +// The function does not compile if provided insufficient arguments... +{ + datespace(); // $ExpectError + datespace( new Date() ); // $ExpectError +} diff --git a/datespace/examples/index.js b/datespace/examples/index.js new file mode 100644 index 00000000..16a947a0 --- /dev/null +++ b/datespace/examples/index.js @@ -0,0 +1,46 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var datespace = require( './../lib' ); +var start; +var arr; +var end; + +end = '2014-12-02T07:00:54.973Z'; +start = new Date( end ) - 100000; + +// Default behavior: +console.log( '\nDefault:' ); +arr = datespace( start, end ); +console.log( arr.join( '\n' ) ); + +// Specify length: +console.log( '\nLength 10:' ); +arr = datespace( start, end, 10 ); +console.log( arr.join( '\n' ) ); + +console.log( '\nLength 11:' ); +arr = datespace( start, end, 11 ); +console.log( arr.join( '\n' ) ); + +// Create an array with decremented values: +console.log( '\nDecremented values:' ); +arr = datespace( end, start, 11 ); +console.log( arr.join( '\n' ) ); diff --git a/datespace/lib/index.js b/datespace/lib/index.js new file mode 100644 index 00000000..8ab74dcf --- /dev/null +++ b/datespace/lib/index.js @@ -0,0 +1,43 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Generate an array of linearly spaced dates. +* +* @module @stdlib/array/datespace +* +* @example +* var datespace = require( '@stdlib/array/datespace' ); +* +* var stop = '2014-12-02T07:00:54.973Z'; +* var start = new Date( stop ) - 60000; +* +* var arr = datespace( start, stop, 6 ); +* // returns [...] +*/ + +// MODULES // + +var datespace = require( './main.js' ); + + +// EXPORTS // + +module.exports = datespace; diff --git a/datespace/lib/main.js b/datespace/lib/main.js new file mode 100644 index 00000000..fd2e2a8a --- /dev/null +++ b/datespace/lib/main.js @@ -0,0 +1,192 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var hasOwnProp = require( '@stdlib/assert/has-own-property' ); +var isInteger = require( '@stdlib/assert/is-integer' ); +var isString = require( '@stdlib/assert/is-string' ).isPrimitive; +var isObject = require( '@stdlib/assert/is-object' ); +var floor = require( '@stdlib/math/base/special/floor' ); +var round = require( '@stdlib/math/base/special/round' ); +var ceil = require( '@stdlib/math/base/special/ceil' ); + + +// VARIABLES // + +var timestamp = /^\d{10}$|^\d{13}$/; +var rounders = [ 'floor', 'ceil', 'round' ]; + + +// FUNCTIONS // + +/** +* Validates a date parameter. +* +* @private +* @param {*} value - value to be validated +* @param {string} name - name to be used in error messages +* @throws {TypeError} value must either be a date string, Date object, Unix timestamp, or JavaScript timestamp +* @throws {Error} numeric date must be either a Unix or Javascript timestamp +* @returns {Date} validated date +*/ +function validDate( value, name ) { + var type; + + type = typeof value; + if ( type === 'string' ) { + value = Date.parse( value ); + if ( value !== value ) { + throw new Error( 'invalid argument. Unable to parse ' + name.toLowerCase() + ' date.' ); + } + value = new Date( value ); + } + if ( type === 'number' ) { + if ( !timestamp.test( value ) ) { + throw new Error( 'invalid argument. Numeric ' + name.toLowerCase() + ' date must be either a Unix or Javascript timestamp.' ); + } + if ( value.toString().length === 10 ) { + value *= 1000; // sec to ms + } + value = new Date( value ); + } + if ( !(value instanceof Date) ) { + throw new TypeError( 'invalid argument. ' + name + ' date must either be a date string, Date object, Unix timestamp, or JavaScript timestamp.' ); + } + return value; +} + + +// MAIN // + +/** +* Generates an array of linearly spaced dates. +* +* @param {(Date|number|string)} start - start time as either a `Date` object, Unix timestamp, JavaScript timestamp, or date string +* @param {(Date|number|string)} stop - stop time as either a `Date` object, Unix timestamp, JavaScript timestamp, or date string +* @param {number} [length] - output array length (default: 100) +* @param {Object} [options] - function options +* @param {string} [options.round] - specifies how sub-millisecond times should be rounded: [ 'floor', 'ceil', 'round' ] (default: 'floor' ) +* @throws {TypeError} length argument must a positive integer +* @throws {Error} must provide valid options +* @returns {Array} array of dates +* +* @example +* var stop = '2014-12-02T07:00:54.973Z'; +* var start = new Date( stop ) - 60000; +* +* var arr = datespace( start, stop, 6 ); +* // returns [...] +* +* @example +* // Equivalent of Math.ceil(): +* var arr = datespace( 1417503655000, 1417503655001, 3, { 'round': 'ceil' } ); +* // returns [...] +* +* // Equivalent of Math.round(): +* arr = datespace( 1417503655000, 1417503655001, 3, { 'round': 'round' } ); +* // returns [...] +*/ +function datespace( start, stop, length, options ) { + var opts; + var len; + var flg; + var arr; + var end; + var fcn; + var tmp; + var d; + var i; + + len = 100; + flg = true; + opts = { + 'round': 'floor' + }; + start = validDate( start, 'Start' ); + stop = validDate( stop, 'Stop' ); + if ( arguments.length > 2 ) { + if ( arguments.length === 3 ) { + if ( isObject( length ) ) { + opts = length; + } else { + len = length; + + // Turn off checking the options object... + flg = false; + } + } else { + opts = options; + len = length; + } + if ( len === 0 ) { + return []; + } + if ( !isInteger( len ) || len < 0 ) { + throw new TypeError( 'invalid argument. Length must a positive integer.' ); + } + if ( flg ) { + if ( !isObject( opts ) ) { + throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + opts + '`.' ); + } + if ( hasOwnProp( opts, 'round' ) ) { + if ( !isString( opts.round ) ) { + throw new TypeError( 'invalid option. `round` option must be a string.' ); + } + if ( rounders.indexOf( opts.round ) === -1 ) { + throw new Error( 'invalid input option. `round` option must be one of [' + rounders.join( ',' ) + '].' ); + } + } + } + } + switch ( opts.round ) { + case 'round': + fcn = round; + break; + case 'ceil': + fcn = ceil; + break; + default: + case 'floor': + fcn = floor; + break; + } + + // Calculate the increment... + end = len - 1; + d = ( stop.getTime() - start.getTime() ) / end; + + // Build the output array... + arr = new Array( len ); + tmp = start; + arr[ 0 ] = tmp; + tmp = tmp.getTime(); + for ( i = 1; i < end; i++ ) { + tmp += d; + arr[ i ] = new Date( fcn( tmp ) ); + } + arr[ end ] = stop; + return arr; +} + + +// EXPORTS // + +module.exports = datespace; diff --git a/datespace/package.json b/datespace/package.json new file mode 100644 index 00000000..1f70635f --- /dev/null +++ b/datespace/package.json @@ -0,0 +1,63 @@ +{ + "name": "@stdlib/array/datespace", + "version": "0.0.0", + "description": "Generate an array of linearly spaced dates.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdmath", + "utilities", + "utils", + "mathematics", + "math", + "generic", + "array", + "matlab", + "linear", + "date" + ] +} diff --git a/datespace/test/test.js b/datespace/test/test.js new file mode 100644 index 00000000..81b5b0d3 --- /dev/null +++ b/datespace/test/test.js @@ -0,0 +1,445 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var isArray = require( '@stdlib/assert/is-array' ); +var floor = require( '@stdlib/math/base/special/floor' ); +var datespace = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.equal( typeof datespace, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error if not provided a valid start date', function test( t ) { + var values; + var stop; + var i; + + stop = new Date(); + + values = [ + 'beep', + 5, + -5, + true, + NaN, + null, + void 0, + [], + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), Error, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + datespace( value, stop ); + }; + } +}); + +tape( 'the function throws an error if not provided a valid stop date', function test( t ) { + var values; + var start; + var i; + + start = new Date().getTime(); + + values = [ + 'beep', + 5, + -5, + true, + NaN, + null, + void 0, + [], + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), Error, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + datespace( start, value ); + }; + } +}); + +tape( 'the function throws an error if provided an invalid length', function test( t ) { + var values; + var start; + var stop; + var i; + + start = new Date().getTime(); + stop = new Date(); + + values = [ + 'beep', + 3.14, + -5, + true, + NaN, + null, + void 0, + [], + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue1( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + t.throws( badValue2( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue1( value ) { + return function badValue1() { + datespace( start, stop, value ); + }; + } + function badValue2( value ) { + return function badValue2() { + datespace( start, stop, value, {} ); + }; + } +}); + +tape( 'the function throws an error if provided a non-object for options', function test( t ) { + var values; + var start; + var stop; + var i; + + start = new Date().getTime(); + stop = new Date(); + + values = [ + 'beep', + 5, + true, + NaN, + null, + void 0, + [], + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + datespace( start, stop, 10, value ); + }; + } +}); + +tape( 'the function throws an error if provided an invalid round option', function test( t ) { + var values; + var start; + var stop; + var i; + + start = new Date().getTime(); + stop = new Date(); + + values = [ + 'beep', + 5, + true, + NaN, + null, + void 0, + [], + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), Error, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + datespace( start, stop, 10, { + 'round': value + }); + }; + } +}); + +tape( 'the function returns an empty array if provided a length of 0', function test( t ) { + var actual; + var start; + var stop; + + start = new Date().getTime(); + stop = new Date(); + actual = datespace( start, stop, 0 ); + + t.deepEqual( actual, [] ); + t.end(); +}); + +tape( 'the function returns an array of `Date` objects', function test( t ) { + var actual; + var start; + var stop; + var i; + + stop = '2014-12-02T07:00:55.973Z'; + start = new Date( stop ) - 5000; + + actual = datespace( start, stop ); + + t.strictEqual( isArray( actual ), true, 'returns an array' ); + for ( i = 0; i < actual.length; i++ ) { + t.ok( actual[i] instanceof Date, 'returns a date' ); + } + t.end(); +}); + +tape( 'the function supplies a default length', function test( t ) { + var actual; + var start; + var stop; + + stop = '2014-12-02T07:00:55.973Z'; + start = new Date( stop ) - 5000; + + actual = datespace( start, stop, { + 'round': 'floor' + }); + + t.ok( actual.length ); + t.ok( actual[0] < actual[1] ); + t.end(); +}); + +tape( 'the function outputs both incremental and decremental arrays', function test( t ) { + var actual; + var start; + var stop; + + stop = '2014-12-02T07:00:55.973Z'; + start = new Date( stop ) - 5000; + + // Incremental: + actual = datespace( start, stop, { + 'round': 'floor' + }); + + t.ok( actual[0] < actual[1] ); + + // Decremental: + actual = datespace( stop, start, { + 'round': 'round' + }); + + t.ok( actual[0] > actual[1] ); + t.end(); +}); + +tape( 'the function creates a linearly spaced array of dates', function test( t ) { + var expected; + var actual; + var start; + var stop; + var i; + + stop = '2014-12-02T07:00:55.973Z'; + start = new Date( stop ) - 5000; + + actual = datespace( start, stop, 6 ); + + for ( i = 0; i < actual.length; i++ ) { + actual[ i ] = actual[ i ].getTime(); + } + + expected = [ + 1417503650973, + 1417503651973, + 1417503652973, + 1417503653973, + 1417503654973, + 1417503655973 + ]; + + t.deepEqual( actual, expected ); + t.end(); +}); + +tape( 'the function accepts Unix timestamps', function test( t ) { + var expected; + var actual; + var start; + var stop; + var i; + + stop = '2014-12-02T07:00:55.973Z'; + stop = new Date( stop ).getTime(); + stop = floor( stop / 1000 ); + start = stop - 5; + + actual = datespace( start, stop, 6 ); + + for ( i = 0; i < actual.length; i++ ) { + actual[ i ] = actual[ i ].getTime(); + } + + expected = [ + 1417503650000, + 1417503651000, + 1417503652000, + 1417503653000, + 1417503654000, + 1417503655000 + ]; + + t.deepEqual( actual, expected ); + t.end(); +}); + +tape( 'the function ceils date values', function test( t ) { + var expected; + var actual; + var start; + var stop; + var i; + + stop = '2014-12-02T07:00:55.973Z'; + start = new Date( stop ) - 5; + + actual = datespace( start, stop, 11, { + 'round': 'ceil' + }); + + for ( i = 0; i < actual.length; i++ ) { + actual[ i ] = actual[ i ].getTime(); + } + + expected = [ + 1417503655968, + 1417503655969, + 1417503655969, + 1417503655970, + 1417503655970, + 1417503655971, + 1417503655971, + 1417503655972, + 1417503655972, + 1417503655973, + 1417503655973 + ]; + + t.deepEqual( actual, expected ); + t.end(); +}); + +tape( 'the function floors date values', function test( t ) { + var expected; + var actual; + var start; + var stop; + var i; + + stop = '2014-12-02T07:00:55.973Z'; + start = new Date( stop ) - 5; + + actual = datespace( start, stop, 11, { + 'round': 'floor' + }); + + for ( i = 0; i < actual.length; i++ ) { + actual[ i ] = actual[ i ].getTime(); + } + + expected = [ + 1417503655968, + 1417503655968, + 1417503655969, + 1417503655969, + 1417503655970, + 1417503655970, + 1417503655971, + 1417503655971, + 1417503655972, + 1417503655972, + 1417503655973 + ]; + + t.deepEqual( actual, expected ); + t.end(); +}); + +tape( 'the function rounds date values', function test( t ) { + var expected; + var actual; + var start; + var stop; + var i; + + stop = '2014-12-02T07:00:55.973Z'; + start = new Date( stop ) - 5; + + actual = datespace( start, stop, 11, { + 'round': 'round' + }); + + for ( i = 0; i < actual.length; i++ ) { + actual[ i ] = actual[ i ].getTime(); + } + + expected = [ + 1417503655968, + 1417503655969, + 1417503655969, + 1417503655970, + 1417503655970, + 1417503655971, + 1417503655971, + 1417503655972, + 1417503655972, + 1417503655973, + 1417503655973 + ]; + + t.deepEqual( actual, expected ); + t.end(); +}); diff --git a/docs/types/index.d.ts b/docs/types/index.d.ts new file mode 100644 index 00000000..b007b962 --- /dev/null +++ b/docs/types/index.d.ts @@ -0,0 +1,884 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/* tslint:disable:max-line-length */ +/* tslint:disable:max-file-line-count */ + +import ArrayBuffer = require( '@stdlib/array/buffer' ); +import Complex64Array = require( '@stdlib/array/complex64' ); +import Complex128Array = require( '@stdlib/array/complex128' ); +import convertArray = require( '@stdlib/array/convert' ); +import convertArraySame = require( '@stdlib/array/convert-same' ); +import arrayCtors = require( '@stdlib/array/ctors' ); +import DataView = require( '@stdlib/array/dataview' ); +import arrayDataType = require( '@stdlib/array/dtype' ); +import arrayDataTypes = require( '@stdlib/array/dtypes' ); +import filledarray = require( '@stdlib/array/filled' ); +import Float32Array = require( '@stdlib/array/float32' ); +import Float64Array = require( '@stdlib/array/float64' ); +import iterator2array = require( '@stdlib/array/from-iterator' ); +import Int8Array = require( '@stdlib/array/int8' ); +import Int16Array = require( '@stdlib/array/int16' ); +import Int32Array = require( '@stdlib/array/int32' ); +import arrayMinDataType = require( '@stdlib/array/min-dtype' ); +import arrayNextDataType = require( '@stdlib/array/next-dtype' ); +import typedarraypool = require( '@stdlib/array/pool' ); +import arrayPromotionRules = require( '@stdlib/array/promotion-rules' ); +import reviveTypedArray = require( '@stdlib/array/reviver' ); +import arraySafeCasts = require( '@stdlib/array/safe-casts' ); +import arraySameKindCasts = require( '@stdlib/array/same-kind-casts' ); +import arrayShape = require( '@stdlib/array/shape' ); +import SharedArrayBuffer = require( '@stdlib/array/shared-buffer' ); +import circarray2iterator = require( '@stdlib/array/to-circular-iterator' ); +import array2iterator = require( '@stdlib/array/to-iterator' ); +import array2iteratorRight = require( '@stdlib/array/to-iterator-right' ); +import typedarray2json = require( '@stdlib/array/to-json' ); +import sparsearray2iterator = require( '@stdlib/array/to-sparse-iterator' ); +import sparsearray2iteratorRight = require( '@stdlib/array/to-sparse-iterator-right' ); +import stridedarray2iterator = require( '@stdlib/array/to-strided-iterator' ); +import arrayview2iterator = require( '@stdlib/array/to-view-iterator' ); +import arrayview2iteratorRight = require( '@stdlib/array/to-view-iterator-right' ); +import typedarray = require( '@stdlib/array/typed' ); +import typedarrayComplexCtors = require( '@stdlib/array/typed-complex-ctors' ); +import typedarrayComplexDataTypes = require( '@stdlib/array/typed-complex-dtypes' ); +import typedarrayCtors = require( '@stdlib/array/typed-ctors' ); +import typedarrayDataTypes = require( '@stdlib/array/typed-dtypes' ); +import Uint8Array = require( '@stdlib/array/uint8' ); +import Uint8ClampedArray = require( '@stdlib/array/uint8c' ); +import Uint16Array = require( '@stdlib/array/uint16' ); +import Uint32Array = require( '@stdlib/array/uint32' ); +import constants = require( '@stdlib/constants/array' ); + +/** +* Interface describing the `array` namespace. +*/ +interface Namespace { + /** + * Constructor which returns an object used to represent a generic, fixed-length raw binary data buffer. + */ + ArrayBuffer: typeof ArrayBuffer; + + /** + * 64-bit complex number array constructor. + * + * @param arg - length, typed array, array-like object, or buffer + * @param byteOffset - byte offset (default: 0) + * @param length - view length + * @throws ArrayBuffer byte length must be a multiple of `8` + * @throws array-like object and typed array input arguments must have a length which is a multiple of two + * @throws if provided only a single argument, must provide a valid argument + * @throws byte offset must be a nonnegative integer + * @throws byte offset must be a multiple of `8` + * @throws view length must be a positive multiple of `8` + * @throws must provide sufficient memory to accommodate byte offset and view length requirements + * @throws an iterator must return either a two element array containing real and imaginary components or a complex number + * @returns complex number array + * + * @example + * var arr = new ns.Complex64Array(); + * // returns + * + * var len = arr.length; + * // returns 0 + * + * @example + * var arr = new ns.Complex64Array( 2 ); + * // returns + * + * var len = arr.length; + * // returns 2 + * + * @example + * var arr = new ns.Complex64Array( [ 1.0, -1.0 ] ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 16 ); + * var arr = new ns.Complex64Array( buf ); + * // returns + * + * var len = arr.length; + * // returns 2 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 16 ); + * var arr = new ns.Complex64Array( buf, 8 ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 32 ); + * var arr = new ns.Complex64Array( buf, 8, 2 ); + * // returns + * + * var len = arr.length; + * // returns 2 + */ + Complex64Array: typeof Complex64Array; + + /** + * 128-bit complex number array constructor. + * + * @param arg - length, typed array, array-like object, or buffer + * @param byteOffset - byte offset (default: 0) + * @param length - view length + * @throws ArrayBuffer byte length must be a multiple of `8` + * @throws array-like object and typed array input arguments must have a length which is a multiple of two + * @throws if provided only a single argument, must provide a valid argument + * @throws byte offset must be a nonnegative integer + * @throws byte offset must be a multiple of `8` + * @throws view length must be a positive multiple of `8` + * @throws must provide sufficient memory to accommodate byte offset and view length requirements + * @throws an iterator must return either a two element array containing real and imaginary components or a complex number + * @returns complex number array + * + * @example + * var arr = new ns.Complex128Array(); + * // returns + * + * var len = arr.length; + * // returns 0 + * + * @example + * var arr = new ns.Complex128Array( 2 ); + * // returns + * + * var len = arr.length; + * // returns 2 + * + * @example + * var arr = new ns.Complex128Array( [ 1.0, -1.0 ] ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 16 ); + * var arr = new ns.Complex128Array( buf ); + * // returns + * + * var len = arr.length; + * // returns 2 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 16 ); + * var arr = new ns.Complex128Array( buf, 8 ); + * // returns + * + * var len = arr.length; + * // returns 1 + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 32 ); + * var arr = new ns.Complex128Array( buf, 8, 2 ); + * // returns + * + * var len = arr.length; + * // returns 2 + */ + Complex128Array: typeof Complex128Array; + + /** + * Converts an array to an array of a different data type. + * + * @param x - array to convert + * @param dtype - output data type + * @returns output array + * + * @example + * var arr = [ 1.0, 2.0, 3.0, 4.0 ]; + * var out = ns.convertArray( arr, 'float64' ); + * // returns [ 1.0, 2.0, 3.0, 4.0 ] + */ + convertArray: typeof convertArray; + + /** + * Converts an array to the same data type as a second input array. + * + * @param x - array to convert + * @param y - array having the desired output data type + * @returns output array + * + * @example + * var Float64Array = require( `@stdlib/array/float64` ); + * + * var y = new Float64Array( 0 ); + * + * var x = [ 1.0, 2.0, 3.0, 4.0 ]; + * var out = ns.convertArraySame( x, y ); + * // returns [ 1.0, 2.0, 3.0, 4.0 ] + */ + convertArraySame: typeof convertArraySame; + + /** + * Returns an array constructor. + * + * @param dtype - data type + * @returns constructor or null + * + * @example + * var ctor = ns.arrayCtors( 'float64' ); + * // returns + * + * @example + * var ctor = ns.arrayCtors( 'float' ); + * // returns null + */ + arrayCtors: typeof arrayCtors; + + /** + * Constructor which returns a data view representing a provided array buffer. + */ + DataView: typeof DataView; + + /** + * Returns the data type of an array. + * + * ## Notes + * + * - If provided an argument having an unknown or unsupported type, the function returns `null`. + * + * @param value - input value + * @returns data type + * + * @example + * var dt = ns.arrayDataType( [ 1, 2, 3 ] ); + * // returns 'generic' + * + * var dt = ns.arrayDataType( 'beep' ); + * // returns null + */ + arrayDataType: typeof arrayDataType; + + /** + * Returns a list of array data types. + * + * @returns list of array data types + * + * @example + * var list = ns.arrayDataTypes(); + * // returns [ 'float32', 'float64', 'generic', 'int16', 'int32', 'int8', 'uint16', 'uint32', 'uint8', 'uint8c' ] + */ + arrayDataTypes: typeof arrayDataTypes; + + /** + * Returns a filled typed array view of an `ArrayBuffer`. + * + * ## Notes + * + * - Creating a generic array from an `ArrayBuffer` is **not** supported. + * + * @param value - fill value + * @param buffer - `ArrayBuffer` + * @param dtype - data type (default: 'float64') + * @throws must provide a recognized data type + * @returns filled array + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 32 ); + * var arr = ns.filledarray( 1.0, buf ); + * // returns [ 1.0, 1.0, 1.0, 1.0 ] + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 32 ); + * var arr = ns.filledarray( 1.0, buf, 'float32' ); + * // returns [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ] + * + */ + filledarray: typeof filledarray; + + /** + * Typed array constructor which returns a typed array representing an array of single-precision floating-point numbers in the platform byte order. + */ + Float32Array: typeof Float32Array; + + /** + * Typed array constructor which returns a typed array representing an array of double-precision floating-point numbers in the platform byte order. + */ + Float64Array: typeof Float64Array; + + /** + * Creates (or fills) an array from an iterator. + * + * @param iterator - source iterator + * @param out - output array + * @param mapFcn - function to invoke for each iterated value + * @param thisArg - execution context + * @returns output array + * + * @example + * var Float64Array = require( `@stdlib/array/float64` ); + * var randu = require( `@stdlib/random/iter/randu` ); + * + * var iter = randu({ + * 'iter': 10 + * }); + * + * var out = new Float64Array( 10 ); + * var arr = ns.iterator2array( iter, out ); + * // returns + */ + iterator2array: typeof iterator2array; + + /** + * Typed array constructor which returns a typed array representing an array of twos-complement 8-bit signed integers in the platform byte order. + */ + Int8Array: typeof Int8Array; + + /** + * Typed array constructor which returns a typed array representing an array of twos-complement 16-bit signed integers in the platform byte order. + */ + Int16Array: typeof Int16Array; + + /** + * Typed array constructor which returns a typed array representing an array of twos-complement 32-bit signed integers in the platform byte order. + */ + Int32Array: typeof Int32Array; + + /** + * Returns the minimum array data type of the closest "kind" necessary for storing a provided scalar value. + * + * ## Notes + * + * - The function does *not* provide precision guarantees for non-integer-valued real numbers. In other words, the function returns the smallest possible floating-point (i.e., inexact) data type for storing numbers having decimals. + * + * @param value - scalar value + * @returns array data type + * + * @example + * var dt = ns.arrayMinDataType( 3.141592653589793 ); + * // returns 'float32' + * + * @example + * var dt = ns.arrayMinDataType( 3 ); + * // returns 'uint8' + */ + arrayMinDataType: typeof arrayMinDataType; + + /** + * Returns the next larger array data type of the same kind. + * + * ## Notes + * + * - If not provided a data type, the function returns a table. + * - If a data type does not have a next larger data type or the next larger type is not supported, the function returns `-1`. + * - If provided an unrecognized data type, the function returns `null`. + * + * @param dtype - array data type + * @returns next larger data type(s) or null + * + * @example + * var dt = ns.arrayNextDataType( 'float32' ); + * // returns 'float64' + */ + arrayNextDataType: typeof arrayNextDataType; + + /** + * Returns an uninitialized typed array. + * + * ## Notes + * + * - Memory is **not** initialized. + * - Memory is lazily allocated. + * - If the function returns `null`, the function was unable to allocate a new typed array from the typed array pool (most likely due to insufficient memory). + * + * @param arg - an array length or an array-like object + * @param dtype - data type (default: 'float64') + * @returns typed array or null + * + * @example + * // Allocate an array of doubles: + * var arr = ns.typedarraypool( 5, 'float64' ); + * // e.g., returns [ 0.0, 0.0, 0.0, 0.0, 0.0 ] + * + * arr[ 0 ] = 3.14; + * arr[ 1 ] = 3.14; + * + * // ... + * + * // Free the allocated memory to be used in a future allocation: + * ns.typedarraypool.free( arr ); + */ + typedarraypool: typeof typedarraypool; + + /** + * Returns a type promotion table displaying array data types with the smallest size and closest "kind" to which array data types can be safely cast. + * + * @returns promotion rule table + * + * @example + * var table = ns.arrayPromotionRules(); + * // returns {...} + */ + arrayPromotionRules: typeof arrayPromotionRules; + + /** + * Revives a JSON-serialized typed array. + * + * @param key - key + * @param value - value + * @returns value or typed array + * + * @example + * var parseJSON = require( `@stdlib/utils/parse-json` ); + * + * var str = '{"type":"Float64Array","data":[5,3]}'; + * + * var arr = parseJSON( str, ns.reviveTypedArray ); + * // returns [ 5.0, 3.0 ] + */ + reviveTypedArray: typeof reviveTypedArray; + + /** + * Returns a list of array data types to which a provided array data type can be safely cast. + * + * ## Notes + * + * - If not provided an array data type, the function returns a casting table. + * - If provided an unrecognized array data type, the function returns `null`. + * + * @param dtype - array data type + * @returns list of array data types or null + * + * @example + * var list = ns.arraySafeCasts( 'float32' ); + * // returns [...] + */ + arraySafeCasts: typeof arraySafeCasts; + + /** + * Returns a list of array data types to which a provided array data type can be safely cast or cast within the same "kind". + * + * ## Notes + * + * - If not provided an array data type, the function returns a casting table. + * - If provided an unrecognized array data type, the function returns `null`. + * + * @param dtype - array data type + * @returns list of array data types or null + * + * @example + * var list = ns.arraySameKindCasts( 'float32' ); + * // returns [...] + */ + arraySameKindCasts: typeof arraySameKindCasts; + + /** + * Determines (nested) array dimensions. + * + * @param arr - array + * @returns array shape + * + * @example + * var arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; + * + * var shape = ns.arrayShape( arr ); + * // returns [ 3, 3 ] + * + * @example + * var arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ] ]; + * + * var shape = ns.arrayShape( arr ); + * // returns [ 3 ] + * + * @example + * var arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], null ]; + * + * var shape = ns.arrayShape( arr ); + * // returns [ 3 ] + */ + arrayShape: typeof arrayShape; + + /** + * Constructor returning an object used to represent a generic, fixed-length raw binary data buffer which can be used to create views of shared memory. + */ + SharedArrayBuffer: typeof SharedArrayBuffer; + + /** + * Returns an iterator which repeatedly iterates over each element in an array-like object. + * + * @param src - input value + * @param options - function options + * @param options.iter - number of iterations + * @param options.dir - iteration direction + * @param mapFcn - function to invoke for each iterated value + * @param thisArg - execution context + * @throws must provide valid options + * @returns iterator + * + * @example + * var opts = { + * 'dir': -1 + * }; + * var it = ns.circarray2iterator( [ 1, 2, 3, 4 ], opts ); + * // returns + * + * var v = it.next().value; + * // returns 4 + * + * v = it.next().value; + * // returns 3 + * + * v = it.next().value; + * // returns 2 + */ + circarray2iterator: typeof circarray2iterator; + + /** + * Returns an iterator which iterates over each element in an array-like object. + * + * @param src - input value + * @param mapFc - function to invoke for each iterated value + * @param thisArg - execution context + * @returns iterator + * + * @example + * var iter = ns.array2iterator( [ 1, 2, 3, 4 ] ); + * + * var v = iter.next().value; + * // returns 1 + * + * v = iter.next().value; + * // returns 2 + * + * v = iter.next().value; + * // returns 3 + * + * // ... + */ + array2iterator: typeof array2iterator; + + /** + * Returns an iterator which iterates from right to left over each element in an array-like object. + * + * ## Notes + * + * - For dynamic array resizing, the only behavior made intentionally consistent with iterating from left to right is when elements are pushed onto the beginning (end) of an array. In other words, iterating from left to right combined with `[].push()` is consistent with iterating from right to left combined with `[].unshift()`. + * + * @param src - input value + * @param mapFcn - function to invoke for each iterated value + * @param thisArg - execution context + * @returns iterator + * + * @example + * var iter = ns.array2iteratorRight( [ 1, 2, 3, 4 ] ); + * + * var v = iter.next().value; + * // returns 4 + * + * v = iter.next().value; + * // returns 3 + * + * v = iter.next().value; + * // returns 2 + * + * // ... + */ + array2iteratorRight: typeof array2iteratorRight; + + /** + * Returns a JSON representation of a typed array. + * + * ## Notes + * + * - We build a JSON object representing a typed array similar to how Node.js `Buffer` objects are represented. See [Buffer][1]. + * + * [1]: https://nodejs.org/api/buffer.html#buffer_buf_tojson + * + * @param arr - typed array to serialize + * @returns JSON representation + * + * @example + * var Float64Array = require( `@stdlib/array/float64` ); + * + * var arr = new Float64Array( [ 5.0, 3.0 ] ); + * var json = ns.typedarray2json( arr ); + * // returns { 'type': 'Float64Array', 'data': [ 5.0, 3.0 ] } + */ + typedarray2json: typeof typedarray2json; + + /** + * Returns an iterator which iterates over each element in a sparse array-like object. + * + * @param src - input value + * @param mapFcn - function to invoke for each iterated value + * @param thisArg - execution context + * @returns iterator + * + * @example + * var iter = ns.sparsearray2iterator( [ 1, , 3, 4 ] ); + * + * var v = iter.next().value; + * // returns 1 + * + * v = iter.next().value; + * // returns 3 + * + * v = iter.next().value; + * // returns 4 + */ + sparsearray2iterator: typeof sparsearray2iterator; + + /** + * Returns an iterator which iterates from right to left over each element in a sparse array-like object. + * + * ## Notes + * + * - For dynamic array resizing, the only behavior made intentionally consistent with iterating from left to right is when elements are pushed onto the beginning (end) of an array. In other words, iterating from left to right combined with `[].push()` is consistent with iterating from right to left combined with `[].unshift()`. + * + * @param src - input value + * @param mapFcn - function to invoke for each iterated value + * @param thisArg - execution context + * @returns iterator + * + * @example + * var iter = ns.sparsearray2iteratorRight( [ 1, , 3, 4 ] ); + * + * var v = iter.next().value; + * // returns 4 + * + * v = iter.next().value; + * // returns 3 + * + * v = iter.next().value; + * // returns 1 + */ + sparsearray2iteratorRight: typeof sparsearray2iteratorRight; + + /** + * Returns an iterator which iterates over elements in an array-like object according to specified stride parameters. + * + * @param N - number of values to iterate + * @param src - input value + * @param stride - stride length + * @param offset - starting index + * @param mapFcn - function to invoke for each iterated value + * @param thisArg - execution context + * @throws first argument must be a nonnegative integer + * @throws third argument must be an integer + * @throws fourth argument must be a nonnegative integer + * @returns iterator + * + * @example + * var values = [ 1, 2, 3, 4, 5, 6, 7, 8 ]; + * + * var N = 4; + * var stride = -2; + * var offset = 6; + * + * var iter = ns.stridedarray2iterator( N, values, stride, offset ); + * + * var v = iter.next().value; + * // returns 7 + * + * v = iter.next().value; + * // returns 5 + * + * v = iter.next().value; + * // returns 3 + * + * // ... + */ + stridedarray2iterator: typeof stridedarray2iterator; + + /** + * Returns an iterator which iterates over each element in an array-like object view. + * + * @param src - input value + * @param begin - starting index (inclusive) (default: 0) + * @param end - ending index (non-inclusive) (default: src.length) + * @param mapFcn - function to invoke for each iterated value + * @param thisArg - execution context + * @returns iterator + * + * @example + * var iter = ns.arrayview2iterator( [ 1, 2, 3, 4 ], 1, 3 ); + * + * var v = iter.next().value; + * // returns 2 + * + * v = iter.next().value; + * // returns 3 + * + * var bool = iter.next().done; + * // returns true + */ + arrayview2iterator: typeof arrayview2iterator; + + /** + * Returns an iterator which iterates from right to left over each element in an array-like object view. + * + * @param src - input value + * @param begin - starting **view** index (inclusive) (default: 0) + * @param end - ending **view** index (non-inclusive) (default: src.length) + * @param mapFcn - function to invoke for each iterated value + * @param thisArg - execution context + * @returns iterator + * + * @example + * var iter = ns.arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1, 3 ); + * + * var v = iter.next().value; + * // returns 3 + * + * v = iter.next().value; + * // returns 2 + * + * var bool = iter.next().done; + * // returns true + */ + arrayview2iteratorRight: typeof arrayview2iteratorRight; + + /** + * Creates a typed array. + * + * @param buffer - underlying ArrayBuffer + * @param byteOffset - integer byte offset specifying the location of the first typed array element (default: 0) + * @param length - view length; if not provided, the view spans from the byteOffset to the end of the underlying ArrayBuffer + * @param dtype - data type (default: 'float64') + * @returns typed array + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 32 ); + * var arr = ns.typedarray( buf, 8, 2 ); + * // returns [ 0.0, 0.0 ] + * + * @example + * var ArrayBuffer = require( `@stdlib/array/buffer` ); + * + * var buf = new ArrayBuffer( 32 ); + * var arr = ns.typedarray( buf, 8, 2, 'int32' ); + * // returns [ 0, 0 ] + */ + typedarray: typeof typedarray; + + /** + * Returns a complex typed array constructor. + * + * @param dtype - data type + * @returns constructor or null + * + * @example + * var ctor = ns.typedarrayComplexCtors( 'complex128' ); + * // returns + * + * @example + * var ctor = ns.typedarrayComplexCtors( 'float64' ); + * // returns null + */ + typedarrayComplexCtors: typeof typedarrayComplexCtors; + + /** + * Returns a list of complex typed array data types. + * + * @returns list of complex typed array data types + * + * @example + * var list = ns.typedarrayComplexDataTypes(); + * // returns [ 'complex64', 'complex128' ] + */ + typedarrayComplexDataTypes: typeof typedarrayComplexDataTypes; + + /** + * Returns a typed array constructor. + * + * @param dtype - data type + * @returns constructor or null + * + * @example + * var ctor = ns.typedarrayCtors( 'float64' ); + * // returns + * + * @example + * var ctor = ns.typedarrayCtors( 'float' ); + * // returns null + */ + typedarrayCtors: typeof typedarrayCtors; + + /** + * Returns a list of typed array data types. + * + * @returns list of typed array data types + * + * @example + * var list = ns.typedarrayDataTypes(); + * // returns [ 'float32', 'float64', 'int16', 'int32', 'int8', 'uint16', 'uint32', 'uint8', 'uint8c' ] + */ + typedarrayDataTypes: typeof typedarrayDataTypes; + + /** + * Typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order. + */ + Uint8Array: typeof Uint8Array; + + /** + * Typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order clamped to 0-255. + */ + Uint8ClampedArray: typeof Uint8ClampedArray; + + /** + * Typed array constructor which returns a typed array representing an array of 16-bit unsigned integers in the platform byte order. + */ + Uint16Array: typeof Uint16Array; + + /** + * Typed array constructor which returns a typed array representing an array of 32-bit unsigned integers in the platform byte order. + */ + Uint32Array: typeof Uint32Array; + + /** + * Array constants. + */ + constants: typeof constants; +} + +/** +* Arrays. +*/ +declare var ns: Namespace; + + +// EXPORTS // + +export = ns; diff --git a/docs/types/test.ts b/docs/types/test.ts new file mode 100644 index 00000000..714a99ac --- /dev/null +++ b/docs/types/test.ts @@ -0,0 +1,29 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* tslint:disable:no-unused-expression */ + +import array = require( './index' ); + + +// TESTS // + +// The exported value is the expected interface... +{ + array; // $ExpectType Namespace +} diff --git a/docs/types/tsconfig.json b/docs/types/tsconfig.json new file mode 100644 index 00000000..a541d610 --- /dev/null +++ b/docs/types/tsconfig.json @@ -0,0 +1,39 @@ +{ + "compilerOptions": { + "allowSyntheticDefaultImports": false, + "allowUnreachableCode": false, + "allowUnusedLabels": false, + "alwaysStrict": true, + "baseUrl": ".", + "charset": "utf8", + "forceConsistentCasingInFileNames": true, + "keyofStringsOnly": false, + "lib": [ + "es6" + ], + "locale": "en", + "module": "commonjs", + "moduleResolution": "node", + "newLine": "lf", + "noEmit": true, + "noFallthroughCasesInSwitch": true, + "noImplicitAny": true, + "noImplicitReturns": false, + "noImplicitThis": true, + "noStrictGenericChecks": false, + "noUnusedLocals": true, + "noUnusedParameters": true, + "paths": {}, + "pretty": true, + "strictBindCallApply": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "suppressExcessPropertyErrors": false, + "suppressImplicitAnyIndexErrors": false, + "typeRoots": [ "." ], + "types": [] + }, + "exclude": [ + "node_modules" + ] +} diff --git a/docs/types/tslint.json b/docs/types/tslint.json new file mode 100644 index 00000000..a0c360d8 --- /dev/null +++ b/docs/types/tslint.json @@ -0,0 +1,252 @@ +{ + "extends": "dtslint/dtslint.json", + "rules": { + "expect": true, + "export-just-namespace": true, + "no-any-union": true, + "no-bad-reference": true, + "no-const-enum": true, + "no-dead-reference": true, + "no-declare-current-package": true, + "no-import-default-of-export-equals": true, + "no-outside-dependencies": true, + "no-padding": true, + "no-redundant-undefined": true, + "no-relative-import-in-test": false, + "no-self-import": true, + "no-single-declare-module": true, + "no-single-element-tuple-type": true, + "no-unnecessary-generics": true, + "no-useless-files": true, + "prefer-declare-function": true, + "strict-export-declare-modifiers": true, + "trim-file": true, + "unified-signatures": true, + "void-return": true, + + "adjacent-overload-signatures": true, + "ban-ts-ignore": false, + "ban-types": false, + "member-access": [ true, "no-public" ], + "member-ordering": [ true, "fields-first" ], + "no-any": false, + "no-empty-interface": true, + "no-import-side-effect": true, + "no-inferrable-types": true, + "no-internal-module": true, + "no-magic-numbers": false, + "no-namespace": true, + "no-non-null-assertion": true, + "no-parameter-reassignment": false, + "no-reference": true, + "no-unnecessary-type-assertion": true, + "no-var-requires": true, + "only-arrow-functions": false, + "prefer-for-of": false, + "promise-function-async": false, + "typedef": true, + "typedef-whitespace": [ true, + { + "call-signature": "nospace", + "index-signature": "nospace", + "parameter": "nospace", + "property-declaration": "nospace", + "variable-declaration": "nospace" + }, + { + "call-signature": "onespace", + "index-signature": "onespace", + "parameter": "onespace", + "property-declaration": "onespace", + "variable-declaration": "onespace" + } + ], + "unified-signatures": true, + + "await-promise": true, + "ban-comma-operator": true, + "ban": [ true, + { + "name": [ "*", "forEach" ], + "message": "Use a regular `for` loop instead." + } + ], + "curly": true, + "forin": true, + "function-constructor": true, + "import-blacklist": [ true, "lodash" ], + "label-position": true, + "no-arg": true, + "no-bitwise": false, + "no-conditional-assignment": true, + "no-console": true, + "no-construct": true, + "no-debugger": true, + "no-duplicate-super": true, + "no-duplicate-switch-case": true, + "no-duplicate-variable": [ true, "check-parameters" ], + "no-dynamic-delete": false, + "no-empty": true, + "no-eval": true, + "no-floating-promises": true, + "no-for-in-array": true, + "no-implicit-dependencies": false, + "no-inferred-empty-object-type": true, + "no-invalid-template-strings": true, + "no-invalid-this": true, + "no-misused-new": true, + "no-null-keyword": false, + "no-object-literal-type-assertion": true, + "no-return-await": true, + "no-shadowed-variable": false, + "no-sparse-arrays": true, + "no-string-literal": false, + "no-string-throw": true, + "no-submodule-imports": false, + "no-switch-case-fall-through": true, + "no-this-assignment": [ true, + { + "allowed-names": [ "^self$" ], + "allow-destructuring": true + } + ], + "no-unbound-method": [ true, "ignore-static" ], + "no-unnecessary-class": true, + "no-unsafe-any": true, + "no-unsafe-finally": true, + "no-unused-expression": true, + "no-use-before-declare": true, + "no-var-keyword": true, + "no-void-expression": true, + "prefer-conditional-expression": false, + "prefer-object-spread": false, + "radix": true, + "restrict-plus-operands": true, + "strict-boolean-expressions": false, + "strict-type-predicates": true, + "switch-default": true, + "triple-equals": true, + "unnecessary-constructor": true, + "use-default-type-parameter": true, + "use-isnan": true, + + "cyclomatic-complexity": false, + "deprecation": true, + "eofline": true, + "indent": [ true, "tabs", 4 ], + "linebreak-style": [ true, "LF" ], + "max-classes-per-file": [ true, 1 ], + "max-file-line-count": [ true, 1000 ], + "max-line-length": [ true, + { + "limit": 80, + "ignore-pattern": "^import |\\/\\/ |\\/?\\* " + } + ], + "no-default-export": false, + "no-default-import": false, + "no-duplicate-imports": true, + "no-mergeable-namespace": true, + "no-require-imports": false, + "object-literal-sort-keys": false, + "prefer-const": true, + "prefer-readonly": true, + "trailing-comma": [ false, + { + "esSpecCompliant": true + } + ], + + "align": false, + "array-type": [ true, "generic" ], + "arrow-parens": true, + "arrow-return-shorthand": true, + "binary-expression-operand-order": true, + "callable-types": true, + "class-name": true, + "comment-format": [ true, "check-space" ], + "comment-type": false, + "completed-docs": true, + "encoding": true, + "file-header": false, + "file-name-casing": [ true, "snake-case" ], + "import-spacing": true, + "increment-decrement": true, + "interface-name": [ true, "never-prefix" ], + "interface-over-type-literal": true, + "jsdoc-format": false, + "match-default-export-name": false, + "newline-before-return": false, + "newline-per-chained-call": false, + "new-parens": true, + "no-angle-bracket-type-assertion": true, + "no-boolean-literal-compare": false, + "no-consecutive-blank-lines": [ true, 2 ], + "no-irregular-whitespace": true, + "no-parameter-properties": true, + "no-redundant-jsdoc": true, + "no-reference-import": true, + "no-trailing-whitespace": true, + "no-unnecessary-callback-wrapper": true, + "no-unnecessary-initializer": true, + "no-unnecessary-qualifier": true, + "number-literal-format": false, + "object-literal-key-quotes": [ true, "always" ], + "object-literal-shorthand": [ true, "never" ], + "one-line": [ true, + "check-catch", + "check-finally", + "check-else", + "check-open-brace", + "check-whitespace" + ], + "one-variable-per-declaration": true, + "ordered-imports": [ true, + { + "grouped-imports": false, + "import-sources-order": "any", + "named-imports-order": "any", + "module-source-path": "full" + } + ], + "prefer-function-over-method": [ true, "allow-public", "allow-protected" ], + "prefer-method-signature": true, + "prefer-switch": [ true, + { + "min-cases": 5 + } + ], + "prefer-template": false, + "prefer-while": true, + "quotemark": [ true, "single", "avoid-escape", "avoid-template" ], + "return-undefined": false, + "semicolon": [ true, "always" ], + "space-before-function-paren": [ true, + { + "anonymous": "always", + "named": "never", + "asyncArrow": "always", + "method": "never", + "constructor": "never" + } + ], + "space-within-parens": [ true, 1 ], + "switch-final-break": [ true, "always" ], + "type-literal-delimiter": [ true, + { + "singleLine": "always" + } + ], + "unnecessary-bind": true, + "variable-name": [ true, "ban-keywords", "check-format" ], + "whitespace": [ true, + "check-branch", + "check-decl", + "check-operator", + "check-rest-spread", + "check-separator", + "check-type", + "check-preblock" + ] + } +} diff --git a/dtype/README.md b/dtype/README.md new file mode 100644 index 00000000..75d4d689 --- /dev/null +++ b/dtype/README.md @@ -0,0 +1,131 @@ + + +# Data Type + +> Return the data type of an array. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var dtype = require( '@stdlib/array/dtype' ); +``` + +#### dtype( array ) + +Returns the [data type][@stdlib/array/dtypes] of an `array`. + +```javascript +var Float64Array = require( '@stdlib/array/float64' ); +var arr = new Float64Array( 10 ); + +var dt = dtype( arr ); +// returns 'float64' +``` + +If provided an argument having an unknown or unsupported [data type][@stdlib/array/dtypes], the function returns `null`. + +```javascript +var dt = dtype( 'beep' ); +// returns null +``` + +
+ + + + + +
+ +
+ + + + + +
+ +## Examples + + + + + +```javascript +var dtypes = require( '@stdlib/array/dtypes' ); +var ctors = require( '@stdlib/array/ctors' ); +var dtype = require( '@stdlib/array/dtype' ); + +var DTYPES; +var ctor; +var arr; +var len; +var dt; +var i; + +// Get a list of supported array data types: +DTYPES = dtypes(); + +// Array length: +len = 10; + +// For each supported data type, create an array and confirm its data type... +for ( i = 0; i < DTYPES.length; i++ ) { + ctor = ctors( DTYPES[ i ] ); + arr = new ctor( len ); + dt = dtype( arr ); + console.log( '%s == %s => %s', DTYPES[ i ], dt, DTYPES[ i ] === dt ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/dtype/benchmark/benchmark.js b/dtype/benchmark/benchmark.js new file mode 100644 index 00000000..52a07a17 --- /dev/null +++ b/dtype/benchmark/benchmark.js @@ -0,0 +1,62 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var dtypes = require( '@stdlib/array/dtypes' ); +var ctors = require( '@stdlib/array/ctors' ); +var isString = require( '@stdlib/assert/is-string' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var dtype = require( './../lib' ); + + +// VARIABLES // + +var DTYPES = dtypes(); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var arrays; + var ctor; + var dt; + var i; + + arrays = []; + for ( i = 0; i < DTYPES.length; i++ ) { + ctor = ctors( DTYPES[ i ] ); + arrays.push( new ctor( 10 ) ); + } + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + dt = dtype( arrays[ i%arrays.length ] ); + if ( typeof dt !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( !isString( dt ) ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/dtype/docs/repl.txt b/dtype/docs/repl.txt new file mode 100644 index 00000000..563d172b --- /dev/null +++ b/dtype/docs/repl.txt @@ -0,0 +1,28 @@ + +{{alias}}( array ) + Returns the data type of an array. + + If provided an argument having an unknown or unsupported type, the function + returns `null`. + + Parameters + ---------- + array: any + Input value. + + Returns + ------- + out: string|null + Data type. + + Examples + -------- + > var arr = new {{alias:@stdlib/array/float64}}( 10 ); + > var dt = {{alias}}( arr ) + 'float64' + > dt = {{alias}}( 'beep' ) + null + + See Also + -------- + diff --git a/dtype/docs/types/index.d.ts b/dtype/docs/types/index.d.ts new file mode 100644 index 00000000..9c3e3e09 --- /dev/null +++ b/dtype/docs/types/index.d.ts @@ -0,0 +1,47 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/// + +import { TypedArray } from '@stdlib/types/array'; + +/** +* Returns the data type of an array. +* +* ## Notes +* +* - If provided an argument having an unknown or unsupported type, the function returns `null`. +* +* @param value - input value +* @returns data type +* +* @example +* var dt = dtype( [ 1, 2, 3 ] ); +* // returns 'generic' +* +* var dt = dtype( 'beep' ); +* // returns null +*/ +declare function dtype( value: TypedArray | Array ): string | null; + + +// EXPORTS // + +export = dtype; diff --git a/dtype/docs/types/test.ts b/dtype/docs/types/test.ts new file mode 100644 index 00000000..5c72bba7 --- /dev/null +++ b/dtype/docs/types/test.ts @@ -0,0 +1,34 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import dtype = require( './index' ); + +// TESTS // + +// The function returns a string or null.. +{ + const x = new Float64Array( 10 ); + + dtype( x ); // $ExpectType string | null +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + dtype(); // $ExpectError + dtype( [ 1, 2, 3 ], 3 ); // $ExpectError +} diff --git a/dtype/examples/index.js b/dtype/examples/index.js new file mode 100644 index 00000000..3c41b730 --- /dev/null +++ b/dtype/examples/index.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var dtypes = require( '@stdlib/array/dtypes' ); +var ctors = require( '@stdlib/array/ctors' ); +var dtype = require( './../lib' ); + +var DTYPES; +var ctor; +var arr; +var len; +var dt; +var i; + +// Get a list of supported array data types: +DTYPES = dtypes(); + +// Array length: +len = 10; + +// For each supported data type, create an array and confirm its data type... +for ( i = 0; i < DTYPES.length; i++ ) { + ctor = ctors( DTYPES[ i ] ); + arr = new ctor( len ); + dt = dtype( arr ); + console.log( '%s == %s => %s', DTYPES[ i ], dt, DTYPES[ i ] === dt ); +} diff --git a/dtype/lib/ctor2dtype.js b/dtype/lib/ctor2dtype.js new file mode 100644 index 00000000..be201855 --- /dev/null +++ b/dtype/lib/ctor2dtype.js @@ -0,0 +1,40 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MAIN // + +// Mapping from array constructors to data types... +var ctor2dtypes = { + 'Float32Array': 'float32', + 'Float64Array': 'float64', + 'Array': 'generic', + 'Int16Array': 'int16', + 'Int32Array': 'int32', + 'Int8Array': 'int8', + 'Uint16Array': 'uint16', + 'Uint32Array': 'uint32', + 'Uint8Array': 'uint8', + 'Uint8ClampedArray': 'uint8c' +}; + + +// EXPORTS // + +module.exports = ctor2dtypes; diff --git a/dtype/lib/ctors.js b/dtype/lib/ctors.js new file mode 100644 index 00000000..8e3ee804 --- /dev/null +++ b/dtype/lib/ctors.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var Float64Array = require( '@stdlib/array/float64' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); +var Int8Array = require( '@stdlib/array/int8' ); + + +// MAIN // + +// Note: order should match `dtypes` order +var CTORS = [ + Float64Array, + Float32Array, + Int32Array, + Uint32Array, + Int16Array, + Uint16Array, + Int8Array, + Uint8Array, + Uint8ClampedArray +]; + + +// EXPORTS // + +module.exports = CTORS; diff --git a/dtype/lib/dtypes.js b/dtype/lib/dtypes.js new file mode 100644 index 00000000..388913ed --- /dev/null +++ b/dtype/lib/dtypes.js @@ -0,0 +1,39 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MAIN // + +// Note: order should match `ctors` order +var DTYPES = [ + 'float64', + 'float32', + 'int32', + 'uint32', + 'int16', + 'uint16', + 'int8', + 'uint8', + 'uint8c' +]; + + +// EXPORTS // + +module.exports = DTYPES; diff --git a/dtype/lib/index.js b/dtype/lib/index.js new file mode 100644 index 00000000..29eebbe4 --- /dev/null +++ b/dtype/lib/index.js @@ -0,0 +1,49 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Return the data type of an array. +* +* @module @stdlib/array/dtype +* +* @example +* var Float64Array = require( '@stdlib/array/float64' ); +* var dtype = require( '@stdlib/array/dtype' ); +* +* var arr = new Float64Array( 10 ); +* +* var dt = dtype( arr ); +* // returns 'float64' +* +* dt = dtype( {} ); +* // returns null +* +* dt = dtype( 'beep' ); +* // returns null +*/ + +// MODULES // + +var dtype = require( './main.js' ); + + +// EXPORTS // + +module.exports = dtype; diff --git a/dtype/lib/main.js b/dtype/lib/main.js new file mode 100644 index 00000000..98b761d3 --- /dev/null +++ b/dtype/lib/main.js @@ -0,0 +1,71 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isBuffer = require( '@stdlib/assert/is-buffer' ); +var isArray = require( '@stdlib/assert/is-array' ); +var constructorName = require( '@stdlib/utils/constructor-name' ); +var ctor2dtype = require( './ctor2dtype.js' ); +var CTORS = require( './ctors.js' ); +var DTYPES = require( './dtypes.js' ); + + +// VARIABLES // + +var NTYPES = DTYPES.length; + + +// MAIN // + +/** +* Returns the data type of an array. +* +* @param {*} value - input value +* @returns {(string|null)} data type +* +* @example +* var dt = dtype( [ 1, 2, 3 ] ); +* // returns 'generic' +* +* var dt = dtype( 'beep' ); +* // returns null +*/ +function dtype( value ) { + var i; + if ( isArray( value ) ) { + return 'generic'; + } + if ( isBuffer( value ) ) { + return null; + } + for ( i = 0; i < NTYPES; i++ ) { + if ( value instanceof CTORS[ i ] ) { + return DTYPES[ i ]; + } + } + // If the above failed, fall back to a more robust (and significantly slower) means for resolving underlying data types: + return ctor2dtype[ constructorName( value ) ] || null; +} + + +// EXPORTS // + +module.exports = dtype; diff --git a/dtype/package.json b/dtype/package.json new file mode 100644 index 00000000..0f00b4a2 --- /dev/null +++ b/dtype/package.json @@ -0,0 +1,66 @@ +{ + "name": "@stdlib/array/dtype", + "version": "0.0.0", + "description": "Return the data type of an array.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "array", + "dtypes", + "dtype", + "data", + "type", + "utilities", + "utility", + "utils", + "util" + ], + "__stdlib__": {} +} diff --git a/dtype/test/test.js b/dtype/test/test.js new file mode 100644 index 00000000..1f12ab10 --- /dev/null +++ b/dtype/test/test.js @@ -0,0 +1,97 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var dtypes = require( '@stdlib/array/dtypes' ); +var ctors = require( '@stdlib/array/ctors' ); +var allocUnsafe = require( '@stdlib/buffer/alloc-unsafe' ); +var dtype = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof dtype, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function returns the data type for an input array', function test( t ) { + var DTYPES; + var ctor; + var arr; + var dt; + var i; + + DTYPES = dtypes(); + + for ( i = 0; i < DTYPES.length; i++ ) { + ctor = ctors( DTYPES[ i ] ); + arr = new ctor( 10 ); + dt = dtype( arr ); + t.strictEqual( dt, DTYPES[ i ], 'returns expected value' ); + } + t.end(); +}); + +tape( 'the function does not support array-like objects', function test( t ) { + var arr; + var dt; + + arr = { + 'length': 10 + }; + dt = dtype( arr ); + t.strictEqual( dt, null, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns `null` if provided a Node.js Buffer', function test( t ) { + var buf; + var dt; + + buf = allocUnsafe( 10 ); + dt = dtype( buf ); + t.strictEqual( dt, null, 'returns expected value' ); + t.end(); +}); + +tape( 'if provided an argument having an unknown/unsupported data type, the function returns `null`', function test( t ) { + var buffers; + var i; + + buffers = [ + 'beep', + 5, + NaN, + null, + void 0, + true, + false, + {}, + function noop() {} + ]; + for ( i = 0; i < buffers.length; i++ ) { + t.strictEqual( dtype( buffers[i] ), null, 'returns expected value for ' + buffers[ i ] ); + } + t.end(); +}); diff --git a/dtypes/README.md b/dtypes/README.md new file mode 100644 index 00000000..d8175869 --- /dev/null +++ b/dtypes/README.md @@ -0,0 +1,130 @@ + + +# Data Types + +> List of array data types. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var dtypes = require( '@stdlib/array/dtypes' ); +``` + +#### dtypes() + +Returns a list of array data types. + +```javascript +var out = dtypes(); +// returns [ 'float32', 'float64', 'generic', 'int16', 'int32', 'int8', 'uint16', 'uint32', 'uint8', 'uint8c' ] +``` + +The output `array` contains the following data types: + +- `float32`: single-precision floating-point numbers. +- `float64`: double-precision floating-point numbers. +- `generic`: values of any type. +- `int16`: signed 16-bit integers. +- `int32`: signed 32-bit integers. +- `int8`: signed 8-bit integers. +- `uint16`: unsigned 16-bit integers. +- `uint32`: unsigned 32-bit integers. +- `uint8`: unsigned 8-bit integers. +- `uint8c`: unsigned clamped 8-bit integers. + +
+ + + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var indexOf = require( '@stdlib/utils/index-of' ); +var dtypes = require( '@stdlib/array/dtypes' ); + +var DTYPES = dtypes(); +var bool; + +function isdtype( str ) { + if ( indexOf( DTYPES, str ) === -1 ) { + return false; + } + return true; +} + +bool = isdtype( 'float64' ); +// returns true + +bool = isdtype( 'int16' ); +// returns true + +bool = isdtype( 'uint8' ); +// returns true + +bool = isdtype( 'beep' ); +// returns false +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/dtypes/benchmark/benchmark.js b/dtypes/benchmark/benchmark.js new file mode 100644 index 00000000..d86bf81f --- /dev/null +++ b/dtypes/benchmark/benchmark.js @@ -0,0 +1,48 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives; +var pkg = require( './../package.json' ).name; +var dtypes = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = dtypes(); + if ( out.length !== 10 ) { + b.fail( 'should return an array of length 10' ); + } + } + b.toc(); + if ( !isStringArray( out ) ) { + b.fail( 'should return an array of strings' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/dtypes/docs/repl.txt b/dtypes/docs/repl.txt new file mode 100644 index 00000000..cd25bbe8 --- /dev/null +++ b/dtypes/docs/repl.txt @@ -0,0 +1,30 @@ + +{{alias}}() + Returns a list of array data types. + + The output array contains the following data types: + + - float32: single-precision floating-point numbers. + - float64: double-precision floating-point numbers. + - generic: values of any type. + - int16: signed 16-bit integers. + - int32: signed 32-bit integers. + - int8: signed 8-bit integers. + - uint16: unsigned 16-bit integers. + - uint32: unsigned 32-bit integers. + - uint8: unsigned 8-bit integers. + - uint8c: unsigned clamped 8-bit integers. + + Returns + ------- + out: Array + List of array data types. + + Examples + -------- + > var out = {{alias}}() + + + See Also + -------- + diff --git a/dtypes/docs/types/index.d.ts b/dtypes/docs/types/index.d.ts new file mode 100644 index 00000000..e3b4f3ad --- /dev/null +++ b/dtypes/docs/types/index.d.ts @@ -0,0 +1,35 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/** +* Returns a list of array data types. +* +* @returns list of array data types +* +* @example +* var list = dtypes(); +* // returns [ 'float32', 'float64', 'generic', 'int16', 'int32', 'int8', 'uint16', 'uint32', 'uint8', 'uint8c' ] +*/ +declare function dtypes(): Array; + + +// EXPORTS // + +export = dtypes; diff --git a/dtypes/docs/types/test.ts b/dtypes/docs/types/test.ts new file mode 100644 index 00000000..a80e01d2 --- /dev/null +++ b/dtypes/docs/types/test.ts @@ -0,0 +1,32 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import dtypes = require( './index' ); + +// TESTS // + +// The function returns a string array.. +{ + dtypes(); // $ExpectType string[] +} + +// The compiler throws an error if the function is provided arguments... +{ + dtypes( 1 ); // $ExpectError + dtypes( 1, 2 ); // $ExpectError +} diff --git a/dtypes/examples/index.js b/dtypes/examples/index.js new file mode 100644 index 00000000..441447aa --- /dev/null +++ b/dtypes/examples/index.js @@ -0,0 +1,48 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var indexOf = require( '@stdlib/utils/index-of' ); +var dtypes = require( './../lib' ); + +var DTYPES = dtypes(); +var bool; + +function isdtype( str ) { + if ( indexOf( DTYPES, str ) === -1 ) { + return false; + } + return true; +} + +bool = isdtype( 'float64' ); +console.log( bool ); +// => true + +bool = isdtype( 'int8' ); +console.log( bool ); +// => true + +bool = isdtype( 'uint16' ); +console.log( bool ); +// => true + +bool = isdtype( 'beep' ); +console.log( bool ); +// => false diff --git a/dtypes/lib/dtypes.json b/dtypes/lib/dtypes.json new file mode 100644 index 00000000..3eb731df --- /dev/null +++ b/dtypes/lib/dtypes.json @@ -0,0 +1,12 @@ +[ + "float32", + "float64", + "generic", + "int16", + "int32", + "int8", + "uint16", + "uint32", + "uint8", + "uint8c" +] diff --git a/dtypes/lib/index.js b/dtypes/lib/index.js new file mode 100644 index 00000000..00e3389b --- /dev/null +++ b/dtypes/lib/index.js @@ -0,0 +1,40 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Return a list of array data types. +* +* @module @stdlib/array/dtypes +* +* @example +* var dtypes = require( '@stdlib/array/dtypes' ); +* +* var list = dtypes(); +* // returns [ 'float32', 'float64', 'generic', 'int16', 'int32', 'int8', 'uint16', 'uint32', 'uint8', 'uint8c' ] +*/ + +// MODULES // + +var dtypes = require( './main.js' ); + + +// EXPORTS // + +module.exports = dtypes; diff --git a/dtypes/lib/main.js b/dtypes/lib/main.js new file mode 100644 index 00000000..3067ebe7 --- /dev/null +++ b/dtypes/lib/main.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var DTYPES = require( './dtypes.json' ); + + +// MAIN // + +/** +* Returns a list of array data types. +* +* @returns {StringArray} list of array data types +* +* @example +* var list = dtypes(); +* // returns [ 'float32', 'float64', 'generic', 'int16', 'int32', 'int8', 'uint16', 'uint32', 'uint8', 'uint8c' ] +*/ +function dtypes() { + return DTYPES.slice(); +} + + +// EXPORTS // + +module.exports = dtypes; diff --git a/dtypes/package.json b/dtypes/package.json new file mode 100644 index 00000000..d7019ec8 --- /dev/null +++ b/dtypes/package.json @@ -0,0 +1,67 @@ +{ + "name": "@stdlib/array/dtypes", + "version": "0.0.0", + "description": "List of array data types.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "typed", + "array", + "dtypes", + "dtype", + "data", + "type", + "utilities", + "utility", + "utils", + "util" + ], + "__stdlib__": {} +} diff --git a/dtypes/test/test.js b/dtypes/test/test.js new file mode 100644 index 00000000..fcdda1d5 --- /dev/null +++ b/dtypes/test/test.js @@ -0,0 +1,55 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var dtypes = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof dtypes, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function returns a list of array data types', function test( t ) { + var expected; + var actual; + + expected = [ + 'float32', + 'float64', + 'generic', + 'int16', + 'int32', + 'int8', + 'uint16', + 'uint32', + 'uint8', + 'uint8c' + ]; + actual = dtypes(); + + t.deepEqual( actual, expected, 'returns expected value' ); + t.end(); +}); diff --git a/examples/index.js b/examples/index.js new file mode 100644 index 00000000..c7e940d8 --- /dev/null +++ b/examples/index.js @@ -0,0 +1,24 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var objectKeys = require( '@stdlib/utils/keys' ); +var ns = require( './../lib' ); + +console.log( objectKeys( ns ) ); diff --git a/filled/README.md b/filled/README.md new file mode 100644 index 00000000..aad7b461 --- /dev/null +++ b/filled/README.md @@ -0,0 +1,223 @@ + + +# Filled Array + +> Create a filled array. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var filledarray = require( '@stdlib/array/filled' ); +``` + +#### filledarray( \[dtype] ) + +Creates a filled array having a specified data type `dtype`. + +```javascript +var arr = filledarray(); +// returns +``` + +The function recognizes the following data types: + +- `float64`: double-precision floating-point numbers (IEEE 754) +- `float32`: single-precision floating-point numbers (IEEE 754) +- `int32`: 32-bit two's complement signed integers +- `uint32`: 32-bit unsigned integers +- `int16`: 16-bit two's complement signed integers +- `uint16`: 16-bit unsigned integers +- `int8`: 8-bit two's complement signed integers +- `uint8`: 8-bit unsigned integers +- `uint8c`: 8-bit unsigned integers clamped to `0-255` +- `generic`: generic JavaScript values + +By default, the output array data type is `float64` (i.e., a [typed array][mdn-typed-array]). To specify an alternative data type, provide a `dtype` argument. + +```javascript +var arr = filledarray( 'int32' ); +// returns +``` + +#### filledarray( value, length\[, dtype] ) + +Returns a filled array having a specified `length`. + +```javascript +var arr1 = filledarray( 1.0, 5 ); +// returns [ 1.0, 1.0, 1.0, 1.0, 1.0 ] + +var arr2 = filledarray( 1, 5, 'uint8' ); +// returns [ 1, 1, 1, 1, 1 ] +``` + +#### filledarray( value, array\[, dtype] ) + +Creates a filled array from another array (or array-like object). + +```javascript +var arr0 = { + '0': 0.5, + '1': 0.5, + '2': 0.5, + 'length': 3 +}; + +var arr1 = filledarray( 1.0, arr0 ); +// returns [ 1.0, 1.0, 1.0 ] + +var arr2 = filledarray( 2.0, arr1 ); +// returns [ 2.0, 2.0, 2.0 ] + +var arr3 = filledarray( 3, arr1, 'int32' ); +// returns [ 3, 3, 3 ] +``` + +#### filledarray( value, iterable\[, dtype] ) + +Creates a filled array from an iterable. + +```javascript +var iterConstant = require( '@stdlib/iter/constant' ); + +var it = iterConstant( 3.0, { + 'iter': 3 +}); +var arr1 = filledarray( 1.0, it ); +// returns [ 1.0, 1.0, 1.0 ] + +var arr2 = filledarray( 1.0, it, 'float32' ); +// returns [ 1.0, 1.0, 1.0 ] +``` + +#### filledarray( value, buffer\[, byteOffset\[, length]]\[, dtype] ) + +Returns a filled [typed array][mdn-typed-array] view of an [`ArrayBuffer`][mdn-arraybuffer]. + +```javascript +var ArrayBuffer = require( '@stdlib/array/buffer' ); + +var buf = new ArrayBuffer( 32 ); +var arr = filledarray( 1.0, buf ); +// returns [ 1.0, 1.0, 1.0, 1.0 ] + +buf = new ArrayBuffer( 32 ); +arr = filledarray( 1.0, buf, 'float32' ); +// returns [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ] + +buf = new ArrayBuffer( 32 ); +arr = filledarray( 1.0, buf, 16 ); +// returns [ 1.0, 1.0 ] + +buf = new ArrayBuffer( 32 ); +arr = filledarray( 1.0, buf, 16, 'float32' ); +// returns [ 1.0, 1.0, 1.0, 1.0 ] + +buf = new ArrayBuffer( 32 ); +arr = filledarray( 1.0, buf, 16, 1 ); +// returns [ 1.0 ] + +buf = new ArrayBuffer( 32 ); +arr = filledarray( 1, buf, 10, 4, 'int16' ); +// returns [ 1, 1, 1, 1 ] +``` + +
+ + + + + +
+ +## Notes + +- Creating a generic [array][mdn-array] from an [`ArrayBuffer`][mdn-arraybuffer] is **not** supported. + +
+ + + + + +
+ +## Examples + + + +```javascript +var discreteUniform = require( '@stdlib/random/base/discrete-uniform' ); +var dtypes = require( '@stdlib/array/dtypes' ); +var filledarray = require( '@stdlib/array/filled' ); + +// Generate a random number: +var r = discreteUniform( 0, 100 ); + +// Get the list of supported array data types: +var dt = dtypes(); + +// Generate filled arrays... +var arr; +var i; +for ( i = 0; i < dt.length; i++ ) { + arr = filledarray( r, 10, dt[ i ] ); + console.log( arr ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/filled/benchmark/benchmark.js b/filled/benchmark/benchmark.js new file mode 100644 index 00000000..9aaab1a7 --- /dev/null +++ b/filled/benchmark/benchmark.js @@ -0,0 +1,228 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var isArray = require( '@stdlib/assert/is-array' ); +var pkg = require( './../package.json' ).name; +var filledarray = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 0.0, 0 ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=float64', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 0.0, 0, 'float64' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=float32', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 0.0, 0, 'float32' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=int32', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 0, 0, 'int32' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint32', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 0, 0, 'uint32' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=int16', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 0, 0, 'int16' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint16', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 0, 0, 'uint16' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=int8', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 0, 0, 'int8' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint8', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 0, 0, 'uint8' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint8c', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 0, 0, 'uint8c' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=generic', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 0, 0, 'generic' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isArray( arr ) ) { + b.fail( 'should return an array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/filled/benchmark/benchmark.length.float32.js b/filled/benchmark/benchmark.length.float32.js new file mode 100644 index 00000000..251d5e9b --- /dev/null +++ b/filled/benchmark/benchmark.length.float32.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var filledarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 1.0, len, 'float32' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':dtype=float32,len='+len, f ); + } +} + +main(); diff --git a/filled/benchmark/benchmark.length.float64.js b/filled/benchmark/benchmark.length.float64.js new file mode 100644 index 00000000..d67a24e1 --- /dev/null +++ b/filled/benchmark/benchmark.length.float64.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var filledarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 1.0, len, 'float64' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':dtype=float64,len='+len, f ); + } +} + +main(); diff --git a/filled/benchmark/benchmark.length.generic.js b/filled/benchmark/benchmark.length.generic.js new file mode 100644 index 00000000..0d21e4e9 --- /dev/null +++ b/filled/benchmark/benchmark.length.generic.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isArray = require( '@stdlib/assert/is-array' ); +var pkg = require( './../package.json' ).name; +var filledarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 1.0, len, 'generic' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':dtype=generic,len='+len, f ); + } +} + +main(); diff --git a/filled/benchmark/benchmark.length.int16.js b/filled/benchmark/benchmark.length.int16.js new file mode 100644 index 00000000..b28b58b5 --- /dev/null +++ b/filled/benchmark/benchmark.length.int16.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var filledarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 1, len, 'int16' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':dtype=int16,len='+len, f ); + } +} + +main(); diff --git a/filled/benchmark/benchmark.length.int32.js b/filled/benchmark/benchmark.length.int32.js new file mode 100644 index 00000000..3ced244b --- /dev/null +++ b/filled/benchmark/benchmark.length.int32.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var filledarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 1, len, 'int32' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':dtype=int32,len='+len, f ); + } +} + +main(); diff --git a/filled/benchmark/benchmark.length.int8.js b/filled/benchmark/benchmark.length.int8.js new file mode 100644 index 00000000..98ad0f7c --- /dev/null +++ b/filled/benchmark/benchmark.length.int8.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var filledarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 1, len, 'int8' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':dtype=int8,len='+len, f ); + } +} + +main(); diff --git a/filled/benchmark/benchmark.length.uint16.js b/filled/benchmark/benchmark.length.uint16.js new file mode 100644 index 00000000..d5020029 --- /dev/null +++ b/filled/benchmark/benchmark.length.uint16.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var filledarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 1, len, 'uint16' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':dtype=uint16,len='+len, f ); + } +} + +main(); diff --git a/filled/benchmark/benchmark.length.uint32.js b/filled/benchmark/benchmark.length.uint32.js new file mode 100644 index 00000000..d23d2955 --- /dev/null +++ b/filled/benchmark/benchmark.length.uint32.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var filledarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 1, len, 'uint32' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':dtype=uint32,len='+len, f ); + } +} + +main(); diff --git a/filled/benchmark/benchmark.length.uint8.js b/filled/benchmark/benchmark.length.uint8.js new file mode 100644 index 00000000..a93ea6df --- /dev/null +++ b/filled/benchmark/benchmark.length.uint8.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var filledarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 1, len, 'uint8' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':dtype=uint8,len='+len, f ); + } +} + +main(); diff --git a/filled/benchmark/benchmark.length.uint8c.js b/filled/benchmark/benchmark.length.uint8c.js new file mode 100644 index 00000000..8bbc2694 --- /dev/null +++ b/filled/benchmark/benchmark.length.uint8c.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var filledarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = filledarray( 1, len, 'uint8c' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':dtype=uint8c,len='+len, f ); + } +} + +main(); diff --git a/filled/docs/repl.txt b/filled/docs/repl.txt new file mode 100644 index 00000000..cca61734 --- /dev/null +++ b/filled/docs/repl.txt @@ -0,0 +1,155 @@ + +{{alias}}( [dtype] ) + Creates a filled array. + + The function supports the following data types: + + - float64: double-precision floating-point numbers (IEEE 754) + - float32: single-precision floating-point numbers (IEEE 754) + - int32: 32-bit two's complement signed integers + - uint32: 32-bit unsigned integers + - int16: 16-bit two's complement signed integers + - uint16: 16-bit unsigned integers + - int8: 8-bit two's complement signed integers + - uint8: 8-bit unsigned integers + - uint8c: 8-bit unsigned integers clamped to 0-255 + - generic: generic JavaScript values + + The default array data type is `float64`. + + Parameters + ---------- + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray|Array + Output array. + + Examples + -------- + > var arr = {{alias}}() + + > arr = {{alias}}( 'float32' ) + + + +{{alias}}( value, length[, dtype] ) + Returns a filled array having a specified length. + + Parameters + ---------- + value: any + Fill value. + + length: integer + Array length. + + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray|Array + Output array. + + Examples + -------- + > var arr = {{alias}}( 1.0, 5 ) + [ 1.0, 1.0, 1.0, 1.0, 1.0 ] + > arr = {{alias}}( 1, 5, 'int32' ) + [ 1, 1, 1, 1, 1 ] + + +{{alias}}( value, array[, dtype] ) + Creates a filled array from another array (or array-like object). + + Parameters + ---------- + value: any + Fill value. + + array: ArrayLikeObject + Array from which to generate another array. + + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray|Array + Output array. + + Examples + -------- + > var arr1 = {{alias}}( 2.0, [ 0.5, 0.5, 0.5 ] ) + [ 2.0, 2.0, 2.0 ] + > var arr2 = {{alias}}( 1.0, arr1, 'float32' ) + [ 1.0, 1.0, 1.0 ] + + +{{alias}}( value, iterable[, dtype] ) + Creates a filled array from an iterable. + + Parameters + ---------- + value: any + Fill value. + + iterable: Object + Iterable from which to generate an array. + + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray|Array + Output array. + + Examples + -------- + > var arr1 = {{alias:@stdlib/iter/constant}}( 3.0, {'iter': 3} ); + > var arr2 = {{alias}}( 1.0, arr1, 'float32' ) + [ 1.0, 1.0, 1.0 ] + + +{{alias}}( value, buffer[, byteOffset[, length]][, dtype] ) + Returns a filled typed array view of an ArrayBuffer. + + The 'generic' array data type is *not* supported. + + Parameters + ---------- + value: any + Fill value. + + buffer: ArrayBuffer + Underlying ArrayBuffer. + + byteOffset: integer (optional) + Integer byte offset specifying the location of the first typed array + element. Default: 0. + + length: integer (optional) + View length. If not provided, the view spans from the byteOffset to + the end of the underlying ArrayBuffer. + + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray + A typed array. + + Examples + -------- + > var buf = new {{alias:@stdlib/array/buffer}}( 16 ); + > var arr = {{alias}}( 1.0, buf, 0, 4, 'float32' ) + [ 1.0, 1.0, 1.0, 1.0 ] + + See Also + -------- + diff --git a/filled/docs/types/index.d.ts b/filled/docs/types/index.d.ts new file mode 100644 index 00000000..d57f999e --- /dev/null +++ b/filled/docs/types/index.d.ts @@ -0,0 +1,225 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/// + +import { TypedArray } from '@stdlib/types/array'; +import { Collection } from '@stdlib/types/object'; +import { IterableIterator } from '@stdlib/types/iter'; + +/** +* Array or typed array. +*/ +type ArrayOrTypedArray = Array | TypedArray; + +/** +* Creates a filled array. +* +* The function recognizes the following data types: +* +* - `float64`: double-precision floating-point numbers (IEEE 754) +* - `float32`: single-precision floating-point numbers (IEEE 754) +* - `int32`: 32-bit two's complement signed integers +* - `uint32`: 32-bit unsigned integers +* - `int16`: 16-bit two's complement signed integers +* - `uint16`: 16-bit unsigned integers +* - `int8`: 8-bit two's complement signed integers +* - `uint8`: 8-bit unsigned integers +* - `uint8c`: 8-bit unsigned integers clamped to `0-255` +* - `generic`: generic JavaScript values +* +* @param dtype - data type (default: 'float64') +* @throws must provide a recognized data type +* @returns filled array +* +* @example +* var arr = filledarray(); +* // returns +* +* @example +* var arr = filledarray( 'float32' ); +* // returns +*/ +declare function filledarray( dtype?: string ): ArrayOrTypedArray; + +/** +* Creates a filled array having a specified `length`. +* +* @param value - fill value +* @param length - array length +* @param dtype - data type (default: 'float64') +* @throws must provide a recognized data type +* @returns filled array +* +* @example +* var arr = filledarray( 1.0, 5 ); +* // returns [ 0.0, 0.0, 0.0, 0.0, 0.0 ] +* +* @example +* var arr = filledarray( 1.0, 5, 'float32' ); +* // returns [ 0.0, 0.0, 0.0, 0.0, 0.0 ] +*/ +declare function filledarray( value: any, length: number, dtype?: string ): ArrayOrTypedArray; // tslint:disable-line:max-line-length + +/** +* Creates a filled array from another `array`. +* +* @param value - fill value +* @param array - typed array or array-like object +* @param dtype - data type (default: 'float64') +* @throws must provide a recognized data type +* @returns filled array +* +* @example +* var arr = filledarray( 1.0, [ 5.0, -3.0, 2.0 ] ); +* // returns [ 1.0, 1.0, 1.0 ] +* +* @example +* var arr = filledarray( 1.0, [ 5.0, -3.0, 2.0 ], 'float32' ); +* // returns [ 1.0, 1.0, 1.0 ] +*/ +declare function filledarray( value: any, array: Collection, dtype?: string ): ArrayOrTypedArray; // tslint:disable-line:max-line-length unified-signatures + +/** +* Creates a filled array from an iterable. +* +* @param value - fill value +* @param iterable - iterable +* @param dtype - data type (default: 'float64') +* @throws must provide a recognized data type +* @returns filled array +* +* @example +* var iterConstant = require( `@stdlib/iter/constant` ); +* +* var it = iterConstant( 3.0, { +* 'iter': 3 +* }); +* var arr = filledarray( 1.0, it ); +* // returns [ 1.0, 1.0, 1.0 ] +* +* @example +* var iterConstant = require( `@stdlib/iter/constant` ); +* +* var it = iterConstant( 3.0, { +* 'iter': 3 +* }); +* var arr = filledarray( 1.0, it, 'float32' ); +* // returns [ 1.0, 1.0, 1.0 ] +*/ +declare function filledarray( value: any, iterable: IterableIterator, dtype?: string ): ArrayOrTypedArray; // tslint:disable-line:max-line-length unified-signatures + +/** +* Returns a filled typed array view of an `ArrayBuffer`. +* +* ## Notes +* +* - Creating a generic array from an `ArrayBuffer` is **not** supported. +* +* @param value - fill value +* @param buffer - `ArrayBuffer` +* @param byteOffset - byte offset +* @param length - view length +* @param dtype - data type (default: 'float64') +* @throws must provide a recognized data type +* @returns filled array +* +* @example +* var ArrayBuffer = require( `@stdlib/array/buffer` ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = filledarray( 1.0, buf, 8, 2 ); +* // returns [ 1.0, 1.0 ] +* +* @example +* var ArrayBuffer = require( `@stdlib/array/buffer` ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = filledarray( 1.0, buf, 8, 2, 'float32' ); +* // returns [ 1.0, 1.0 ] +* +*/ +declare function filledarray( value: any, buffer: ArrayBuffer, byteOffset: number, length: number, dtype?: string ): TypedArray; // tslint:disable-line:max-line-length + +/** +* Returns a filled typed array view of an `ArrayBuffer`. +* +* ## Notes +* +* - Creating a generic array from an `ArrayBuffer` is **not** supported. +* +* @param value - fill value +* @param buffer - `ArrayBuffer` +* @param byteOffset - byte offset +* @param dtype - data type (default: 'float64') +* @throws must provide a recognized data type +* @returns filled array +* +* @example +* var ArrayBuffer = require( `@stdlib/array/buffer` ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = filledarray( 1.0, buf, 8 ); +* // returns [ 1.0, 1.0, 1.0 ] +* +* @example +* var ArrayBuffer = require( `@stdlib/array/buffer` ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = filledarray( 1.0, buf, 8, 'float32' ); +* // returns [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ] +* +*/ +declare function filledarray( value: any, buffer: ArrayBuffer, byteOffset: number, dtype?: string ): TypedArray; // tslint:disable-line:max-line-length + +/** +* Returns a filled typed array view of an `ArrayBuffer`. +* +* ## Notes +* +* - Creating a generic array from an `ArrayBuffer` is **not** supported. +* +* @param value - fill value +* @param buffer - `ArrayBuffer` +* @param dtype - data type (default: 'float64') +* @throws must provide a recognized data type +* @returns filled array +* +* @example +* var ArrayBuffer = require( `@stdlib/array/buffer` ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = filledarray( 1.0, buf ); +* // returns [ 1.0, 1.0, 1.0, 1.0 ] +* +* @example +* var ArrayBuffer = require( `@stdlib/array/buffer` ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = filledarray( 1.0, buf, 'float32' ); +* // returns [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ] +* +*/ +declare function filledarray( value: any, buffer: ArrayBuffer, dtype?: string ): TypedArray; // tslint:disable-line:max-line-length unified-signatures + + +// EXPORTS // + +export = filledarray; diff --git a/filled/docs/types/test.ts b/filled/docs/types/test.ts new file mode 100644 index 00000000..23711735 --- /dev/null +++ b/filled/docs/types/test.ts @@ -0,0 +1,206 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/// + +import { IterableIterator } from '@stdlib/types/iter'; +import filledarray = require( './index' ); + + +/** +* Returns an iterator protocol-compliant object. +* +* @returns iterator protocol-compliant object +*/ +function iterator(): IterableIterator { + const obj: IterableIterator = { + [Symbol.iterator]: iterator, + 'next': next + }; + return obj; +} + +/** +* Implements the iterator protocol `next` method. +* +* @returns iterator protocol-compliant object +*/ +function next(): any { + return { + 'value': 1.0, + 'done': false + }; +} + + +// TESTS // + +// The function returns an array or typed array... +{ + filledarray(); // $ExpectType ArrayOrTypedArray + filledarray( 'float32' ); // $ExpectType ArrayOrTypedArray + + filledarray( 1.0, 10 ); // $ExpectType ArrayOrTypedArray + filledarray( 1.0, 10, 'int32' ); // $ExpectType ArrayOrTypedArray + + const x = new Float64Array( 10 ); + filledarray( 1.0, x ); // $ExpectType ArrayOrTypedArray + filledarray( 1.0, x, 'uint8' ); // $ExpectType ArrayOrTypedArray + + const y = [ 2.0, 2.0, 2.0 ]; + filledarray( 1.0, y ); // $ExpectType ArrayOrTypedArray + filledarray( 1.0, y, 'float64' ); // $ExpectType ArrayOrTypedArray + + const it = iterator(); + filledarray( 1.0, it ); // $ExpectType ArrayOrTypedArray + filledarray( 1.0, it, 'uint8c' ); // $ExpectType ArrayOrTypedArray + + const buf = new ArrayBuffer( 32 ); + filledarray( 1.0, buf ); // $ExpectType TypedArray + filledarray( 1.0, buf, 'uint32' ); // $ExpectType TypedArray + + filledarray( 1.0, buf, 8 ); // $ExpectType TypedArray + filledarray( 1.0, buf, 8, 'uint16' ); // $ExpectType TypedArray + + filledarray( 1.0, buf, 8, 2 ); // $ExpectType TypedArray + filledarray( 1.0, buf, 8, 2, 'int16' ); // $ExpectType TypedArray +} + +// The compiler throws an error if the function is not provided a valid length, typed array, array-like object, or `ArrayBuffer` argument... +{ + filledarray( 1.0, false ); // $ExpectError + filledarray( 1.0, true ); // $ExpectError + filledarray( 1.0, null ); // $ExpectError + filledarray( 1.0, {} ); // $ExpectError + + filledarray( 1.0, false, 'float64' ); // $ExpectError + filledarray( 1.0, true, 'float64' ); // $ExpectError + filledarray( 1.0, null, 'float64' ); // $ExpectError + filledarray( 1.0, undefined, 'float64' ); // $ExpectError + filledarray( 1.0, {}, 'float64' ); // $ExpectError + + filledarray( 1.0, '5', 8 ); // $ExpectError + filledarray( 1.0, 1.0, 8 ); // $ExpectError + filledarray( 1.0, false, 8 ); // $ExpectError + filledarray( 1.0, true, 8 ); // $ExpectError + filledarray( 1.0, null, 8 ); // $ExpectError + filledarray( 1.0, undefined, 8 ); // $ExpectError + filledarray( 1.0, [], 8 ); // $ExpectError + filledarray( 1.0, {}, 8 ); // $ExpectError + filledarray( 1.0, ( x: number ): number => x, 8 ); // $ExpectError + + filledarray( 1.0, '5', 8, 'float64' ); // $ExpectError + filledarray( 1.0, 1.0, 8, 'float64' ); // $ExpectError + filledarray( 1.0, false, 8, 'float64' ); // $ExpectError + filledarray( 1.0, true, 8, 'float64' ); // $ExpectError + filledarray( 1.0, null, 8, 'float64' ); // $ExpectError + filledarray( 1.0, undefined, 8, 'float64' ); // $ExpectError + filledarray( 1.0, [], 8, 'float64' ); // $ExpectError + filledarray( 1.0, {}, 8, 'float64' ); // $ExpectError + filledarray( 1.0, ( x: number ): number => x, 8, 'float64' ); // $ExpectError + + filledarray( 1.0, '5', 8, 2 ); // $ExpectError + filledarray( 1.0, 1.0, 8, 2 ); // $ExpectError + filledarray( 1.0, false, 8, 2 ); // $ExpectError + filledarray( 1.0, true, 8, 2 ); // $ExpectError + filledarray( 1.0, null, 8, 2 ); // $ExpectError + filledarray( 1.0, undefined, 8, 2 ); // $ExpectError + filledarray( 1.0, [], 8, 2 ); // $ExpectError + filledarray( 1.0, {}, 8, 2 ); // $ExpectError + filledarray( 1.0, ( x: number ): number => x, 8, 2 ); // $ExpectError + + filledarray( 1.0, '5', 8, 2, 'float64' ); // $ExpectError + filledarray( 1.0, 1.0, 8, 2, 'float64' ); // $ExpectError + filledarray( 1.0, false, 8, 2, 'float64' ); // $ExpectError + filledarray( 1.0, true, 8, 2, 'float64' ); // $ExpectError + filledarray( 1.0, null, 8, 2, 'float64' ); // $ExpectError + filledarray( 1.0, undefined, 8, 2, 'float64' ); // $ExpectError + filledarray( 1.0, [], 8, 2, 'float64' ); // $ExpectError + filledarray( 1.0, {}, 8, 2, 'float64' ); // $ExpectError + filledarray( 1.0, ( x: number ): number => x, 8, 2, 'float64' ); // $ExpectError +} + +// The compiler throws an error if the function is provided a byte offset argument which is not a number... +{ + const buf = new ArrayBuffer( 32 ); + + filledarray( 1.0, buf, false ); // $ExpectError + filledarray( 1.0, buf, true ); // $ExpectError + filledarray( 1.0, buf, null ); // $ExpectError + filledarray( 1.0, buf, [] ); // $ExpectError + filledarray( 1.0, buf, {} ); // $ExpectError + filledarray( 1.0, buf, ( x: number ): number => x ); // $ExpectError + + filledarray( 1.0, buf, '5', 'float64' ); // $ExpectError + filledarray( 1.0, buf, false, 'float64' ); // $ExpectError + filledarray( 1.0, buf, true, 'float64' ); // $ExpectError + filledarray( 1.0, buf, null, 'float64' ); // $ExpectError + filledarray( 1.0, buf, undefined, 'float64' ); // $ExpectError + filledarray( 1.0, buf, [], 'float64' ); // $ExpectError + filledarray( 1.0, buf, {}, 'float64' ); // $ExpectError + filledarray( 1.0, buf, ( x: number ): number => x, 'float64' ); // $ExpectError +} + +// The compiler throws an error if the function is provided a view length argument which is not a number... +{ + const buf = new ArrayBuffer( 32 ); + + filledarray( 1.0, buf, 8, false ); // $ExpectError + filledarray( 1.0, buf, 8, true ); // $ExpectError + filledarray( 1.0, buf, 8, null ); // $ExpectError + filledarray( 1.0, buf, 8, [] ); // $ExpectError + filledarray( 1.0, buf, 8, {} ); // $ExpectError + filledarray( 1.0, buf, 8, ( x: number ): number => x ); // $ExpectError + + filledarray( 1.0, buf, 8, '5', 'float64' ); // $ExpectError + filledarray( 1.0, buf, 8, false, 'float64' ); // $ExpectError + filledarray( 1.0, buf, 8, true, 'float64' ); // $ExpectError + filledarray( 1.0, buf, 8, null, 'float64' ); // $ExpectError + filledarray( 1.0, buf, 8, undefined, 'float64' ); // $ExpectError + filledarray( 1.0, buf, 8, [], 'float64' ); // $ExpectError + filledarray( 1.0, buf, 8, {}, 'float64' ); // $ExpectError + filledarray( 1.0, buf, 8, ( x: number ): number => x, 'float64' ); // $ExpectError +} + +// The compiler throws an error if the function is not provided a third argument which is a number... +{ + const buf = new ArrayBuffer( 32 ); + + filledarray( 1.0, buf, false ); // $ExpectError + filledarray( 1.0, buf, true ); // $ExpectError + filledarray( 1.0, buf, null ); // $ExpectError + filledarray( 1.0, buf, [] ); // $ExpectError + filledarray( 1.0, buf, {} ); // $ExpectError + filledarray( 1.0, buf, ( x: number ): number => x ); // $ExpectError + + filledarray( 1.0, buf, '5', 'float64' ); // $ExpectError + filledarray( 1.0, buf, false, 'float64' ); // $ExpectError + filledarray( 1.0, buf, true, 'float64' ); // $ExpectError + filledarray( 1.0, buf, null, 'float64' ); // $ExpectError + filledarray( 1.0, buf, undefined, 'float64' ); // $ExpectError + filledarray( 1.0, buf, [], 'float64' ); // $ExpectError + filledarray( 1.0, buf, {}, 'float64' ); // $ExpectError + filledarray( 1.0, buf, ( x: number ): number => x, 'float64' ); // $ExpectError +} + +// The compiler throws an error if the function is provided too many arguments... +{ + const buf = new ArrayBuffer( 32 ); + + filledarray( 1.0, buf, 8, 2, 'float64', 1 ); // $ExpectError +} diff --git a/filled/examples/index.js b/filled/examples/index.js new file mode 100644 index 00000000..b31054f0 --- /dev/null +++ b/filled/examples/index.js @@ -0,0 +1,37 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var discreteUniform = require( '@stdlib/random/base/discrete-uniform' ); +var dtypes = require( '@stdlib/array/dtypes' ); +var filledarray = require( './../lib' ); + +// Generate a random number: +var r = discreteUniform( 0, 100 ); + +// Get the list of supported array data types: +var dt = dtypes(); + +// Generate filled arrays... +var arr; +var i; +for ( i = 0; i < dt.length; i++ ) { + arr = filledarray( r, 10, dt[ i ] ); + console.log( arr ); +} diff --git a/filled/lib/index.js b/filled/lib/index.js new file mode 100644 index 00000000..090d04e4 --- /dev/null +++ b/filled/lib/index.js @@ -0,0 +1,132 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Create a filled array. +* +* @module @stdlib/array/filled +* +* @example +* var filledarray = require( '@stdlib/array/filled' ); +* +* var arr = filledarray(); +* // returns +* +* @example +* var filledarray = require( '@stdlib/array/filled' ); +* +* var arr = filledarray( 1.0, 2 ); +* // returns [ 1.0, 1.0 ] +* +* @example +* var filledarray = require( '@stdlib/array/filled' ); +* +* var arr = filledarray( 1.0, 2, 'float32' ); +* // returns [ 1.0, 1.0 ] +* +* @example +* var filledarray = require( '@stdlib/array/filled' ); +* +* var arr = filledarray( 1.0, 2, 'generic' ); +* // returns [ 1.0, 1.0 ] +* +* @example +* var filledarray = require( '@stdlib/array/filled' ); +* +* var arr = filledarray( 1.0, [ 0.5, 0.5 ] ); +* // returns [ 1.0, 1.0 ] +* +* @example +* var filledarray = require( '@stdlib/array/filled' ); +* +* var arr = filledarray( 1, [ 5, -3 ], 'int32' ); +* // returns [ 1, 1 ] +* +* @example +* var filledarray = require( '@stdlib/array/filled' ); +* +* var arr1 = filledarray( 10, [ 5, 3 ], 'int32' ); +* var arr2 = filledarray( 1.0, arr1 ); +* // returns [ 1.0, 1.0 ] +* +* @example +* var filledarray = require( '@stdlib/array/filled' ); +* +* var arr1 = filledarray( 1, [ 5, 3 ], 'int32' ); +* var arr2 = filledarray( 2, arr1, 'uint32' ); +* // returns [ 2, 2 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* var filledarray = require( '@stdlib/array/filled' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = filledarray( 1.0, buf ); +* // returns [ 1.0, 1.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* var filledarray = require( '@stdlib/array/filled' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = filledarray( 1.0, buf, 'float32' ); +* // returns [ 1.0, 1.0, 1.0, 1.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* var filledarray = require( '@stdlib/array/filled' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = filledarray( 1.0, buf, 8 ); +* // returns [ 1.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* var filledarray = require( '@stdlib/array/filled' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = filledarray( 1.0, buf, 8, 'float32' ); +* // returns [ 1.0, 1.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* var filledarray = require( '@stdlib/array/filled' ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = filledarray( 1.0, buf, 8, 2 ); +* // returns [ 1.0, 1.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* var filledarray = require( '@stdlib/array/filled' ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = filledarray( 1, buf, 8, 2, 'int32' ); +* // returns [ 1, 1 ] +*/ + +// MODULES // + +var filledarray = require( './main.js' ); + + +// EXPORTS // + +module.exports = filledarray; diff --git a/filled/lib/main.js b/filled/lib/main.js new file mode 100644 index 00000000..0b1a999c --- /dev/null +++ b/filled/lib/main.js @@ -0,0 +1,228 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isString = require( '@stdlib/assert/is-string' ).isPrimitive; +var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; +var isCollection = require( '@stdlib/assert/is-collection' ); +var isArrayBuffer = require( '@stdlib/assert/is-arraybuffer' ); +var isObject = require( '@stdlib/assert/is-object' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var hasOwnProp = require( '@stdlib/assert/has-own-property' ); +var ctors = require( '@stdlib/array/ctors' ); +var gfill = require( '@stdlib/blas/ext/base/gfill' ); +var hasIteratorSymbolSupport = require( '@stdlib/assert/has-iterator-symbol-support' ); +var ITERATOR_SYMBOL = require( '@stdlib/symbol/iterator' ); + + +// VARIABLES // + +var HAS_ITERATOR_SYMBOL = hasIteratorSymbolSupport(); + + +// MAIN // + +/** +* Creates a filled array. +* +* @param {*} [value] - fill value +* @param {(NonNegativeInteger|TypedArray|ArrayLikeObject|ArrayBuffer)} [arg] - a length, typed array, array-like object, or buffer +* @param {NonNegativeInteger} [byteOffset=0] - byte offset +* @param {NonNegativeInteger} [length] - view length +* @param {string} [dtype="float64"] - data type +* @throws {TypeError} must provide a recognized data type +* @throws {TypeError} must provide a length, typed array, array-like object, or buffer +* @throws {Error} creating a generic array from an `ArrayBuffer` is not supported +* @returns {(TypedArray|Array)} array or typed array +* +* @example +* var arr = filledarray(); +* // returns +* +* @example +* var arr = filledarray( 1.0, 2 ); +* // returns [ 1.0, 1.0 ] +* +* @example +* var arr = filledarray( 1.0, 2, 'float32' ); +* // returns [ 1.0, 1.0 ] +* +* @example +* var arr = filledarray( 1.0, 2, 'generic' ); +* // returns [ 1.0, 1.0 ] +* +* @example +* var arr = filledarray( 1.0, [ 0.5, 0.5 ] ); +* // returns [ 1.0, 1.0 ] +* +* @example +* var arr = filledarray( 1, [ 5, -3 ], 'int32' ); +* // returns [ 1, 1 ] +* +* @example +* var arr1 = filledarray( 2, [ 5, 3 ], 'int32' ); +* var arr2 = filledarray( 1.0, arr1 ); +* // returns [ 1.0, 1.0 ] +* +* @example +* var arr1 = filledarray( 2, [ 5, 3 ], 'int32' ); +* var arr2 = filledarray( 1, arr1, 'uint32' ); +* // returns [ 1, 1 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = filledarray( 1.0, buf ); +* // returns [ 1.0, 1.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = filledarray( 1.0, buf, 'float32' ); +* // returns [ 1.0, 1.0, 1.0, 1.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = filledarray( 1.0, buf, 8 ); +* // returns [ 1.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = filledarray( 1.0, buf, 8, 'float32' ); +* // returns [ 1.0, 1.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = filledarray( 1.0, buf, 8, 2 ); +* // returns [ 1.0, 1.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = filledarray( 1, buf, 8, 2, 'int32' ); +* // returns [ 1, 1 ] +*/ +function filledarray() { + var value; + var nargs; + var dtype; + var ctor; + var arr; + var len; + var arg; + var v; + var i; + + nargs = arguments.length; + nargs -= 1; + if ( nargs >= 0 && isString( arguments[ nargs ] ) ) { + dtype = arguments[ nargs ]; + nargs -= 1; + } else { + dtype = 'float64'; + } + ctor = ctors( dtype ); + if ( ctor === null ) { + throw new TypeError( 'invalid argument. Must provide a recognized data type. Value: `'+dtype+'`.' ); + } + if ( dtype === 'generic' ) { + if ( nargs <= 0 ) { + return []; + } + value = arguments[ 0 ]; + arg = arguments[ 1 ]; + if ( nargs === 1 ) { + if ( isNonNegativeInteger( arg ) ) { + len = arg; + } else if ( isCollection( arg ) ) { + len = arg.length; + } + if ( len !== void 0 ) { + arr = []; + + // Manually push elements in order to ensure "fast" elements... + for ( i = 0; i < len; i++ ) { + arr.push( value ); + } + return arr; + } + if ( isArrayBuffer( arg ) ) { + throw new Error( 'invalid arguments. Creating a generic array from an ArrayBuffer is not supported.' ); + } + if ( isObject( arg ) ) { + if ( HAS_ITERATOR_SYMBOL === false ) { + throw new TypeError( 'invalid argument. Environment lacks Symbol.iterator support. Must provide a length, typed array, or array-like object. Value: `'+arg+'`.' ); + } + if ( !isFunction( arg[ ITERATOR_SYMBOL ] ) ) { + throw new TypeError( 'invalid argument. Must provide a length, typed array, array-like object, or an iterable. Value: `'+arg+'`.' ); + } + arg = arg[ ITERATOR_SYMBOL ](); + if ( !isFunction( arg.next ) ) { + throw new TypeError( 'invalid argument. Must provide a length, typed array, array-like object, or an iterable.' ); + } + arr = []; + while ( true ) { + v = arg.next(); + if ( hasOwnProp( v, 'value' ) ) { + arr.push( value ); + } + if ( v.done ) { + break; + } + } + return arr; + } + throw new TypeError( 'invalid argument. Must provide a length, typed array, array-like object, or an iterable. Value: `'+arg+'`.' ); + } else if ( isArrayBuffer( arg ) ) { + throw new Error( 'invalid arguments. Creating a generic array from an ArrayBuffer is not supported.' ); + } + throw new TypeError( 'invalid argument. Must provide a length, typed array, array-like object, or an iterable. Value: `'+arg+'`.' ); + } + if ( nargs <= 0 ) { + return new ctor( 0 ); + } + if ( nargs === 1 ) { + arr = new ctor( arguments[1] ); + } else if ( nargs === 2 ) { + arr = new ctor( arguments[1], arguments[2] ); + } else { + arr = new ctor( arguments[1], arguments[2], arguments[3] ); + } + value = arguments[ 0 ]; + if ( arr.length > 0 && value !== 0 ) { // i.e., nonzero + gfill( arr.length, value, arr, 1 ); + } + return arr; +} + + +// EXPORTS // + +module.exports = filledarray; diff --git a/filled/package.json b/filled/package.json new file mode 100644 index 00000000..5334e5b7 --- /dev/null +++ b/filled/package.json @@ -0,0 +1,99 @@ +{ + "name": "@stdlib/array/filled", + "version": "0.0.0", + "description": "Create a filled array.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structure", + "typed", + "array", + "typed array", + "typed-array", + "vector", + "ndarray", + "matrix", + "float64array", + "float32array", + "int32array", + "uint32array", + "int16array", + "uint16array", + "int8array", + "uint8array", + "uint8clampedarray", + "float64", + "double", + "precision", + "double-precision", + "single", + "float", + "single-precision", + "float32", + "ieee754", + "integer", + "int32", + "signed", + "unsigned", + "uint32", + "int16", + "uint16", + "int8", + "uint8", + "uint8c", + "clamped", + "short", + "long", + "generic", + "fill", + "filled" + ] +} diff --git a/filled/test/test.js b/filled/test/test.js new file mode 100644 index 00000000..3a04ffc0 --- /dev/null +++ b/filled/test/test.js @@ -0,0 +1,2059 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var Float64Array = require( '@stdlib/array/float64' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Int8Array = require( '@stdlib/array/int8' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); +var ArrayBuffer = require( '@stdlib/array/buffer' ); +var instanceOf = require( '@stdlib/assert/instance-of' ); +var iterConstant = require( '@stdlib/iter/constant' ); +var hasIteratorSymbolSupport = require( '@stdlib/assert/has-iterator-symbol-support' ); +var filledarray = require( './../lib' ); + + +// VARIABLES // + +var opts = { + 'skip': !hasIteratorSymbolSupport() +}; + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof filledarray, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error if provided an unrecognized data type (one argument)', function test( t ) { + var values; + var i; + + values = [ + '5', + 'beep', + 'filledarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32', + 'GENERIC' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + filledarray( value ); + }; + } +}); + +tape( 'the function throws an error if provided an unrecognized data type (length)', function test( t ) { + var values; + var i; + + values = [ + '5', + 'beep', + 'filledarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32', + 'GENERIC' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + filledarray( 1.0, 10, value ); + }; + } +}); + +tape( 'the function throws an error if provided an unrecognized data type (typed array)', function test( t ) { + var values; + var i; + + values = [ + '5', + 'beep', + 'filledarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32', + 'GENERIC' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + filledarray( 1.0, new Float64Array( 10 ), value ); + }; + } +}); + +tape( 'the function throws an error if provided an unrecognized data type (array-like object)', function test( t ) { + var values; + var i; + + values = [ + '5', + 'beep', + 'filledarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32', + 'GENERIC' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + filledarray( 1.0, [ 1, 2, 3 ], value ); + }; + } +}); + +tape( 'the function throws an error if provided an unrecognized data type (ArrayBuffer)', function test( t ) { + var values; + var i; + + values = [ + '5', + 'beep', + 'filledarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32', + 'GENERIC' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + filledarray( 1.0, new ArrayBuffer( 16 ), value ); + }; + } +}); + +tape( 'the function throws an error if provided an unrecognized data type (ArrayBuffer, byteOffset)', function test( t ) { + var values; + var i; + + values = [ + '5', + 'beep', + 'filledarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32', + 'GENERIC' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + filledarray( 1.0, new ArrayBuffer( 16 ), 0, value ); + }; + } +}); + +tape( 'the function throws an error if provided an unrecognized data type (ArrayBuffer, byteOffset, length)', function test( t ) { + var values; + var i; + + values = [ + '5', + 'beep', + 'filledarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32', + 'GENERIC' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + filledarray( 1.0, new ArrayBuffer( 16 ), 0, 1, value ); + }; + } +}); + +tape( 'the function throws an error if not provided a length, typed array, array-like object, or an iterable when attempting to create a generic array', function test( t ) { + var values; + var i; + + values = [ + '5', + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + filledarray( 1.0, value, 'generic' ); + }; + } +}); + +tape( 'the function throws an error if not provided a length, typed array, array-like object, or an iterable when attempting to create a generic array (no iterator symbol support)', function test( t ) { + var filledarray; + var values; + var i; + + filledarray = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport + }); + + values = [ + '5', + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + filledarray( 1.0, value, 'generic' ); + }; + } + + function hasSupport() { + return false; + } +}); + +tape( 'the function throws an error if not provided a length, typed array, array-like object, or an iterable when attempting to create a generic array (iterator symbol support)', function test( t ) { + var filledarray; + var values; + var i; + + filledarray = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport + }); + + values = [ + '5', + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + filledarray( 1.0, value, 'generic' ); + }; + } + + function hasSupport() { + return true; + } +}); + +tape( 'the function throws an error if not provided a valid iterable when attempting to create a generic array (non-function iterator symbol property)', function test( t ) { + var filledarray; + var values; + var i; + + filledarray = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport, + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ + '5', + 5, + true, + false, + null, + void 0, + {}, + [] + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + var obj = { + '__ITERATOR_SYMBOL__': value + }; + filledarray( 1.0, obj, 'generic' ); + }; + } + + function hasSupport() { + return true; + } +}); + +tape( 'the function throws an error if not provided a valid iterable when attempting to create a generic array (`next` property is not a function)', function test( t ) { + var filledarray; + var values; + var i; + + filledarray = proxyquire( './../lib/main.js', { + '@stdlib/assert/has-iterator-symbol-support': hasSupport, + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ + '5', + 5, + true, + false, + null, + void 0, + {}, + [] + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + var obj = { + '__ITERATOR_SYMBOL__': iterator + }; + filledarray( 1.0, obj, 'generic' ); + }; + + function iterator() { + return { + 'next': value + }; + } + } + + function hasSupport() { + return true; + } +}); + +tape( 'the function throws an error if not provided valid arguments when attempting to create a generic array (arraybuffer, byteoffset)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + true, + false, + null, + void 0, + {}, + [], + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + filledarray( 1.0, value, 1, 'generic' ); + }; + } +}); + +tape( 'the function throws an error if not provided valid arguments when attempting to create a generic array (arraybuffer, byteoffset, length)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + true, + false, + null, + void 0, + {}, + [], + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + filledarray( 1.0, value, 1, 1, 'generic' ); + }; + } +}); + +tape( 'the function returns a filled array (default)', function test( t ) { + var expected; + var arr; + + expected = new Float64Array( 0 ); + + arr = filledarray(); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=float64)', function test( t ) { + var expected; + var arr; + + expected = new Float64Array( 0 ); + + arr = filledarray( 'float64' ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=float32)', function test( t ) { + var expected; + var arr; + + expected = new Float32Array( 0 ); + + arr = filledarray( 'float32' ); + t.strictEqual( instanceOf( arr, Float32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=int32)', function test( t ) { + var expected; + var arr; + + expected = new Int32Array( 0 ); + + arr = filledarray( 'int32' ); + t.strictEqual( instanceOf( arr, Int32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint32)', function test( t ) { + var expected; + var arr; + + expected = new Uint32Array( 0 ); + + arr = filledarray( 'uint32' ); + t.strictEqual( instanceOf( arr, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=int16)', function test( t ) { + var expected; + var arr; + + expected = new Int16Array( 0 ); + + arr = filledarray( 'int16' ); + t.strictEqual( instanceOf( arr, Int16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint16)', function test( t ) { + var expected; + var arr; + + expected = new Uint16Array( 0 ); + + arr = filledarray( 'uint16' ); + t.strictEqual( instanceOf( arr, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=int8)', function test( t ) { + var expected; + var arr; + + expected = new Int8Array( 0 ); + + arr = filledarray( 'int8' ); + t.strictEqual( instanceOf( arr, Int8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint8)', function test( t ) { + var expected; + var arr; + + expected = new Uint8Array( 0 ); + + arr = filledarray( 'uint8' ); + t.strictEqual( instanceOf( arr, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint8c)', function test( t ) { + var expected; + var arr; + + expected = new Uint8ClampedArray( 0 ); + + arr = filledarray( 'uint8c' ); + t.strictEqual( instanceOf( arr, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=generic)', function test( t ) { + var expected; + var arr; + + expected = []; + + arr = filledarray( 'generic' ); + t.strictEqual( instanceOf( arr, Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (default, length)', function test( t ) { + var expected; + var arr; + + expected = new Float64Array( [ 1.0, 1.0, 1.0, 1.0, 1.0 ] ); + + arr = filledarray( 1.0, 5 ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (value=0, default, length)', function test( t ) { + var expected; + var arr; + + expected = new Float64Array( [ 0.0, 0.0, 0.0, 0.0, 0.0 ] ); + + arr = filledarray( 0.0, 5 ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=float64, length)', function test( t ) { + var expected; + var arr; + + expected = new Float64Array( [ 1.0, 1.0, 1.0, 1.0, 1.0 ] ); + + arr = filledarray( 1.0, 5, 'float64' ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (value=0, dtype=float64, length)', function test( t ) { + var expected; + var arr; + + expected = new Float64Array( [ 0.0, 0.0, 0.0, 0.0, 0.0 ] ); + + arr = filledarray( 0.0, 5, 'float64' ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=float32, length)', function test( t ) { + var expected; + var arr; + + expected = new Float32Array( [ 1.0, 1.0, 1.0, 1.0, 1.0 ] ); + + arr = filledarray( 1.0, 5, 'float32' ); + t.strictEqual( instanceOf( arr, Float32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (value=0, dtype=float32, length)', function test( t ) { + var expected; + var arr; + + expected = new Float32Array( [ 0.0, 0.0, 0.0, 0.0, 0.0 ] ); + + arr = filledarray( 0.0, 5, 'float32' ); + t.strictEqual( instanceOf( arr, Float32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=int32, length)', function test( t ) { + var expected; + var arr; + + expected = new Int32Array( [ 1, 1, 1, 1, 1 ] ); + + arr = filledarray( 1, 5, 'int32' ); + t.strictEqual( instanceOf( arr, Int32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (value=0, dtype=int32, length)', function test( t ) { + var expected; + var arr; + + expected = new Int32Array( [ 0, 0, 0, 0, 0 ] ); + + arr = filledarray( 0, 5, 'int32' ); + t.strictEqual( instanceOf( arr, Int32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint32, length)', function test( t ) { + var expected; + var arr; + + expected = new Uint32Array( [ 1, 1, 1, 1, 1 ] ); + + arr = filledarray( 1, 5, 'uint32' ); + t.strictEqual( instanceOf( arr, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (value=0, dtype=uint32, length)', function test( t ) { + var expected; + var arr; + + expected = new Uint32Array( [ 0, 0, 0, 0, 0 ] ); + + arr = filledarray( 0, 5, 'uint32' ); + t.strictEqual( instanceOf( arr, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=int16, length)', function test( t ) { + var expected; + var arr; + + expected = new Int16Array( [ 1, 1, 1, 1, 1 ] ); + + arr = filledarray( 1, 5, 'int16' ); + t.strictEqual( instanceOf( arr, Int16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (value=0, dtype=int16, length)', function test( t ) { + var expected; + var arr; + + expected = new Int16Array( [ 0, 0, 0, 0, 0 ] ); + + arr = filledarray( 0, 5, 'int16' ); + t.strictEqual( instanceOf( arr, Int16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint16, length)', function test( t ) { + var expected; + var arr; + + expected = new Uint16Array( [ 1, 1, 1, 1, 1 ] ); + + arr = filledarray( 1, 5, 'uint16' ); + t.strictEqual( instanceOf( arr, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (value=0, dtype=uint16, length)', function test( t ) { + var expected; + var arr; + + expected = new Uint16Array( [ 0, 0, 0, 0, 0 ] ); + + arr = filledarray( 0, 5, 'uint16' ); + t.strictEqual( instanceOf( arr, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=int8, length)', function test( t ) { + var expected; + var arr; + + expected = new Int8Array( [ 1, 1, 1, 1, 1 ] ); + + arr = filledarray( 1, 5, 'int8' ); + t.strictEqual( instanceOf( arr, Int8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (value=0, dtype=int8, length)', function test( t ) { + var expected; + var arr; + + expected = new Int8Array( [ 0, 0, 0, 0, 0 ] ); + + arr = filledarray( 0, 5, 'int8' ); + t.strictEqual( instanceOf( arr, Int8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint8, length)', function test( t ) { + var expected; + var arr; + + expected = new Uint8Array( [ 1, 1, 1, 1, 1 ] ); + + arr = filledarray( 1, 5, 'uint8' ); + t.strictEqual( instanceOf( arr, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (value=0, dtype=uint8, length)', function test( t ) { + var expected; + var arr; + + expected = new Uint8Array( [ 0, 0, 0, 0, 0 ] ); + + arr = filledarray( 0, 5, 'uint8' ); + t.strictEqual( instanceOf( arr, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint8c, length)', function test( t ) { + var expected; + var arr; + + expected = new Uint8ClampedArray( [ 1, 1, 1, 1, 1 ] ); + + arr = filledarray( 1, 5, 'uint8c' ); + t.strictEqual( instanceOf( arr, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (value=0, dtype=uint8c, length)', function test( t ) { + var expected; + var arr; + + expected = new Uint8ClampedArray( [ 0, 0, 0, 0, 0 ] ); + + arr = filledarray( 0, 5, 'uint8c' ); + t.strictEqual( instanceOf( arr, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=generic, length)', function test( t ) { + var expected; + var arr; + + expected = [ 1, 1, 1, 1, 1 ]; + + arr = filledarray( 1, 5, 'generic' ); + t.strictEqual( instanceOf( arr, Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (value=0, dtype=generic, length)', function test( t ) { + var expected; + var arr; + + expected = [ 0, 0, 0, 0, 0 ]; + + arr = filledarray( 0, 5, 'generic' ); + t.strictEqual( instanceOf( arr, Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, expected.length, 'returns expected value' ); + t.deepEqual( arr, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (default, array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Float64Array( [ 1.0, 1.0, 1.0 ] ); + + arr = [ 1.0, 2.0, 3.0 ]; + out = filledarray( 1.0, arr ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=float64, array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Float64Array( [ 1.0, 1.0, 1.0 ] ); + + arr = [ 1.0, 2.0, 3.0 ]; + out = filledarray( 1.0, arr, 'float64' ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=float32, array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Float32Array( [ 1.0, 1.0, 1.0 ] ); + + arr = [ 1.0, 2.0, 3.0 ]; + out = filledarray( 1.0, arr, 'float32' ); + t.strictEqual( instanceOf( out, Float32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=int32, array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Int32Array( [ 1, 1, 1 ] ); + + arr = [ 1.0, 2.0, 3.0 ]; + out = filledarray( 1, arr, 'int32' ); + t.strictEqual( instanceOf( out, Int32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint32, array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Uint32Array( [ 1, 1, 1 ] ); + + arr = [ 1.0, 2.0, 3.0 ]; + out = filledarray( 1, arr, 'uint32' ); + t.strictEqual( instanceOf( out, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=int16, array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Int16Array( [ 1, 1, 1 ] ); + + arr = [ 1.0, 2.0, 3.0 ]; + out = filledarray( 1, arr, 'int16' ); + t.strictEqual( instanceOf( out, Int16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint16, array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Uint16Array( [ 1, 1, 1 ] ); + + arr = [ 1.0, 2.0, 3.0 ]; + out = filledarray( 1, arr, 'uint16' ); + t.strictEqual( instanceOf( out, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=int8, array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Int8Array( [ 1, 1, 1 ] ); + + arr = [ 1.0, 2.0, 3.0 ]; + out = filledarray( 1, arr, 'int8' ); + t.strictEqual( instanceOf( out, Int8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint8, array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Uint8Array( [ 1, 1, 1 ] ); + + arr = [ 1.0, 2.0, 3.0 ]; + out = filledarray( 1, arr, 'uint8' ); + t.strictEqual( instanceOf( out, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint8c, array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Uint8ClampedArray( [ 1, 1, 1 ] ); + + arr = [ 1.0, 2.0, 3.0 ]; + out = filledarray( 1, arr, 'uint8c' ); + t.strictEqual( instanceOf( out, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=generic, array)', function test( t ) { + var expected; + var arr; + var out; + + expected = [ 1.0, 1.0, 1.0 ]; + + arr = [ 1.0, 2.0, 3.0 ]; + out = filledarray( 1.0, arr, 'generic' ); + t.strictEqual( instanceOf( out, Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (default, typed array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Float64Array( [ 1.0, 1.0, 1.0 ] ); + + arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + out = filledarray( 1.0, arr ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=float64, typed array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Float64Array( [ 1.0, 1.0, 1.0 ] ); + + arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + out = filledarray( 1.0, arr, 'float64' ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=float32, typed array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Float32Array( [ 1.0, 1.0, 1.0 ] ); + + arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + out = filledarray( 1.0, arr, 'float32' ); + t.strictEqual( instanceOf( out, Float32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=int32, typed array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Int32Array( [ 1, 1, 1 ] ); + + arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + out = filledarray( 1, arr, 'int32' ); + t.strictEqual( instanceOf( out, Int32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint32, typed array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Uint32Array( [ 1, 1, 1 ] ); + + arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + out = filledarray( 1, arr, 'uint32' ); + t.strictEqual( instanceOf( out, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=int16, typed array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Int16Array( [ 1, 1, 1 ] ); + + arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + out = filledarray( 1, arr, 'int16' ); + t.strictEqual( instanceOf( out, Int16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint16, typed array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Uint16Array( [ 1, 1, 1 ] ); + + arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + out = filledarray( 1, arr, 'uint16' ); + t.strictEqual( instanceOf( out, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=int8, typed array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Int8Array( [ 1, 1, 1 ] ); + + arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + out = filledarray( 1, arr, 'int8' ); + t.strictEqual( instanceOf( out, Int8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint8, typed array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Uint8Array( [ 1, 1, 1 ] ); + + arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + out = filledarray( 1, arr, 'uint8' ); + t.strictEqual( instanceOf( out, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint8c, typed array)', function test( t ) { + var expected; + var arr; + var out; + + expected = new Uint8ClampedArray( [ 1, 1, 1 ] ); + + arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + out = filledarray( 1, arr, 'uint8c' ); + t.strictEqual( instanceOf( out, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=generic, typed array)', function test( t ) { + var expected; + var arr; + var out; + + expected = [ 1.0, 1.0, 1.0 ]; + + arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + out = filledarray( 1.0, arr, 'generic' ); + t.strictEqual( instanceOf( out, Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (default, arraybuffer)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Float64Array( [ 1.0 ] ); + + buf = new ArrayBuffer( 8 ); + out = filledarray( 1.0, buf ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=float64, arraybuffer)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Float64Array( [ 1.0 ] ); + + buf = new ArrayBuffer( 8 ); + out = filledarray( 1.0, buf, 'float64' ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=float32, arraybuffer)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Float32Array( [ 1.0, 1.0 ] ); + + buf = new ArrayBuffer( 8 ); + out = filledarray( 1.0, buf, 'float32' ); + t.strictEqual( instanceOf( out, Float32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=int32, arraybuffer)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Int32Array( [ 1, 1 ] ); + + buf = new ArrayBuffer( 8 ); + out = filledarray( 1, buf, 'int32' ); + t.strictEqual( instanceOf( out, Int32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=uint32, arraybuffer)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Uint32Array( [ 1, 1 ] ); + + buf = new ArrayBuffer( 8 ); + out = filledarray( 1, buf, 'uint32' ); + t.strictEqual( instanceOf( out, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=int16, arraybuffer)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Int16Array( [ 1, 1, 1, 1 ] ); + + buf = new ArrayBuffer( 8 ); + out = filledarray( 1, buf, 'int16' ); + t.strictEqual( instanceOf( out, Int16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=uint16, arraybuffer)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Uint16Array( [ 1, 1, 1, 1 ] ); + + buf = new ArrayBuffer( 8 ); + out = filledarray( 1, buf, 'uint16' ); + t.strictEqual( instanceOf( out, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=int8, arraybuffer)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Int8Array( [ 1, 1, 1, 1, 1, 1, 1, 1 ] ); + + buf = new ArrayBuffer( 8 ); + out = filledarray( 1, buf, 'int8' ); + t.strictEqual( instanceOf( out, Int8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=uint8, arraybuffer)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Uint8Array( [ 1, 1, 1, 1, 1, 1, 1, 1 ] ); + + buf = new ArrayBuffer( 8 ); + out = filledarray( 1, buf, 'uint8' ); + t.strictEqual( instanceOf( out, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=uint8c, arraybuffer)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Uint8ClampedArray( [ 1, 1, 1, 1, 1, 1, 1, 1 ] ); + + buf = new ArrayBuffer( 8 ); + out = filledarray( 1, buf, 'uint8c' ); + t.strictEqual( instanceOf( out, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function throws an error if provided an ArrayBuffer when attempting to create a generic array (dtype=generic, arraybuffer)', function test( t ) { + t.throws( foo, Error, 'throws an error' ); + t.end(); + + function foo() { + var buf = new ArrayBuffer( 8 ); + return filledarray( 1, buf, 'generic' ); + } +}); + +tape( 'the function returns a filled typed array (default, arraybuffer, byteoffset)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Float64Array( [ 1.0, 1.0, 1.0 ] ); + + buf = new ArrayBuffer( 32 ); + out = filledarray( 1.0, buf, 8 ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=float64, arraybuffer, byteoffset)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Float64Array( [ 1.0, 1.0, 1.0 ] ); + + buf = new ArrayBuffer( 32 ); + out = filledarray( 1.0, buf, 8, 'float64' ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=float32, arraybuffer, byteoffset)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Float32Array( [ 1.0, 1.0, 1.0 ] ); + + buf = new ArrayBuffer( 16 ); + out = filledarray( 1.0, buf, 4, 'float32' ); + t.strictEqual( instanceOf( out, Float32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=int32, arraybuffer, byteoffset)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Int32Array( [ 1, 1, 1 ] ); + + buf = new ArrayBuffer( 16 ); + out = filledarray( 1, buf, 4, 'int32' ); + t.strictEqual( instanceOf( out, Int32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=uint32, arraybuffer, byteoffset)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Uint32Array( [ 1, 1, 1 ] ); + + buf = new ArrayBuffer( 16 ); + out = filledarray( 1, buf, 4, 'uint32' ); + t.strictEqual( instanceOf( out, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=int16, arraybuffer, byteoffset)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Int16Array( [ 1, 1, 1, 1, 1, 1 ] ); + + buf = new ArrayBuffer( 16 ); + out = filledarray( 1, buf, 4, 'int16' ); + t.strictEqual( instanceOf( out, Int16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=uint16, arraybuffer, byteoffset)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Uint16Array( [ 1, 1, 1, 1, 1, 1 ] ); + + buf = new ArrayBuffer( 16 ); + out = filledarray( 1, buf, 4, 'uint16' ); + t.strictEqual( instanceOf( out, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=int8, arraybuffer, byteoffset)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Int8Array( [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] ); + + buf = new ArrayBuffer( 16 ); + out = filledarray( 1, buf, 4, 'int8' ); + t.strictEqual( instanceOf( out, Int8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=uint8, arraybuffer, byteoffset)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Uint8Array( [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] ); + + buf = new ArrayBuffer( 16 ); + out = filledarray( 1, buf, 4, 'uint8' ); + t.strictEqual( instanceOf( out, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=uint8c, arraybuffer, byteoffset)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Uint8ClampedArray( [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] ); + + buf = new ArrayBuffer( 16 ); + out = filledarray( 1, buf, 4, 'uint8c' ); + t.strictEqual( instanceOf( out, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function throws an error if provided an ArrayBuffer when attempting to create a generic array (dtype=generic, arraybuffer, byteoffset)', function test( t ) { + t.throws( foo, Error, 'throws an error' ); + t.end(); + + function foo() { + var buf = new ArrayBuffer( 8 ); + return filledarray( 1, buf, 4, 'generic' ); + } +}); + +tape( 'the function returns a filled typed array (default, arraybuffer, byteoffset, length)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Float64Array( [ 1.0, 1.0 ] ); + + buf = new ArrayBuffer( 32 ); + out = filledarray( 1.0, buf, 8, 2 ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=float64, arraybuffer, byteoffset, length)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Float64Array( [ 1.0, 1.0 ] ); + + buf = new ArrayBuffer( 32 ); + out = filledarray( 1.0, buf, 8, 2, 'float64' ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=float32, arraybuffer, byteoffset, length)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Float32Array( [ 1.0, 1.0 ] ); + + buf = new ArrayBuffer( 16 ); + out = filledarray( 1.0, buf, 4, 2, 'float32' ); + t.strictEqual( instanceOf( out, Float32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int32, arraybuffer, byteoffset, length)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Int32Array( [ 1, 1 ] ); + + buf = new ArrayBuffer( 16 ); + out = filledarray( 1, buf, 4, 2, 'int32' ); + t.strictEqual( instanceOf( out, Int32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=uint32, arraybuffer, byteoffset, length)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Uint32Array( [ 1, 1 ] ); + + buf = new ArrayBuffer( 16 ); + out = filledarray( 1, buf, 4, 2, 'uint32' ); + t.strictEqual( instanceOf( out, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=int16, arraybuffer, byteoffset, length)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Int16Array( [ 1, 1 ] ); + + buf = new ArrayBuffer( 16 ); + out = filledarray( 1, buf, 4, 2, 'int16' ); + t.strictEqual( instanceOf( out, Int16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=uint16, arraybuffer, byteoffset, length)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Uint16Array( [ 1, 1 ] ); + + buf = new ArrayBuffer( 16 ); + out = filledarray( 1, buf, 4, 2, 'uint16' ); + t.strictEqual( instanceOf( out, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=int8, arraybuffer, byteoffset, length)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Int8Array( [ 1, 1 ] ); + + buf = new ArrayBuffer( 16 ); + out = filledarray( 1, buf, 4, 2, 'int8' ); + t.strictEqual( instanceOf( out, Int8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=uint8, arraybuffer, byteoffset, length)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Uint8Array( [ 1, 1 ] ); + + buf = new ArrayBuffer( 16 ); + out = filledarray( 1, buf, 4, 2, 'uint8' ); + t.strictEqual( instanceOf( out, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled typed array (dtype=uint8c, arraybuffer, byteoffset, length)', function test( t ) { + var expected; + var buf; + var out; + + expected = new Uint8ClampedArray( [ 1, 1 ] ); + + buf = new ArrayBuffer( 16 ); + out = filledarray( 1, buf, 4, 2, 'uint8c' ); + t.strictEqual( instanceOf( out, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function throws an error if provided an ArrayBuffer when attempting to create a generic array (dtype=generic, arraybuffer, byteoffset, length)', function test( t ) { + t.throws( foo, Error, 'throws an error' ); + t.end(); + + function foo() { + var buf = new ArrayBuffer( 8 ); + return filledarray( 1, buf, 4, 1, 'generic' ); + } +}); + +tape( 'the function returns a filled array (default, iterator)', opts, function test( t ) { + var expected; + var arr; + var out; + + expected = new Float64Array( [ 1.0, 1.0, 1.0 ] ); + + arr = iterConstant( 3.0, { + 'iter': 3 + }); + out = filledarray( 1.0, arr ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=float64, iterator)', opts, function test( t ) { + var expected; + var arr; + var out; + + expected = new Float64Array( [ 1.0, 1.0, 1.0 ] ); + + arr = iterConstant( 3.0, { + 'iter': 3 + }); + out = filledarray( 1.0, arr, 'float64' ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=float32, iterator)', opts, function test( t ) { + var expected; + var arr; + var out; + + expected = new Float32Array( [ 1.0, 1.0, 1.0 ] ); + + arr = iterConstant( 3.0, { + 'iter': 3 + }); + out = filledarray( 1.0, arr, 'float32' ); + t.strictEqual( instanceOf( out, Float32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=int32, iterator)', opts, function test( t ) { + var expected; + var arr; + var out; + + expected = new Int32Array( [ 1, 1, 1 ] ); + + arr = iterConstant( 3, { + 'iter': 3 + }); + out = filledarray( 1, arr, 'int32' ); + t.strictEqual( instanceOf( out, Int32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint32, iterator)', opts, function test( t ) { + var expected; + var arr; + var out; + + expected = new Uint32Array( [ 1, 1, 1 ] ); + + arr = iterConstant( 3, { + 'iter': 3 + }); + out = filledarray( 1, arr, 'uint32' ); + t.strictEqual( instanceOf( out, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=int16, iterator)', opts, function test( t ) { + var expected; + var arr; + var out; + + expected = new Int16Array( [ 1, 1, 1 ] ); + + arr = iterConstant( 3, { + 'iter': 3 + }); + out = filledarray( 1, arr, 'int16' ); + t.strictEqual( instanceOf( out, Int16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint16, iterator)', opts, function test( t ) { + var expected; + var arr; + var out; + + expected = new Uint16Array( [ 1, 1, 1 ] ); + + arr = iterConstant( 3, { + 'iter': 3 + }); + out = filledarray( 1, arr, 'uint16' ); + t.strictEqual( instanceOf( out, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=int8, iterator)', opts, function test( t ) { + var expected; + var arr; + var out; + + expected = new Int8Array( [ 1, 1, 1 ] ); + + arr = iterConstant( 3, { + 'iter': 3 + }); + out = filledarray( 1, arr, 'int8' ); + t.strictEqual( instanceOf( out, Int8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint8, iterator)', opts, function test( t ) { + var expected; + var arr; + var out; + + expected = new Uint8Array( [ 1, 1, 1 ] ); + + arr = iterConstant( 3, { + 'iter': 3 + }); + out = filledarray( 1, arr, 'uint8' ); + t.strictEqual( instanceOf( out, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=uint8c, iterator)', opts, function test( t ) { + var expected; + var arr; + var out; + + expected = new Uint8ClampedArray( [ 1, 1, 1 ] ); + + arr = iterConstant( 3, { + 'iter': 3 + }); + out = filledarray( 1, arr, 'uint8c' ); + t.strictEqual( instanceOf( out, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns a filled array (dtype=generic, iterator)', opts, function test( t ) { + var expected; + var arr; + var out; + + expected = [ 1.0, 1.0, 1.0 ]; + + arr = iterConstant( 3, { + 'iter': 3 + }); + out = filledarray( 1.0, arr, 'generic' ); + t.strictEqual( instanceOf( out, Array ), true, 'returns expected value' ); + t.strictEqual( out.length, expected.length, 'returns expected value' ); + t.deepEqual( out, expected, 'returns expected value' ); + + t.end(); +}); diff --git a/float32/README.md b/float32/README.md new file mode 100644 index 00000000..65e84104 --- /dev/null +++ b/float32/README.md @@ -0,0 +1,1444 @@ + + +# Float32Array + +> [Typed array][mdn-typed-array] constructor which returns a [typed array][mdn-typed-array] representing an array of single-precision floating-point numbers in the platform byte order. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var Float32Array = require( '@stdlib/array/float32' ); +``` + +#### Float32Array() + +A [typed array][mdn-typed-array] constructor which returns a [typed array][mdn-typed-array] representing an array of single-precision floating-point numbers in the platform byte order. + + + +```javascript +var arr = new Float32Array(); +// returns +``` + +#### Float32Array( length ) + +Returns a [typed array][mdn-typed-array] having a specified length. + + + +```javascript +var arr = new Float32Array( 5 ); +// returns [ 0.0, 0.0, 0.0, 0.0, 0.0 ] +``` + +#### Float32Array( typedarray ) + +Creates a [typed array][mdn-typed-array] from another [typed array][mdn-typed-array]. + + + +```javascript +var Float64Array = require( '@stdlib/array/float64' ); + +var arr1 = new Float64Array( [ 0.5, 0.5, 0.5 ] ); +var arr2 = new Float32Array( arr1 ); +// returns [ 0.5, 0.5, 0.5 ] +``` + +#### Float32Array( obj ) + +Creates a [typed array][mdn-typed-array] from an array-like `object` or iterable. + + + +```javascript +var arr = new Float32Array( [ 0.5, 0.5, 0.5 ] ); +// returns [ 0.5, 0.5, 0.5 ] +``` + +#### Float32Array( buffer\[, byteOffset\[, length]] ) + +Returns a [typed array][mdn-typed-array] view of an [`ArrayBuffer`][@stdlib/array/buffer]. + + + +```javascript +var ArrayBuffer = require( '@stdlib/array/buffer' ); + +var buf = new ArrayBuffer( 16 ); +var arr = new Float32Array( buf, 0, 4 ); +// returns [ 0.0, 0.0, 0.0, 0.0 ] +``` + +* * * + +### Properties + + + +#### Float32Array.BYTES_PER_ELEMENT + +Number of bytes per view element. + + + +```javascript +var nbytes = Float32Array.BYTES_PER_ELEMENT; +// returns 4 +``` + + + +#### Float32Array.name + +[Typed array][mdn-typed-array] constructor name. + + + +```javascript +var str = Float32Array.name; +// returns 'Float32Array' +``` + + + +#### Float32Array.prototype.buffer + +**Read-only** property which returns the [`ArrayBuffer`][@stdlib/array/buffer] referenced by the [typed array][mdn-typed-array]. + + + +```javascript +var arr = new Float32Array( 5 ); +var buf = arr.buffer; +// returns +``` + + + +#### Float32Array.prototype.byteLength + +**Read-only** property which returns the length (in bytes) of the [typed array][mdn-typed-array]. + + + +```javascript +var arr = new Float32Array( 5 ); +var byteLength = arr.byteLength; +// returns 20 +``` + + + +#### Float32Array.prototype.byteOffset + +**Read-only** property which returns the offset (in bytes) of the [typed array][mdn-typed-array] from the start of its [`ArrayBuffer`][@stdlib/array/buffer]. + + + +```javascript +var arr = new Float32Array( 5 ); +var byteOffset = arr.byteOffset; +// returns 0 +``` + + + +#### Float32Array.prototype.BYTES_PER_ELEMENT + +Number of bytes per view element. + + + +```javascript +var arr = new Float32Array( 5 ); +var nbytes = arr.BYTES_PER_ELEMENT; +// returns 4 +``` + + + +#### Float32Array.prototype.length + +**Read-only** property which returns the number of view elements. + + + +```javascript +var arr = new Float32Array( 5 ); +var len = arr.length; +// returns 5 +``` + +* * * + +### Methods + + + +#### Float32Array.from( src\[, map\[, thisArg]] ) + +Creates a new typed array from an array-like `object` or an iterable. + + + +```javascript +var arr = Float32Array.from( [ 1.0, 2.0 ] ); +// returns [ 1.0, 2.0 ] +``` + +To invoke a function for each `src` value, provide a callback function. + + + +```javascript +function mapFcn( v ) { + return v * 2.0; +} + +var arr = Float32Array.from( [ 1.0, 2.0 ], mapFcn ); +// returns [ 2.0, 4.0 ] +``` + +A callback function is provided two arguments: + +- `value`: source value +- `index`: source index + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function mapFcn( v ) { + this.count += 1; + return v * 2.0; +} + +var ctx = { + 'count': 0 +}; + +var arr = Float32Array.from( [ 1.0, 2.0 ], mapFcn, ctx ); +// returns [ 2.0, 4.0 ] + +var n = ctx.count; +// returns 2 +``` + + + +#### Float32Array.of( element0\[, element1\[, ...elementN]] ) + +Creates a new typed array from a variable number of arguments. + + + +```javascript +var arr = Float32Array.of( 1.0, 2.0 ); +// returns [ 1.0, 2.0 ] +``` + + + +#### Float32Array.prototype.copyWithin( target, start\[, end] ) + +Copies a sequence of elements within an array starting at `start` and ending at `end` (non-inclusive) to the position starting at `target`. + + + +```javascript +var arr = new Float32Array( [ 1.0, 2.0, 3.0, 4.0, 5.0 ] ); + +// Copy the last two elements to the first two elements: +arr.copyWithin( 0, 3 ); + +var v = arr[ 0 ]; +// returns 4.0 + +v = arr[ 1 ]; +// returns 5.0 +``` + +By default, `end` equals the number of array elements (i.e., one more than the last array index). To limit the sequence length, provide an `end` argument. + + + +```javascript +var arr = new Float32Array( [ 1.0, 2.0, 3.0, 4.0, 5.0 ] ); + +// Copy the first two elements to the last two elements: +arr.copyWithin( 3, 0, 2 ); + +var v = arr[ 3 ]; +// returns 1.0 + +v = arr[ 4 ]; +// returns 2.0 +``` + +When a `target`, `start`, and/or `end` index is negative, the respective index is determined relative to the last array element. The following example achieves the same behavior as the previous example: + + + +```javascript +var arr = new Float32Array( [ 1.0, 2.0, 3.0, 4.0, 5.0 ] ); + +// Copy the first two elements to the last two elements: +arr.copyWithin( -2, -5, -3 ); + +var v = arr[ 3 ]; +// returns 1.0 + +v = arr[ 4 ]; +// returns 2.0 +``` + + + +#### Float32Array.prototype.entries() + +Returns an iterator for iterating over array key-value pairs. + + + +```javascript +var arr = new Float32Array( [ 1.0, 2.0 ] ); + +// Create an iterator: +var it = arr.entries(); + +// Iterate over key-value pairs... +var v = it.next().value; +// returns [ 0, 1.0 ] + +v = it.next().value; +// returns [ 1, 2.0 ] + +var bool = it.next().done; +// returns true +``` + + + +#### Float32Array.prototype.every( predicate\[, thisArg] ) + +Tests whether all array elements pass a test implemented by a `predicate` function. + + + +```javascript +function predicate( v ) { + return ( v <= 1.0 ); +} + +var arr = new Float32Array( [ 1.0, 2.0 ] ); + +var bool = arr.every( predicate ); +// returns false +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 1.0 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Float32Array( [ 1.0, 2.0 ] ); + +var bool = arr.every( predicate, ctx ); +// returns true + +var n = ctx.count; +// returns 2 +``` + + + +#### Float32Array.prototype.fill( value\[, start\[, end]] ) + +Fills an array from a `start` index to an `end` index (non-inclusive) with a provided `value`. + + + +```javascript +var arr = new Float32Array( 2 ); + +// Set all array elements to the same value: +arr.fill( 2.0 ); + +var v = arr[ 0 ]; +// returns 2.0 + +v = arr[ 1 ]; +// returns 2.0 + +// Set all array elements starting from the first index to the same value: +arr.fill( 3.0, 1 ); + +v = arr[ 0 ]; +// returns 2.0 + +v = arr[ 1 ]; +// returns 3.0 + +// Set all array elements, except the last element, to the same value: +arr.fill( 4.0, 0, arr.length-1 ); + +v = arr[ 0 ]; +// returns 4.0 + +v = arr[ 1 ]; +// returns 3.0 +``` + +When a `start` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr = new Float32Array( 2 ); + +// Set all array elements, except the last element, to the same value: +arr.fill( 2.0, -arr.length, -1 ); + +var v = arr[ 0 ]; +// returns 2.0 + +v = arr[ 1 ]; +// returns 0.0 +``` + + + +#### Float32Array.prototype.filter( predicate\[, thisArg] ) + +Creates a new array (of the same data type as the host array) which includes those elements for which a `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v >= 2.0 ); +} + +var arr1 = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.filter( predicate ); +// returns [ 2.0, 3.0 ] +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns an empty array. + + + +```javascript +function predicate( v ) { + return ( v >= 10.0 ); +} + +var arr1 = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.filter( predicate ); +// returns [] +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 2.0 ); +} + +var ctx = { + 'count': 0 +}; + +var arr1 = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.filter( predicate, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Float32Array.prototype.find( predicate\[, thisArg] ) + +Returns the first array element for which a provided `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v > 2.0 ); +} + +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var v = arr.find( predicate ); +// returns 3.0 +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns `undefined`. + + + +```javascript +function predicate( v ) { + return ( v < 1.0 ); +} + +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var v = arr.find( predicate ); +// returns undefined +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v > 2.0 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var v = arr.find( predicate, ctx ); +// returns 3.0 + +var n = ctx.count; +// returns 3 +``` + + + +#### Float32Array.prototype.findIndex( predicate\[, thisArg] ) + +Returns the index of the first array element for which a provided `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v >= 3.0 ); +} + +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var idx = arr.findIndex( predicate ); +// returns 2 +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns `-1`. + + + +```javascript +function predicate( v ) { + return ( v < 1.0 ); +} + +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var idx = arr.findIndex( predicate ); +// returns -1 +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 3.0 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var idx = arr.findIndex( predicate, ctx ); +// returns 2 + +var n = ctx.count; +// returns 3 +``` + + + +#### Float32Array.prototype.forEach( fcn\[, thisArg] ) + +Invokes a callback for each array element. + + + +```javascript +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var str = ''; + +function fcn( v, i ) { + str += i + ':' + v; + if ( i < arr.length-1 ) { + str += ' '; + } +} + +arr.forEach( fcn ); + +console.log( str ); +// => '0:1 1:2 2:3' +``` + +The callback is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function fcn() { + this.count += 1; +} + +var ctx = { + 'count': 0 +}; + +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +arr.forEach( fcn, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Float32Array.prototype.includes( searchElement\[, fromIndex] ) + +Returns a `boolean` indicating whether an array includes a search element. + + + +```javascript +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var bool = arr.includes( 3.0 ); +// returns true + +bool = arr.includes( 0.0 ); +// returns false +``` + +By default, the method searches the entire array (`fromIndex = 0`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var bool = arr.includes( 1.0, 1 ); +// returns false +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +bool = arr.includes( 1.0, -2 ); +// returns false +``` + +The method does **not** distinguish between signed and unsigned zero. + + + +#### Float32Array.prototype.indexOf( searchElement\[, fromIndex] ) + +Returns the index of the first array element strictly equal to a search element. + + + +```javascript +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var idx = arr.indexOf( 3.0 ); +// returns 2 + +idx = arr.indexOf( 0.0 ); +// returns -1 +``` + +By default, the method searches the entire array (`fromIndex = 0`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var idx = arr.indexOf( 1.0, 1 ); +// returns -1 +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var idx = arr.indexOf( 1.0, -2 ); +// returns -1 +``` + +The method does **not** distinguish between signed and unsigned zero. + + + +#### Float32Array.prototype.join( \[separator] ) + +Serializes an array by joining all array elements as a string. + + + +```javascript +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var str = arr.join(); +// returns '1,2,3' +``` + +By default, the method delineates array elements using a comma `,`. To specify a custom separator, provide a `separator` string. + + + +```javascript +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var str = arr.join( '|' ); +// returns '1|2|3' +``` + + + +#### Float32Array.prototype.keys() + +Returns an iterator for iterating over array keys. + + + +```javascript +var arr = new Float32Array( [ 1.0, 2.0 ] ); + +// Create an iterator: +var it = arr.keys(); + +// Iterate over keys... +var v = it.next().value; +// returns 0 + +v = it.next().value; +// returns 1 + +var bool = it.next().done; +// returns true +``` + + + +#### Float32Array.prototype.lastIndexOf( searchElement\[, fromIndex] ) + +Returns the index of the last array element strictly equal to a search element, iterating from right to left. + + + +```javascript +var arr = new Float32Array( [ 1.0, 0.0, 2.0, 0.0, 1.0 ] ); + +var idx = arr.lastIndexOf( 0.0 ); +// returns 3 + +idx = arr.lastIndexOf( 3.0 ); +// returns -1 +``` + +By default, the method searches the entire array (`fromIndex = -1`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Float32Array( [ 1.0, 0.0, 2.0, 0.0, 1.0 ] ); + +var idx = arr.lastIndexOf( 0.0, 2 ); +// returns 1 +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Float32Array( [ 1.0, 0.0, 2.0, 0.0, 1.0 ] ); + +var idx = arr.lastIndexOf( 0.0, -3 ); +// returns 1 +``` + +The method does **not** distinguish between signed and unsigned zero. + + + +#### Float32Array.prototype.map( fcn\[, thisArg] ) + +Maps each array element to an element in a new array having the same data type as the host array. + + + +```javascript +function fcn( v ) { + return v * 2.0; +} + +var arr1 = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.map( fcn ); +// returns [ 2.0, 4.0, 6.0 ] +``` + +A callback is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function fcn( v ) { + this.count += 1; + return v * 2.0; +} + +var ctx = { + 'count': 0 +}; + +var arr1 = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.map( fcn, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Float32Array.prototype.reduce( fcn\[, initialValue] ) + +Applies a function against an accumulator and each element in an array and returns the accumulated result. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Float32Array( [ 2.0, 1.0, 3.0 ] ); + +var v = arr.reduce( fcn ); +// returns 12.0 +``` + +If not provided an initial value, the method invokes a provided function with the first array element as the first argument and the second array element as the second argument. + +If provided an initial value, the method invokes a provided function with the initial value as the first argument and the first array element as the second argument. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Float32Array( [ 2.0, 1.0, 3.0 ] ); + +var v = arr.reduce( fcn, 0.0 ); +// returns 14.0 +``` + +A callback is provided four arguments: + +- `acc`: accumulated result +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + + + +#### Float32Array.prototype.reduceRight( fcn\[, initialValue] ) + +Applies a function against an accumulator and each element in an array and returns the accumulated result, iterating from right to left. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Float32Array( [ 2.0, 1.0, 3.0 ] ); + +var v = arr.reduceRight( fcn ); +// returns 8.0 +``` + +If not provided an initial value, the method invokes a provided function with the last array element as the first argument and the second-to-last array element as the second argument. + +If provided an initial value, the method invokes a provided function with the initial value as the first argument and the last array element as the second argument. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Float32Array( [ 2.0, 1.0, 3.0 ] ); + +var v = arr.reduce( fcn, 0.0 ); +// returns 14.0 +``` + +A callback is provided four arguments: + +- `acc`: accumulated result +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + + + +#### Float32Array.prototype.reverse() + +Reverses an array **in-place** (thus mutating the array on which the method is invoked). + + + +```javascript +var arr = new Float32Array( [ 2.0, 0.0, 3.0 ] ); + +// Reverse the array: +arr.reverse(); + +var v = arr[ 0 ]; +// returns 3.0 + +v = arr[ 1 ]; +// returns 0.0 + +v = arr[ 2 ]; +// returns 2.0 +``` + + + +#### Float32Array.prototype.set( arr\[, offset] ) + +Sets array elements. + + + +```javascript +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); +// returns [ 1.0, 2.0, 3.0 ] + +// Set the first two array elements: +arr.set( [ 4.0, 5.0 ] ); + +var v = arr[ 0 ]; +// returns 4.0 + +v = arr[ 1 ]; +// returns 5.0 +``` + +By default, the method starts writing values at the first array index. To specify an alternative index, provide an index `offset`. + + + +```javascript +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); +// returns [ 1.0, 2.0, 3.0 ] + +// Set the last two array elements: +arr.set( [ 4.0, 5.0 ], 1 ); + +var v = arr[ 1 ]; +// returns 4.0 + +v = arr[ 2 ]; +// returns 5.0 +``` + + + +#### Float32Array.prototype.slice( \[begin\[, end]] ) + +Copies array elements to a new array with the same underlying data type as the host array. + + + +```javascript +var arr1 = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.slice(); + +var bool = ( arr1 === arr2 ); +// returns false + +bool = ( arr1.buffer === arr2.buffer ); +// returns false + +var v = arr2[ 0 ]; +// returns 1.0 + +v = arr2[ 1 ]; +// returns 2.0 + +v = arr2[ 2 ]; +// returns 3.0 +``` + +By default, the method copies elements beginning with the first array element. To specify an alternative array index at which to begin copying, provide a `begin` index (inclusive). + + + +```javascript +var arr1 = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.slice( 1 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 2.0 + +v = arr2[ 1 ]; +// returns 3.0 +``` + +By default, the method copies all array elements after `begin`. To specify an alternative array index at which to end copying, provide an `end` index (exclusive). + + + +```javascript +var arr1 = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.slice( 0, 2 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 1.0 + +v = arr2[ 1 ]; +// returns 2.0 +``` + +When a `begin` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr1 = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.slice( -arr1.length, -1 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 1.0 + +v = arr2[ 1 ]; +// returns 2.0 +``` + + + +#### Float32Array.prototype.some( predicate\[, thisArg] ) + +Tests whether at least one array element passes a test implemented by a `predicate` function. + + + +```javascript +function predicate( v ) { + return ( v >= 2.0 ); +} + +var arr = new Float32Array( [ 1.0, 2.0 ] ); + +var bool = arr.some( predicate ); +// returns true +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 2.0 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Float32Array( [ 1.0, 1.0 ] ); + +var bool = arr.some( predicate, ctx ); +// returns false + +var n = ctx.count; +// returns 2 +``` + + + +#### Float32Array.prototype.sort( \[compareFunction] ) + +Sorts an array **in-place** (thus mutating the array on which the method is invoked). + + + +```javascript +var arr = new Float32Array( [ 2.0, 3.0, 0.0 ] ); + +// Sort the array (in ascending order): +arr.sort(); + +var v = arr[ 0 ]; +// returns 0.0 + +v = arr[ 1 ]; +// returns 2.0 + +v = arr[ 2 ]; +// returns 3.0 +``` + +By default, the method sorts array elements in ascending order. To impose a custom order, provide a `compareFunction`. + + + +```javascript +function descending( a, b ) { + return b - a; +} + +var arr = new Float32Array( [ 2.0, 3.0, 0.0 ] ); + +// Sort the array (in descending order): +arr.sort( descending ); + +var v = arr[ 0 ]; +// returns 3.0 + +v = arr[ 1 ]; +// returns 2.0 + +v = arr[ 2 ]; +// returns 0.0 +``` + +The comparison function is provided two array elements, `a` and `b`, per invocation, and its return value determines the sort order as follows: + +- If the comparison function returns a value **less** than zero, then the method sorts `a` to an index lower than `b` (i.e., `a` should come **before** `b`). +- If the comparison function returns a value **greater** than zero, then the method sorts `a` to an index higher than `b` (i.e., `b` should come **before** `a`). +- If the comparison function returns **zero**, then the relative order of `a` and `b` _should_ remain unchanged. + + + +#### Float32Array.prototype.subarray( \[begin\[, end]] ) + +Creates a new typed array view over the same underlying [`ArrayBuffer`][@stdlib/array/buffer] and with the same underlying data type as the host array. + + + +```javascript +var arr1 = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.subarray(); +// returns [ 1.0, 2.0, 3.0 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +By default, the method creates a typed array view beginning with the first array element. To specify an alternative array index at which to begin, provide a `begin` index (inclusive). + + + +```javascript +var arr1 = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.subarray( 1 ); +// returns [ 2.0, 3.0 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +By default, the method creates a typed array view which includes all array elements after `begin`. To limit the number of array elements after `begin`, provide an `end` index (exclusive). + + + +```javascript +var arr1 = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.subarray( 0, 2 ); +// returns [ 1.0, 2.0 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +When a `begin` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr1 = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.subarray( -arr1.length, -1 ); +// returns [ 1.0, 2.0 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +If the method is unable to resolve indices to a non-empty array subsequence, the method returns an empty typed array. + + + +```javascript +var arr1 = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.subarray( 10, -1 ); +// returns [] +``` + + + +#### Float32Array.prototype.toLocaleString( \[locales\[, options]] ) + +Serializes an array as a locale-specific `string`. + + + +```javascript +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var str = arr.toLocaleString(); +// returns '1,2,3' +``` + + + +#### Float32Array.prototype.toString() + +Serializes an array as a `string`. + + + +```javascript +var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + +var str = arr.toString(); +// returns '1,2,3' +``` + + + +#### Float32Array.prototype.values() + +Returns an iterator for iterating over array elements. + + + +```javascript +var arr = new Float32Array( [ 1.0, 2.0 ] ); + +// Create an iterator: +var it = arr.values(); + +// Iterate over array elements... +var v = it.next().value; +// returns 1.0 + +v = it.next().value; +// returns 2.0 + +var bool = it.next().done; +// returns true +``` + +
+ + + +* * * + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var randu = require( '@stdlib/random/base/randu' ); +var ctor = require( '@stdlib/array/float32' ); + +var arr; +var i; + +arr = new ctor( 10 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = randu() * 100.0; +} +console.log( arr ); +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/float32/benchmark/benchmark.copy_within.js b/float32/benchmark/benchmark.copy_within.js new file mode 100644 index 00000000..7e64a807 --- /dev/null +++ b/float32/benchmark/benchmark.copy_within.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':copyWithin', function benchmark( b ) { + var arr; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + arr = arr.copyWithin( 1, 0 ); + if ( arr[ 0 ] !== i ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float32/benchmark/benchmark.copy_within.length.js b/float32/benchmark/benchmark.copy_within.length.js new file mode 100644 index 00000000..e7c4529c --- /dev/null +++ b/float32/benchmark/benchmark.copy_within.length.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + arr = arr.copyWithin( 1, 0 ); + if ( arr[ 0 ] !== i ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':copyWithin:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.data.js b/float32/benchmark/benchmark.data.js new file mode 100644 index 00000000..b120c941 --- /dev/null +++ b/float32/benchmark/benchmark.data.js @@ -0,0 +1,75 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::get,index', function benchmark( b ) { + var arr; + var N; + var v; + var i; + + arr = new Float32Array( 2 ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr[ i%N ]; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::set,index', function benchmark( b ) { + var arr; + var N; + var i; + + arr = new Float32Array( 2 ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ i%N ] = i; + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] || arr[ 1 ] !== arr[ 1 ] ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float32/benchmark/benchmark.entries.js b/float32/benchmark/benchmark.entries.js new file mode 100644 index 00000000..66e8bb25 --- /dev/null +++ b/float32/benchmark/benchmark.entries.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':entries', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Float32Array( [ 1.0, 2.0 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.entries(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float32/benchmark/benchmark.every.js b/float32/benchmark/benchmark.every.js new file mode 100644 index 00000000..3ae10431 --- /dev/null +++ b/float32/benchmark/benchmark.every.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':every', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0.0; + } +}); + +bench( pkg+'::this_context:every', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate, {} ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0.0; + } +}); diff --git a/float32/benchmark/benchmark.every.length.js b/float32/benchmark/benchmark.every.length.js new file mode 100644 index 00000000..f5693bf2 --- /dev/null +++ b/float32/benchmark/benchmark.every.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value >= 0.0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':every:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.fill.js b/float32/benchmark/benchmark.fill.js new file mode 100644 index 00000000..2358c69c --- /dev/null +++ b/float32/benchmark/benchmark.fill.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':fill', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr = arr.fill( v ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float32/benchmark/benchmark.fill.length.js b/float32/benchmark/benchmark.fill.length.js new file mode 100644 index 00000000..e7c5dab2 --- /dev/null +++ b/float32/benchmark/benchmark.fill.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr = arr.fill( v ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':fill:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.filter.js b/float32/benchmark/benchmark.filter.js new file mode 100644 index 00000000..1534462c --- /dev/null +++ b/float32/benchmark/benchmark.filter.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isFloat32Array = require( '@stdlib/assert/is-float32array' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':filter', function benchmark( b ) { + var arr; + var out; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat32Array( out ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0.0; + } +}); + +bench( pkg+'::this_context:filter', function benchmark( b ) { + var arr; + var out; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate, {} ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat32Array( out ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0.0; + } +}); diff --git a/float32/benchmark/benchmark.filter.length.js b/float32/benchmark/benchmark.filter.length.js new file mode 100644 index 00000000..7bb44041 --- /dev/null +++ b/float32/benchmark/benchmark.filter.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isFloat32Array = require( '@stdlib/assert/is-float32array' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value >= 0.0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat32Array( out ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':filter:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.find.js b/float32/benchmark/benchmark.find.js new file mode 100644 index 00000000..993fa3db --- /dev/null +++ b/float32/benchmark/benchmark.find.js @@ -0,0 +1,82 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':find', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float32Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0.0; + } +}); + +bench( pkg+'::this_context:find', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float32Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate, {} ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0.0; + } +}); diff --git a/float32/benchmark/benchmark.find.length.js b/float32/benchmark/benchmark.find.length.js new file mode 100644 index 00000000..d53055c7 --- /dev/null +++ b/float32/benchmark/benchmark.find.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0.0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - tuple length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':find:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.find_index.js b/float32/benchmark/benchmark.find_index.js new file mode 100644 index 00000000..ebfae0de --- /dev/null +++ b/float32/benchmark/benchmark.find_index.js @@ -0,0 +1,82 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':findIndex', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float32Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0.0; + } +}); + +bench( pkg+'::this_context:findIndex', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float32Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate, {} ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0.0; + } +}); diff --git a/float32/benchmark/benchmark.find_index.length.js b/float32/benchmark/benchmark.find_index.length.js new file mode 100644 index 00000000..05cfd05e --- /dev/null +++ b/float32/benchmark/benchmark.find_index.length.js @@ -0,0 +1,104 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0.0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':findIndex:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.for_each.js b/float32/benchmark/benchmark.for_each.js new file mode 100644 index 00000000..60c398fa --- /dev/null +++ b/float32/benchmark/benchmark.for_each.js @@ -0,0 +1,88 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':forEach', function benchmark( b ) { + var count; + var arr; + var N; + var i; + + arr = new Float32Array( 2 ); + N = arr.length; + + count = 0; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn ); + if ( count !== N*(i+1) ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( count !== N*i ) { + b.fail( 'unexpected result' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn() { + count += 1; + } +}); + +bench( pkg+'::this_context:forEach', function benchmark( b ) { + var count; + var arr; + var N; + var i; + + arr = new Float32Array( 2 ); + N = arr.length; + + count = 0; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn, {} ); + if ( count !== N*(i+1) ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( count !== N*i ) { + b.fail( 'unexpected result' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn() { + count += 1; + } +}); diff --git a/float32/benchmark/benchmark.for_each.length.js b/float32/benchmark/benchmark.for_each.length.js new file mode 100644 index 00000000..0d700cc3 --- /dev/null +++ b/float32/benchmark/benchmark.for_each.length.js @@ -0,0 +1,106 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var count; + var arr; + + arr = new Float32Array( len ); + count = 0; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn ); + if ( count !== count ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( count !== count ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } + + /** + * Callback invoked for each tuple element. + * + * @private + */ + function fcn() { + count += 1; + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':forEach:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.from.js b/float32/benchmark/benchmark.from.js new file mode 100644 index 00000000..6465a900 --- /dev/null +++ b/float32/benchmark/benchmark.from.js @@ -0,0 +1,237 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var ITERATOR_SYMBOL = require( '@stdlib/symbol/iterator' ); +var isFloat32Array = require( '@stdlib/assert/is-float32array' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// VARIABLES // + +var opts = { + 'skip': ( ITERATOR_SYMBOL === null ) +}; + + +// MAIN // + +bench( pkg+'::typed_array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Float32Array( [ 1.0, 2.0 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Float32Array.from( buf ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isFloat32Array( arr ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array,clbk:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Float32Array( [ 1.0, 2.0 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Float32Array.from( buf, clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isFloat32Array( arr ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1.0; + } +}); + +bench( pkg+'::array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1.0, 2.0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Float32Array.from( buf ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isFloat32Array( arr ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::array,clbk:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1.0, 2.0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Float32Array.from( buf, clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isFloat32Array( arr ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1.0; + } +}); + +bench( pkg+'::iterable:from', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Float32Array.from( createIterable() ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isFloat32Array( arr ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out; + var i; + + out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + + i = 0; + + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + i += 1; + if ( i <= 2 ) { + return { + 'value': 0.0, + 'done': false + }; + } + return { + 'done': true + }; + } + } +}); + +bench( pkg+'::iterable,clbk:from:', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Float32Array.from( createIterable(), clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isFloat32Array( arr ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out; + var i; + + out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + + i = 0; + + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + i += 1; + if ( i <= 2 ) { + return { + 'value': 1.0, + 'done': false + }; + } + return { + 'done': true + }; + } + } + + function clbk( v ) { + return v + 1.0; + } +}); diff --git a/float32/benchmark/benchmark.includes.js b/float32/benchmark/benchmark.includes.js new file mode 100644 index 00000000..3082378a --- /dev/null +++ b/float32/benchmark/benchmark.includes.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':includes', function benchmark( b ) { + var bool; + var arr; + var v; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1.0; + bool = arr.includes( v ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float32/benchmark/benchmark.includes.length.js b/float32/benchmark/benchmark.includes.length.js new file mode 100644 index 00000000..a9c2d9fa --- /dev/null +++ b/float32/benchmark/benchmark.includes.length.js @@ -0,0 +1,96 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1.0; + bool = arr.includes( v ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':includes:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.index_of.js b/float32/benchmark/benchmark.index_of.js new file mode 100644 index 00000000..b289de19 --- /dev/null +++ b/float32/benchmark/benchmark.index_of.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':indexOf', function benchmark( b ) { + var out; + var arr; + var v; + var i; + + arr = new Float32Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1.0; + out = arr.indexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float32/benchmark/benchmark.index_of.length.js b/float32/benchmark/benchmark.index_of.length.js new file mode 100644 index 00000000..adb0e970 --- /dev/null +++ b/float32/benchmark/benchmark.index_of.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1.0; + out = arr.indexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':indexOf:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.join.js b/float32/benchmark/benchmark.join.js new file mode 100644 index 00000000..d31859c4 --- /dev/null +++ b/float32/benchmark/benchmark.join.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':join', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i % 127; + out = arr.join(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float32/benchmark/benchmark.join.length.js b/float32/benchmark/benchmark.join.length.js new file mode 100644 index 00000000..93632d2f --- /dev/null +++ b/float32/benchmark/benchmark.join.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i % 127; + out = arr.join(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':join:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.js b/float32/benchmark/benchmark.js new file mode 100644 index 00000000..b924b087 --- /dev/null +++ b/float32/benchmark/benchmark.js @@ -0,0 +1,49 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isFloat32Array = require( '@stdlib/assert/is-float32array' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new ctor( 0 ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isFloat32Array( arr ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +// TODO: add additional instantiation benchmarks (e.g., ArrayBuffer, etc) diff --git a/float32/benchmark/benchmark.keys.js b/float32/benchmark/benchmark.keys.js new file mode 100644 index 00000000..b3445cc5 --- /dev/null +++ b/float32/benchmark/benchmark.keys.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':keys', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.keys(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float32/benchmark/benchmark.last_index_of.js b/float32/benchmark/benchmark.last_index_of.js new file mode 100644 index 00000000..b2010445 --- /dev/null +++ b/float32/benchmark/benchmark.last_index_of.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':lastIndexOf', function benchmark( b ) { + var out; + var arr; + var v; + var i; + + arr = new Float32Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1.0; + out = arr.lastIndexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float32/benchmark/benchmark.last_index_of.length.js b/float32/benchmark/benchmark.last_index_of.length.js new file mode 100644 index 00000000..a9bec695 --- /dev/null +++ b/float32/benchmark/benchmark.last_index_of.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1.0; + out = arr.lastIndexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':lastIndexOf:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.length.js b/float32/benchmark/benchmark.length.js new file mode 100644 index 00000000..cba0e610 --- /dev/null +++ b/float32/benchmark/benchmark.length.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isFloat32Array = require( '@stdlib/assert/is-float32array' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new ctor( len ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isFloat32Array( arr ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.map.js b/float32/benchmark/benchmark.map.js new file mode 100644 index 00000000..fc405d03 --- /dev/null +++ b/float32/benchmark/benchmark.map.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isFloat32Array = require( '@stdlib/assert/is-float32array' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':map', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat32Array( out ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1.0; + } +}); + +bench( pkg+'::this_context:map', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn, {} ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat32Array( out ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1.0; + } +}); diff --git a/float32/benchmark/benchmark.map.length.js b/float32/benchmark/benchmark.map.length.js new file mode 100644 index 00000000..5149d9d7 --- /dev/null +++ b/float32/benchmark/benchmark.map.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isFloat32Array = require( '@stdlib/assert/is-float32array' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Maps an array element to a new value. +* +* @private +* @param {*} value - array element +* @returns {*} new value +*/ +function fcn( value ) { + return value + 1.0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat32Array( out ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':map:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.of.js b/float32/benchmark/benchmark.of.js new file mode 100644 index 00000000..0eaa1586 --- /dev/null +++ b/float32/benchmark/benchmark.of.js @@ -0,0 +1,48 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isFloat32Array = require( '@stdlib/assert/is-float32array' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':of', function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Float32Array.of( i, 2.0 ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isFloat32Array( arr ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float32/benchmark/benchmark.properties.js b/float32/benchmark/benchmark.properties.js new file mode 100644 index 00000000..563d90f4 --- /dev/null +++ b/float32/benchmark/benchmark.properties.js @@ -0,0 +1,145 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isArrayBuffer = require( '@stdlib/assert/is-arraybuffer' ); +var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::get:buffer', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.buffer; + if ( typeof v !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isArrayBuffer( v ) ) { + b.fail( 'should return an ArrayBuffer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteLength', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteLength; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteOffset', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteOffset; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:BYTES_PER_ELEMENT', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.BYTES_PER_ELEMENT; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:length', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.length; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float32/benchmark/benchmark.reduce.js b/float32/benchmark/benchmark.reduce.js new file mode 100644 index 00000000..52e04a3d --- /dev/null +++ b/float32/benchmark/benchmark.reduce.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reduce', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( acc, v ) { + return acc + v + 1.0; + } +}); + +bench( pkg+'::initial_value:reduce', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn, 3.14 ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1.0; + } +}); diff --git a/float32/benchmark/benchmark.reduce.length.js b/float32/benchmark/benchmark.reduce.length.js new file mode 100644 index 00000000..2f7db248 --- /dev/null +++ b/float32/benchmark/benchmark.reduce.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Updates an accumulated value. +* +* @private +* @param {*} acc - accumulated value +* @param {*} value - array element +* @returns {*} accumulated value +*/ +function fcn( acc, value ) { + return acc + value + 1.0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reduce:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.reduce_right.js b/float32/benchmark/benchmark.reduce_right.js new file mode 100644 index 00000000..bd2ff498 --- /dev/null +++ b/float32/benchmark/benchmark.reduce_right.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reduceRight', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( acc, v ) { + return acc + v + 1.0; + } +}); + +bench( pkg+'::initial_value:reduceRight', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn, 3.14 ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1.0; + } +}); diff --git a/float32/benchmark/benchmark.reduce_right.length.js b/float32/benchmark/benchmark.reduce_right.length.js new file mode 100644 index 00000000..5010b8c4 --- /dev/null +++ b/float32/benchmark/benchmark.reduce_right.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Updates an accumulated value. +* +* @private +* @param {*} acc - accumulated value +* @param {*} value - array element +* @returns {*} accumulated value +*/ +function fcn( acc, value ) { + return acc + value + 1.0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reduceRight:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.reverse.js b/float32/benchmark/benchmark.reverse.js new file mode 100644 index 00000000..9f19259a --- /dev/null +++ b/float32/benchmark/benchmark.reverse.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isFloat32Array = require( '@stdlib/assert/is-float32array' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reverse', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.reverse(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat32Array( out ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float32/benchmark/benchmark.reverse.length.js b/float32/benchmark/benchmark.reverse.length.js new file mode 100644 index 00000000..e0f46f40 --- /dev/null +++ b/float32/benchmark/benchmark.reverse.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isFloat32Array = require( '@stdlib/assert/is-float32array' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.reverse(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat32Array( out ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reverse:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.set.js b/float32/benchmark/benchmark.set.js new file mode 100644 index 00000000..9fc4b69e --- /dev/null +++ b/float32/benchmark/benchmark.set.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::array:set', function benchmark( b ) { + var values; + var buf; + var arr; + var N; + var v; + var i; + + values = []; + for ( i = 0; i < 10; i++ ) { + values.push( i ); + } + N = values.length; + + arr = new Float32Array( 2 ); + buf = [ 0.0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = values[ i%N ]; + v = arr.set( buf ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array:set', function benchmark( b ) { + var values; + var buf; + var arr; + var N; + var v; + var i; + + values = new Float32Array( 20 ); + N = values.length; + for ( i = 0; i < N; i++ ) { + values[ i ] = i; + } + + arr = new Float32Array( 2 ); + buf = new Float32Array( 1 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = values[ i%N ]; + v = arr.set( buf ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float32/benchmark/benchmark.set.length.js b/float32/benchmark/benchmark.set.length.js new file mode 100644 index 00000000..b67f4fa0 --- /dev/null +++ b/float32/benchmark/benchmark.set.length.js @@ -0,0 +1,114 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randi = require( '@stdlib/random/base/randi' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var values; + var arr1; + var arr2; + var arr; + var N; + var i; + + arr1 = []; + arr2 = []; + for ( i = 0; i < len; i++ ) { + arr1.push( randi() ); + arr2.push( randi() ); + } + arr = new Float32Array( len ); + + values = [ + arr1, + arr2 + ]; + N = values.length; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr.set( values[ i%N ] ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':set:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.slice.js b/float32/benchmark/benchmark.slice.js new file mode 100644 index 00000000..0c585e89 --- /dev/null +++ b/float32/benchmark/benchmark.slice.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isFloat32Array = require( '@stdlib/assert/is-float32array' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':slice', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.slice(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat32Array( out ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float32/benchmark/benchmark.slice.length.js b/float32/benchmark/benchmark.slice.length.js new file mode 100644 index 00000000..8458ec83 --- /dev/null +++ b/float32/benchmark/benchmark.slice.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isFloat32Array = require( '@stdlib/assert/is-float32array' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.slice(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat32Array( out ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':slice:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.some.js b/float32/benchmark/benchmark.some.js new file mode 100644 index 00000000..0fd32437 --- /dev/null +++ b/float32/benchmark/benchmark.some.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':some', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0.0; + } +}); + +bench( pkg+'::this_context:some', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate, {} ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0.0; + } +}); diff --git a/float32/benchmark/benchmark.some.length.js b/float32/benchmark/benchmark.some.length.js new file mode 100644 index 00000000..f82b82cb --- /dev/null +++ b/float32/benchmark/benchmark.some.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0.0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':some:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.sort.js b/float32/benchmark/benchmark.sort.js new file mode 100644 index 00000000..98441ed4 --- /dev/null +++ b/float32/benchmark/benchmark.sort.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var randi = require( '@stdlib/random/base/randi' ); +var isFloat32Array = require( '@stdlib/assert/is-float32array' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':sort', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float32Array( [ randi(), randi() ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = randi(); + out = arr.sort(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat32Array( out ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float32/benchmark/benchmark.sort.length.js b/float32/benchmark/benchmark.sort.length.js new file mode 100644 index 00000000..aa0e5595 --- /dev/null +++ b/float32/benchmark/benchmark.sort.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randi = require( '@stdlib/random/base/randi' ); +var isFloat32Array = require( '@stdlib/assert/is-float32array' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var data; + var arr; + var i; + + data = []; + for ( i = 0; i < len; i++ ) { + data.push( randi() ); + } + arr = new Float32Array( data ); + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ i%len ] = randi(); + out = arr.sort(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat32Array( out ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':sort:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.subarray.js b/float32/benchmark/benchmark.subarray.js new file mode 100644 index 00000000..5b032889 --- /dev/null +++ b/float32/benchmark/benchmark.subarray.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isFloat32Array = require( '@stdlib/assert/is-float32array' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':subarray', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.subarray(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat32Array( out ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float32/benchmark/benchmark.subarray.length.js b/float32/benchmark/benchmark.subarray.length.js new file mode 100644 index 00000000..d2a112e4 --- /dev/null +++ b/float32/benchmark/benchmark.subarray.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isFloat32Array = require( '@stdlib/assert/is-float32array' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.subarray(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat32Array( out ) ) { + b.fail( 'should return a Float32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':subarray:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.to_locale_string.js b/float32/benchmark/benchmark.to_locale_string.js new file mode 100644 index 00000000..e1bc74e7 --- /dev/null +++ b/float32/benchmark/benchmark.to_locale_string.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':toLocaleString', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toLocaleString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float32/benchmark/benchmark.to_locale_string.length.js b/float32/benchmark/benchmark.to_locale_string.length.js new file mode 100644 index 00000000..5948a579 --- /dev/null +++ b/float32/benchmark/benchmark.to_locale_string.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toLocaleString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':toLocaleString:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.to_string.js b/float32/benchmark/benchmark.to_string.js new file mode 100644 index 00000000..25c4da95 --- /dev/null +++ b/float32/benchmark/benchmark.to_string.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':toString', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float32/benchmark/benchmark.to_string.length.js b/float32/benchmark/benchmark.to_string.length.js new file mode 100644 index 00000000..954d1713 --- /dev/null +++ b/float32/benchmark/benchmark.to_string.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':toString:len='+len, f ); + } +} + +main(); diff --git a/float32/benchmark/benchmark.values.js b/float32/benchmark/benchmark.values.js new file mode 100644 index 00000000..dda1b3f8 --- /dev/null +++ b/float32/benchmark/benchmark.values.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':values', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Float32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.values(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float32/docs/repl.txt b/float32/docs/repl.txt new file mode 100644 index 00000000..3f3439ac --- /dev/null +++ b/float32/docs/repl.txt @@ -0,0 +1,959 @@ + +{{alias}}() + A typed array constructor which returns a typed array representing an array + of single-precision floating-point numbers in the platform byte order. + + Returns + ------- + out: Float32Array + A typed array. + + Examples + -------- + > var arr = new {{alias}}() + + + +{{alias}}( length ) + Returns a typed array having a specified length. + + Parameters + ---------- + length: integer + Typed array length. + + Returns + ------- + out: Float32Array + A typed array. + + Examples + -------- + > var arr = new {{alias}}( 5 ) + [ 0.0, 0.0, 0.0, 0.0, 0.0 ] + + +{{alias}}( typedarray ) + Creates a typed array from another typed array. + + Parameters + ---------- + typedarray: TypedArray + Typed array from which to generate another typed array. + + Returns + ------- + out: Float32Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias:@stdlib/array/float64}}( [ 0.5, 0.5, 0.5 ] ); + > var arr2 = new {{alias}}( arr1 ) + [ 0.5, 0.5, 0.5 ] + + +{{alias}}( obj ) + Creates a typed array from an array-like object or iterable. + + Parameters + ---------- + obj: Object + Array-like object or iterable from which to generate a typed array. + + Returns + ------- + out: Float32Array + A typed array. + + Examples + -------- + > var arr1 = [ 0.5, 0.5, 0.5 ]; + > var arr2 = new {{alias}}( arr1 ) + [ 0.5, 0.5, 0.5 ] + + +{{alias}}( buffer[, byteOffset[, length]] ) + Returns a typed array view of an ArrayBuffer. + + Parameters + ---------- + buffer: ArrayBuffer + Underlying ArrayBuffer. + + byteOffset: integer (optional) + Integer byte offset specifying the location of the first typed array + element. Default: 0. + + length: integer (optional) + View length. If not provided, the view spans from the byteOffset to + the end of the underlying ArrayBuffer. + + Returns + ------- + out: Float32Array + A typed array. + + Examples + -------- + > var buf = new {{alias:@stdlib/array/buffer}}( 16 ); + > var arr = new {{alias}}( buf, 0, 4 ) + [ 0.0, 0.0, 0.0, 0.0 ] + + +{{alias}}.from( src[, map[, thisArg]] ) + Creates a new typed array from an array-like object or an iterable. + + A callback is provided the following arguments: + + - value: source value. + - index: source index. + + Parameters + ---------- + src: ArrayLike|Iterable + Source of array elements. + + map: Function (optional) + Callback to invoke for each source element. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Float32Array + A typed array. + + Examples + -------- + > function mapFcn( v ) { return v * 2.0; }; + > var arr = {{alias}}.from( [ 1.0, -1.0 ], mapFcn ) + [ 2.0, -2.0 ] + + +{{alias}}.of( element0[, element1[, ...elementN]] ) + Creates a new typed array from a variable number of arguments. + + Parameters + ---------- + element0: number + Array element. + + element1: number (optional) + Array element. + + elementN: number (optional) + Array elements. + + Returns + ------- + out: Float32Array + A typed array. + + Examples + -------- + > var arr = {{alias}}.of( 2.0, -2.0 ) + [ 2.0, -2.0 ] + + +{{alias}}.BYTES_PER_ELEMENT + Number of bytes per view element. + + Examples + -------- + > {{alias}}.BYTES_PER_ELEMENT + 4 + + +{{alias}}.name + Typed array constructor name. + + Examples + -------- + > {{alias}}.name + 'Float32Array' + + +{{alias}}.prototype.buffer + Read-only property which returns the ArrayBuffer referenced by the typed + array. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.buffer + + + +{{alias}}.prototype.byteLength + Read-only property which returns the length (in bytes) of the typed array. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.byteLength + 20 + + +{{alias}}.prototype.byteOffset + Read-only property which returns the offset (in bytes) of the typed array + from the start of its ArrayBuffer. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.byteOffset + 0 + + +{{alias}}.prototype.BYTES_PER_ELEMENT + Number of bytes per view element. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.BYTES_PER_ELEMENT + 4 + + +{{alias}}.prototype.length + Read-only property which returns the number of view elements. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.length + 5 + + +{{alias}}.prototype.copyWithin( target, start[, end] ) + Copies a sequence of elements within the array starting at `start` and + ending at `end` (non-inclusive) to the position starting at `target`. + + Parameters + ---------- + target: integer + Target start index position. + + start: integer + Source start index position. + + end: integer (optional) + Source end index position. Default: out.length. + + Returns + ------- + out: Float32Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 2.0, -2.0, 1.0, -1.0, 1.0 ] ); + > arr.copyWithin( 3, 0, 2 ); + > arr[ 3 ] + 2.0 + > arr[ 4 ] + -2.0 + + +{{alias}}.prototype.entries() + Returns an iterator for iterating over array key-value pairs. + + Returns + ------- + iter: Iterator + Iterator for iterating over array key-value pairs. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, -1.0 ] ); + > it = arr.entries(); + > it.next().value + [ 0, 1.0 ] + > it.next().value + [ 1, -1.0 ] + > it.next().done + true + + +{{alias}}.prototype.every( predicate[, thisArg] ) + Tests whether all array elements pass a test implemented by a predicate + function. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. If a predicate function + returns a truthy value, an array element passes; otherwise, an array + element fails. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + bool: boolean + Boolean indicating whether all array elements pass. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, -1.0 ] ); + > function predicate( v ) { return ( v >= 0.0 ); }; + > arr.every( predicate ) + false + + +{{alias}}.prototype.fill( value[, start[, end]] ) + Fills an array from a start index to an end index (non-inclusive) with a + provided value. + + Parameters + ---------- + value: number + Fill value. + + start: integer (optional) + Start index. If less than zero, the start index is resolved relative to + the last array element. Default: 0. + + end: integer (optional) + End index (non-inclusive). If less than zero, the end index is resolved + relative to the last array element. Default: out.length. + + Returns + ------- + out: Float32Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, -1.0 ] ); + > arr.fill( 2.0 ); + > arr[ 0 ] + 2.0 + > arr[ 1 ] + 2.0 + + +{{alias}}.prototype.filter( predicate[, thisArg] ) + Creates a new array which includes those elements for which a predicate + function returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + The returned array has the same data type as the host array. + + If a predicate function does not return a truthy value for any array + element, the method returns `null`. + + Parameters + ---------- + predicate: Function + Predicate function which filters array elements. If a predicate function + returns a truthy value, an array element is included in the output + array; otherwise, an array element is not included in the output array. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Float32Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > function predicate( v ) { return ( v >= 0.0 ); }; + > var arr2 = arr1.filter( predicate ); + > arr2.length + 2 + + +{{alias}}.prototype.find( predicate[, thisArg] ) + Returns the first array element for which a provided predicate function + returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + If a predicate function never returns a truthy value, the method returns + `undefined`. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + value: number|undefined + Array element. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > function predicate( v ) { return ( v < 0.0 ); }; + > var v = arr.find( predicate ) + -1.0 + + +{{alias}}.prototype.findIndex( predicate[, thisArg] ) + Returns the index of the first array element for which a provided predicate + function returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + If a predicate function never returns a truthy value, the method returns + `-1`. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + idx: integer + Array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > function predicate( v ) { return ( v < 0.0 ); }; + > var idx = arr.findIndex( predicate ) + 2 + + +{{alias}}.prototype.forEach( fcn[, thisArg] ) + Invokes a callback for each array element. + + A provided function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + fcn: Function + Function to invoke for each array element. + + thisArg: Any (optional) + Callback execution context. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > var str = ' '; + > function fcn( v, i ) { str += i + ':' + v + ' '; }; + > arr.forEach( fcn ); + > str + ' 0:1 1:0 2:-1 ' + + +{{alias}}.prototype.includes( searchElement[, fromIndex] ) + Returns a boolean indicating whether an array includes a search element. + + The method does not distinguish between signed and unsigned zero. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: 0. + + Returns + ------- + bool: boolean + Boolean indicating whether an array includes a search element. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > var bool = arr.includes( 2.0 ) + false + > bool = arr.includes( -1.0 ) + true + + +{{alias}}.prototype.indexOf( searchElement[, fromIndex] ) + Returns the index of the first array element strictly equal to a search + element. + + The method does not distinguish between signed and unsigned zero. + + If unable to locate a search element, the method returns `-1`. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: 0. + + Returns + ------- + idx: integer + Array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > var idx = arr.indexOf( 2.0 ) + -1 + > idx = arr.indexOf( -1.0 ) + 2 + + +{{alias}}.prototype.join( [separator] ) + Serializes an array by joining all array elements as a string. + + Parameters + ---------- + separator: string (optional) + String delineating array elements. Default: ','. + + Returns + ------- + str: string + Array serialized as a string. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > arr.join( '|' ) + '1|0|-1' + + +{{alias}}.prototype.keys() + Returns an iterator for iterating over array keys. + + Returns + ------- + iter: Iterator + Iterator for iterating over array keys. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, -1.0 ] ); + > it = arr.keys(); + > it.next().value + 0 + > it.next().value + 1 + > it.next().done + true + + +{{alias}}.prototype.lastIndexOf( searchElement[, fromIndex] ) + Returns the index of the last array element strictly equal to a search + element. + + The method iterates from the last array element to the first array element. + + The method does not distinguish between signed and unsigned zero. + + If unable to locate a search element, the method returns `-1`. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: -1. + + Returns + ------- + idx: integer + array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0, 0.0, 1.0 ] ); + > var idx = arr.lastIndexOf( 2.0 ) + -1 + > idx = arr.lastIndexOf( 0.0 ) + 3 + + +{{alias}}.prototype.map( fcn[, thisArg] ) + Maps each array element to an element in a new typed array. + + A provided function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + The returned array has the same data type as the host array. + + Parameters + ---------- + fcn: Function + Function which maps array elements to elements in the new array. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Float32Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > function fcn( v ) { return v * 2.0; }; + > var arr2 = arr1.map( fcn ); + [ 2.0, 0.0, -2.0 ] + + +{{alias}}.prototype.reduce( fcn[, initialValue] ) + Applies a function against an accumulator and each element in an array and + returns the accumulated result. + + The provided function is provided the following arguments: + + - acc: accumulated result. + - value: current array element. + - index: index of the current array element. + - arr: array on which the method is invoked. + + If provided an initial value, the method invokes a provided function with + the initial value as the first argument and the first array element as the + second argument. + + If not provided an initial value, the method invokes a provided function + with the first array element as the first argument and the second array + element as the second argument. + + Parameters + ---------- + fcn: Function + Function to apply. + + initialValue: Any (optional) + Initial accumulation value. + + Returns + ------- + out: Any + Accumulated result. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > function fcn( acc, v ) { return acc + (v*v); }; + > var v = arr.reduce( fcn, 0.0 ) + 2.0 + + +{{alias}}.prototype.reduceRight( fcn[, initialValue] ) + Applies a function against an accumulator and each element in an array and + returns the accumulated result, iterating from right to left. + + The provided function is provided the following arguments: + + - acc: accumulated result. + - value: current array element. + - index: index of the current array element. + - arr: array on which the method is invoked. + + If provided an initial value, the method invokes a provided function with + the initial value as the first argument and the last array element as the + second argument. + + If not provided an initial value, the method invokes a provided function + with the last array element as the first argument and the second-to-last + array element as the second argument. + + Parameters + ---------- + fcn: Function + Function to apply. + + initialValue: Any (optional) + Initial accumulation value. + + Returns + ------- + out: Any + Accumulated result. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > function fcn( acc, v ) { return acc + (v*v); }; + > var v = arr.reduceRight( fcn, 0.0 ) + 2.0 + + +{{alias}}.prototype.reverse() + Reverses an array *in-place*. + + This method mutates the array on which the method is invoked. + + Returns + ------- + out: Float32Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ) + [ 1.0, 0.0, -1.0 ] + > arr.reverse() + [ -1.0, 0.0, 1.0 ] + + +{{alias}}.prototype.set( arr[, offset] ) + Sets array elements. + + Parameters + ---------- + arr: ArrayLike + Source array containing array values to set. + + offset: integer (optional) + Array index at which to start writing values. Default: 0. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > arr.set( [ -2.0, 2.0 ], 1 ); + > arr[ 1 ] + -2.0 + > arr[ 2 ] + 2.0 + + +{{alias}}.prototype.slice( [begin[, end]] ) + Copies array elements to a new array with the same underlying data type as + the host array. + + If the method is unable to resolve indices to a non-empty array subsequence, + the method returns `null`. + + Parameters + ---------- + begin: integer (optional) + Start element index (inclusive). If less than zero, the start index is + resolved relative to the last array element. Default: 0. + + end: integer (optional) + End element index (exclusive). If less than zero, the end index is + resolved relative to the last array element. Default: arr.length. + + Returns + ------- + out: Float32Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > var arr2 = arr1.slice( 1 ); + > arr2.length + 2 + > arr2[ 0 ] + 0.0 + > arr2[ 1 ] + -1.0 + + +{{alias}}.prototype.some( predicate[, thisArg] ) + Tests whether at least one array element passes a test implemented by a + predicate function. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. If a predicate function + returns a truthy value, a array element passes; otherwise, an array + element fails. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + bool: boolean + Boolean indicating whether at least one array element passes. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, -1.0 ] ); + > function predicate( v ) { return ( v < 0.0 ); }; + > arr.some( predicate ) + true + + +{{alias}}.prototype.sort( [compareFunction] ) + Sorts an array *in-place*. + + The comparison function is provided two array elements per invocation: `a` + and `b`. + + The comparison function return value determines the sort order as follows: + + - If the comparison function returns a value less than zero, then the method + sorts `a` to an index lower than `b` (i.e., `a` should come *before* `b`). + + - If the comparison function returns a value greater than zero, then the + method sorts `a` to an index higher than `b` (i.e., `b` should come *before* + `a`). + + - If the comparison function returns zero, then the relative order of `a` + and `b` should remain unchanged. + + This method mutates the array on which the method is invoked. + + Parameters + ---------- + compareFunction: Function (optional) + Function which specifies the sort order. The default sort order is + ascending order. + + Returns + ------- + out: Float32Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, -1.0, 0.0, 2.0, -2.0 ] ); + > arr.sort() + [ -2.0, -1.0, 0.0, 1.0, 2.0 ] + + +{{alias}}.prototype.subarray( [begin[, end]] ) + Creates a new typed array over the same underlying ArrayBuffer and with the + same underlying data type as the host array. + + If the method is unable to resolve indices to a non-empty array subsequence, + the method returns an empty typed array. + + Parameters + ---------- + begin: integer (optional) + Start element index (inclusive). If less than zero, the start index is + resolved relative to the last array element. Default: 0. + + end: integer (optional) + End element index (exclusive). If less than zero, the end index is + resolved relative to the last array element. Default: arr.length. + + Returns + ------- + out: Float32Array + A new typed array view. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1.0, -1.0, 0.0, 2.0, -2.0 ] ); + > var arr2 = arr1.subarray( 2 ) + [ 0.0, 2.0, -2.0 ] + + +{{alias}}.prototype.toLocaleString( [locales[, options]] ) + Serializes an array as a locale-specific string. + + Parameters + ---------- + locales: string|Array (optional) + A BCP 47 language tag, or an array of such tags. + + options: Object (optional) + Options. + + Returns + ------- + str: string + A typed array string representation. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, -1.0, 0.0 ] ); + > arr.toLocaleString() + '1,-1,0' + + +{{alias}}.prototype.toString() + Serializes an array as a string. + + Returns + ------- + str: string + A typed array string representation. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, -1.0, 0.0 ] ); + > arr.toString() + '1,-1,0' + + +{{alias}}.prototype.values() + Returns an iterator for iterating over array elements. + + Returns + ------- + iter: Iterator + Iterator for iterating over array elements. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, -1.0 ] ); + > it = arr.values(); + > it.next().value + 1.0 + > it.next().value + -1.0 + > it.next().done + true + + + See Also + -------- + diff --git a/float32/docs/types/index.d.ts b/float32/docs/types/index.d.ts new file mode 100644 index 00000000..120432a9 --- /dev/null +++ b/float32/docs/types/index.d.ts @@ -0,0 +1,26 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +// EXPORTS // + +/** +* Typed array constructor which returns a typed array representing an array of single-precision floating-point numbers in the platform byte order. +*/ +export = Float32Array; diff --git a/float32/docs/types/test.ts b/float32/docs/types/test.ts new file mode 100644 index 00000000..b793c75c --- /dev/null +++ b/float32/docs/types/test.ts @@ -0,0 +1,37 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// tslint:disable: no-construct +// tslint:disable: no-unused-expression + +import Float32Array = require( './index' ); + + +// TESTS // + +// The function returns a typed array instance... +{ + new Float32Array( 10 ); // $ExpectType Float32Array + new Float32Array( [ 2.1, 3.9, 5.2, 7.3 ] ); // $ExpectType Float32Array +} + +// The constructor function has to be invoked with `new`... +{ + Float32Array( 10 ); // $ExpectError + Float32Array( [ 2.1, 3.9, 5.2, 7.3 ] ); // $ExpectError +} diff --git a/float32/examples/index.js b/float32/examples/index.js new file mode 100644 index 00000000..a47829c7 --- /dev/null +++ b/float32/examples/index.js @@ -0,0 +1,31 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var randu = require( '@stdlib/random/base/randu' ); +var ctor = require( './../lib' ); + +var arr; +var i; + +arr = new ctor( 10 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = randu() * 100.0; +} +console.log( arr ); diff --git a/float32/lib/float32array.js b/float32/lib/float32array.js new file mode 100644 index 00000000..826b2ed6 --- /dev/null +++ b/float32/lib/float32array.js @@ -0,0 +1,28 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MAIN // + +var ctor = ( typeof Float32Array === 'function' ) ? Float32Array : void 0; // eslint-disable-line stdlib/require-globals + + +// EXPORTS // + +module.exports = ctor; diff --git a/float32/lib/index.js b/float32/lib/index.js new file mode 100644 index 00000000..d9c9c149 --- /dev/null +++ b/float32/lib/index.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Typed array constructor which returns a typed array representing an array of single-precision floating-point numbers in the platform byte order. +* +* @module @stdlib/array/float32 +* +* @example +* var ctor = require( '@stdlib/array/float32' ); +* +* var arr = new ctor( 10 ); +* // returns +*/ + +// MODULES // + +var hasFloat32ArraySupport = require( '@stdlib/assert/has-float32array-support' ); +var builtin = require( './float32array.js' ); +var polyfill = require( './polyfill.js' ); + + +// MAIN // + +var ctor; +if ( hasFloat32ArraySupport() ) { + ctor = builtin; +} else { + ctor = polyfill; +} + + +// EXPORTS // + +module.exports = ctor; diff --git a/float32/lib/polyfill.js b/float32/lib/polyfill.js new file mode 100644 index 00000000..43e3bf4e --- /dev/null +++ b/float32/lib/polyfill.js @@ -0,0 +1,37 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// TODO: write polyfill + +// MAIN // + +/** +* Typed array which represents an array of single-precision floating-point numbers in the platform byte order. +* +* @throws {Error} not implemented +*/ +function polyfill() { + throw new Error( 'not implemented' ); +} + + +// EXPORTS // + +module.exports = polyfill; diff --git a/float32/package.json b/float32/package.json new file mode 100644 index 00000000..1acdf01b --- /dev/null +++ b/float32/package.json @@ -0,0 +1,68 @@ +{ + "name": "@stdlib/array/float32", + "version": "0.0.0", + "description": "Float32Array.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structure", + "array", + "typed", + "typed array", + "typed-array", + "float32array", + "float32", + "float", + "single", + "single-precision", + "ieee754" + ] +} diff --git a/float32/test/test.copy_within.js b/float32/test/test.copy_within.js new file mode 100644 index 00000000..fb7e117a --- /dev/null +++ b/float32/test/test.copy_within.js @@ -0,0 +1,320 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var hasProp = require( '@stdlib/assert/has-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var Float32Array = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof Float32Array, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'a typed array instance has a `copyWithin` method for copying a sequence of elements within a typed array', function test( t ) { + var arr = new Float32Array( 2 ); + t.strictEqual( hasProp( arr, 'copyWithin' ), true, 'has property' ); + t.strictEqual( isFunction( arr.copyWithin ), true, 'has method' ); + t.end(); +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a typed array instance', function test( t ) { + var values; + var arr; + var i; + + arr = new Float32Array( 2 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0 ); + }; + } +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a typed array instance (end)', function test( t ) { + var values; + var arr; + var i; + + arr = new Float32Array( 2 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0, 5 ); + }; + } +}); + +tape( 'the method copies a sequence of elements within a typed array', function test( t ) { + var arr; + var p; + + arr = [ + 0.0, + 1.0, + 2.0, + 3.0, + 4.0 + ]; + + p = new Float32Array( arr ); + p.copyWithin( 0, 3 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3.0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4.0, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2.0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3.0, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4.0, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative target)', function test( t ) { + var arr; + var p; + + arr = [ + 0.0, + 1.0, + 2.0, + 3.0, + 4.0 + ]; + + p = new Float32Array( arr ); + p.copyWithin( -p.length, 3 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3.0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4.0, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2.0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3.0, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4.0, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative start)', function test( t ) { + var arr; + var p; + + arr = [ + 0.0, + 1.0, + 2.0, + 3.0, + 4.0 + ]; + + p = new Float32Array( arr ); + p.copyWithin( 0, -2 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3.0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4.0, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2.0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3.0, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4.0, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (end=length)', function test( t ) { + var arr; + var p; + + arr = [ + 0.0, + 1.0, + 2.0, + 3.0, + 4.0 + ]; + + p = new Float32Array( arr ); + p.copyWithin( 0, 3, p.length ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3.0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4.0, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2.0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3.0, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4.0, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (non-inclusive end)', function test( t ) { + var arr; + var p; + + arr = [ + 0.0, + 1.0, + 2.0, + 3.0, + 4.0 + ]; + + p = new Float32Array( arr ); + p.copyWithin( 2, 0, 2 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0.0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1.0, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0.0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1.0, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 4 ], 4.0, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative end)', function test( t ) { + var arr; + var p; + + arr = [ + 0.0, + 1.0, + 2.0, + 3.0, + 4.0 + ]; + + p = new Float32Array( arr ); + p.copyWithin( 2, 0, -3 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0.0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1.0, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0.0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1.0, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 4 ], 4.0, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (target >= length)', function test( t ) { + var arr; + var p; + + arr = [ + 0.0, + 1.0, + 2.0, + 3.0, + 4.0 + ]; + + p = new Float32Array( arr ); + p.copyWithin( p.length, 3 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0.0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1.0, 'returns expected value' ); + t.strictEqual( p[ 2 ], 2.0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3.0, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4.0, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (target > start)', function test( t ) { + var arr; + var p; + + arr = [ + 0.0, + 1.0, + 2.0, + 3.0, + 4.0 + ]; + + p = new Float32Array( arr ); + p.copyWithin( 2, 0 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0.0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1.0, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0.0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1.0, 'returns expected value' ); + t.strictEqual( p[ 4 ], 2.0, 'returns expected value' ); + + t.end(); +}); diff --git a/float32/test/test.js b/float32/test/test.js new file mode 100644 index 00000000..dcfed38f --- /dev/null +++ b/float32/test/test.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var hasFloat32ArraySupport = require( '@stdlib/assert/has-float32array-support' ); +var polyfill = require( './../lib/polyfill.js' ); +var ctor = require( './../lib' ); + + +// VARIABLES // + +var hasFloat32Arrays = hasFloat32ArraySupport(); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'if an environment supports `Float32Array`, the export is an alias for `Float32Array`', function test( t ) { + var Foo; + + Foo = proxyquire( './../lib', { + '@stdlib/assert/has-float32array-support': isTrue, + './float32array.js': Mock + }); + t.strictEqual( Foo, Mock, 'returns builtin' ); + + if ( hasFloat32Arrays ) { + t.strictEqual( ctor, Float32Array, 'is alias' ); // eslint-disable-line stdlib/require-globals + } + + t.end(); + + function Mock() { + return this; + } + + function isTrue() { + return true; + } +}); + +tape( 'if an environment does not support `Float32Array`, the export is a polyfill', function test( t ) { + var Foo; + + Foo = proxyquire( './../lib', { + '@stdlib/assert/has-float32array-support': isFalse + }); + + t.strictEqual( Foo, polyfill, 'returns polyfill' ); + t.end(); + + function isFalse() { + return false; + } +}); diff --git a/float32/test/test.polyfill.js b/float32/test/test.polyfill.js new file mode 100644 index 00000000..9d6fcb19 --- /dev/null +++ b/float32/test/test.polyfill.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var ctor = require( './../lib/polyfill.js' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error when invoked', function test( t ) { + t.throws( foo, Error, 'throws an error' ); + t.end(); + + function foo() { + var f = new ctor(); // eslint-disable-line no-unused-vars + } +}); + +// TODO: tests diff --git a/float64/README.md b/float64/README.md new file mode 100644 index 00000000..2e4673dd --- /dev/null +++ b/float64/README.md @@ -0,0 +1,1436 @@ + + +# Float64Array + +> [Typed array][mdn-typed-array] constructor which returns a [typed array][mdn-typed-array] representing an array of double-precision floating-point numbers in the platform byte order. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var Float64Array = require( '@stdlib/array/float64' ); +``` + +#### Float64Array() + +A [typed array][mdn-typed-array] constructor which returns a [typed array][mdn-typed-array] representing an array of double-precision floating-point numbers in the platform byte order. + + + +```javascript +var arr = new Float64Array(); +// returns +``` + +#### Float64Array( length ) + +Returns a [typed array][mdn-typed-array] having a specified length. + + + +```javascript +var arr = new Float64Array( 5 ); +// returns [ 0.0, 0.0, 0.0, 0.0, 0.0 ] +``` + +#### Float64Array( typedarray ) + +Creates a [typed array][mdn-typed-array] from another [typed array][mdn-typed-array]. + + + +```javascript +var Float32Array = require( '@stdlib/array/float32' ); + +var arr1 = new Float32Array( [ 0.5, 0.5, 0.5 ] ); +var arr2 = new Float64Array( arr1 ); +// returns [ 0.5, 0.5, 0.5 ] +``` + +#### Float64Array( obj ) + +Creates a [typed array][mdn-typed-array] from an array-like `object` or iterable. + + + +```javascript +var arr = new Float64Array( [ 0.5, 0.5, 0.5 ] ); +// returns [ 0.5, 0.5, 0.5 ] +``` + +#### Float64Array( buffer\[, byteOffset\[, length]] ) + +Returns a [typed array][mdn-typed-array] view of an [`ArrayBuffer`][@stdlib/array/buffer]. + + + +```javascript +var ArrayBuffer = require( '@stdlib/array/buffer' ); + +var buf = new ArrayBuffer( 32 ); +var arr = new Float64Array( buf, 0, 4 ); +// returns [ 0.0, 0.0, 0.0, 0.0 ] +``` + +* * * + +### Properties + + + +#### Float64Array.BYTES_PER_ELEMENT + +Number of bytes per view element. + + + +```javascript +var nbytes = Float64Array.BYTES_PER_ELEMENT; +// returns 8 +``` + + + +#### Float64Array.name + +[Typed array][mdn-typed-array] constructor name. + + + +```javascript +var str = Float64Array.name; +// returns 'Float64Array' +``` + + + +#### Float64Array.prototype.buffer + +**Read-only** property which returns the [`ArrayBuffer`][@stdlib/array/buffer] referenced by the [typed array][mdn-typed-array]. + + + +```javascript +var arr = new Float64Array( 5 ); +var buf = arr.buffer; +// returns +``` + + + +#### Float64Array.prototype.byteLength + +**Read-only** property which returns the length (in bytes) of the [typed array][mdn-typed-array]. + + + +```javascript +var arr = new Float64Array( 5 ); +var byteLength = arr.byteLength; +// returns 40 +``` + + + +#### Float64Array.prototype.byteOffset + +**Read-only** property which returns the offset (in bytes) of the [typed array][mdn-typed-array] from the start of its [`ArrayBuffer`][@stdlib/array/buffer]. + + + +```javascript +var arr = new Float64Array( 5 ); +var byteOffset = arr.byteOffset; +// returns 0 +``` + + + +#### Float64Array.prototype.BYTES_PER_ELEMENT + +Number of bytes per view element. + + + +```javascript +var arr = new Float64Array( 5 ); +var nbytes = arr.BYTES_PER_ELEMENT; +// returns 8 +``` + + + +#### Float64Array.prototype.length + +**Read-only** property which returns the number of view elements. + + + +```javascript +var arr = new Float64Array( 5 ); +var len = arr.length; +// returns 5 +``` + +* * * + +### Methods + + + +#### Float64Array.from( src\[, map\[, thisArg]] ) + +Creates a new typed array from an array-like `object` or an iterable. + +```javascript +var arr = Float64Array.from( [ 1.0, -1.0 ] ); +// returns [ 1.0, -1.0 ] +``` + +To invoke a function for each `src` value, provide a callback function. + +```javascript +function mapFcn( v ) { + return v * 2.0; +} + +var arr = Float64Array.from( [ 1.0, -1.0 ], mapFcn ); +// returns [ 2.0, -2.0 ] +``` + +A callback function is provided two arguments: + +- `value`: source value +- `index`: source index + +To set the callback execution context, provide a `thisArg`. + +```javascript +function mapFcn( v ) { + this.count += 1; + return v * 2.0; +} + +var ctx = { + 'count': 0 +}; + +var arr = Float64Array.from( [ 1.0, -1.0 ], mapFcn, ctx ); +// returns [ 2.0, -2.0 ] + +var n = ctx.count; +// returns 2 +``` + + + +#### Float64Array.of( element0\[, element1\[, ...elementN]] ) + +Creates a new typed array from a variable number of arguments. + +```javascript +var arr = Float64Array.of( 1.0, -1.0 ); +// returns [ 1.0, -1.0 ] +``` + + + +#### Float64Array.prototype.copyWithin( target, start\[, end] ) + +Copies a sequence of elements within an array starting at `start` and ending at `end` (non-inclusive) to the position starting at `target`. + + + +```javascript +var arr = new Float64Array( [ 1.0, 2.0, 3.0, 4.0, 5.0 ] ); + +// Copy the last two elements to the first two elements: +arr.copyWithin( 0, 3 ); + +var v = arr[ 0 ]; +// returns 4.0 + +v = arr[ 1 ]; +// returns 5.0 +``` + +By default, `end` equals the number of array elements (i.e., one more than the last array index). To limit the sequence length, provide an `end` argument. + + + +```javascript +var arr = new Float64Array( [ 1.0, 2.0, 3.0, 4.0, 5.0 ] ); + +// Copy the first two elements to the last two elements: +arr.copyWithin( 3, 0, 2 ); + +var v = arr[ 3 ]; +// returns 1.0 + +v = arr[ 4 ]; +// returns 2.0 +``` + +When a `target`, `start`, and/or `end` index is negative, the respective index is determined relative to the last array element. The following example achieves the same behavior as the previous example: + + + +```javascript +var arr = new Float64Array( [ 1.0, 2.0, 3.0, 4.0, 5.0 ] ); + +// Copy the first two elements to the last two elements: +arr.copyWithin( -2, -5, -3 ); + +var v = arr[ 3 ]; +// returns 1.0 + +v = arr[ 4 ]; +// returns 2.0 +``` + + + +#### Float64Array.prototype.entries() + +Returns an iterator for iterating over array key-value pairs. + + + +```javascript +var arr = new Float64Array( [ 1.0, 2.0 ] ); + +// Create an iterator: +var it = arr.entries(); + +// Iterate over key-value pairs... +var v = it.next().value; +// returns [ 0, 1.0 ] + +v = it.next().value; +// returns [ 1, 2.0 ] + +var bool = it.next().done; +// returns true +``` + + + +#### Float64Array.prototype.every( predicate\[, thisArg] ) + +Tests whether all array elements pass a test implemented by a `predicate` function. + + + +```javascript +function predicate( v ) { + return ( v <= 1.0 ); +} + +var arr = new Float64Array( [ 1.0, 2.0 ] ); + +var bool = arr.every( predicate ); +// returns false +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 1.0 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Float64Array( [ 1.0, 2.0 ] ); + +var bool = arr.every( predicate, ctx ); +// returns true + +var n = ctx.count; +// returns 2 +``` + + + +#### Float64Array.prototype.fill( value\[, start\[, end]] ) + +Fills an array from a `start` index to an `end` index (non-inclusive) with a provided `value`. + + + +```javascript +var arr = new Float64Array( 2 ); + +// Set all array elements to the same value: +arr.fill( 2.0 ); + +var v = arr[ 0 ]; +// returns 2.0 + +v = arr[ 1 ]; +// returns 2.0 + +// Set all array elements starting from the first index to the same value: +arr.fill( 3.0, 1 ); + +v = arr[ 0 ]; +// returns 2.0 + +v = arr[ 1 ]; +// returns 3.0 + +// Set all array elements, except the last element, to the same value: +arr.fill( 4.0, 0, arr.length-1 ); + +v = arr[ 0 ]; +// returns 4.0 + +v = arr[ 1 ]; +// returns 3.0 +``` + +When a `start` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr = new Float64Array( 2 ); + +// Set all array elements, except the last element, to the same value: +arr.fill( 2.0, -arr.length, -1 ); + +var v = arr[ 0 ]; +// returns 2.0 + +v = arr[ 1 ]; +// returns 0.0 +``` + + + +#### Float64Array.prototype.filter( predicate\[, thisArg] ) + +Creates a new array (of the same data type as the host array) which includes those elements for which a `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v >= 2.0 ); +} + +var arr1 = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.filter( predicate ); +// returns [ 2.0, 3.0 ] +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns an empty array. + + + +```javascript +function predicate( v ) { + return ( v >= 10.0 ); +} + +var arr1 = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.filter( predicate ); +// returns [] +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 2.0 ); +} + +var ctx = { + 'count': 0 +}; + +var arr1 = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.filter( predicate, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Float64Array.prototype.find( predicate\[, thisArg] ) + +Returns the first array element for which a provided `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v > 2.0 ); +} + +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var v = arr.find( predicate ); +// returns 3.0 +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns `undefined`. + + + +```javascript +function predicate( v ) { + return ( v < 1.0 ); +} + +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var v = arr.find( predicate ); +// returns undefined +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v > 2.0 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var v = arr.find( predicate, ctx ); +// returns 3.0 + +var n = ctx.count; +// returns 3 +``` + + + +#### Float64Array.prototype.findIndex( predicate\[, thisArg] ) + +Returns the index of the first array element for which a provided `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v >= 3.0 ); +} + +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var idx = arr.findIndex( predicate ); +// returns 2 +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns `-1`. + + + +```javascript +function predicate( v ) { + return ( v < 1.0 ); +} + +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var idx = arr.findIndex( predicate ); +// returns -1 +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 3.0 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var idx = arr.findIndex( predicate, ctx ); +// returns 2 + +var n = ctx.count; +// returns 3 +``` + + + +#### Float64Array.prototype.forEach( fcn\[, thisArg] ) + +Invokes a callback for each array element. + + + +```javascript +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var str = ''; + +function fcn( v, i ) { + str += i + ':' + v; + if ( i < arr.length-1 ) { + str += ' '; + } +} + +arr.forEach( fcn ); + +console.log( str ); +// => '0:1 1:2 2:3' +``` + +The callback is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function fcn() { + this.count += 1; +} + +var ctx = { + 'count': 0 +}; + +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +arr.forEach( fcn, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Float64Array.prototype.includes( searchElement\[, fromIndex] ) + +Returns a `boolean` indicating whether an array includes a search element. + + + +```javascript +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var bool = arr.includes( 3.0 ); +// returns true + +bool = arr.includes( 0.0 ); +// returns false +``` + +By default, the method searches the entire array (`fromIndex = 0`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var bool = arr.includes( 1.0, 1 ); +// returns false +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +bool = arr.includes( 1.0, -2 ); +// returns false +``` + +The method does **not** distinguish between signed and unsigned zero. + + + +#### Float64Array.prototype.indexOf( searchElement\[, fromIndex] ) + +Returns the index of the first array element strictly equal to a search element. + + + +```javascript +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var idx = arr.indexOf( 3.0 ); +// returns 2 + +idx = arr.indexOf( 0.0 ); +// returns -1 +``` + +By default, the method searches the entire array (`fromIndex = 0`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var idx = arr.indexOf( 1.0, 1 ); +// returns -1 +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var idx = arr.indexOf( 1.0, -2 ); +// returns -1 +``` + +The method does **not** distinguish between signed and unsigned zero. + + + +#### Float64Array.prototype.join( \[separator] ) + +Serializes an array by joining all array elements as a string. + + + +```javascript +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var str = arr.join(); +// returns '1,2,3' +``` + +By default, the method delineates array elements using a comma `,`. To specify a custom separator, provide a `separator` string. + + + +```javascript +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var str = arr.join( '|' ); +// returns '1|2|3' +``` + + + +#### Float64Array.prototype.keys() + +Returns an iterator for iterating over array keys. + + + +```javascript +var arr = new Float64Array( [ 1.0, 2.0 ] ); + +// Create an iterator: +var it = arr.keys(); + +// Iterate over keys... +var v = it.next().value; +// returns 0 + +v = it.next().value; +// returns 1 + +var bool = it.next().done; +// returns true +``` + + + +#### Float64Array.prototype.lastIndexOf( searchElement\[, fromIndex] ) + +Returns the index of the last array element strictly equal to a search element, iterating from right to left. + + + +```javascript +var arr = new Float64Array( [ 1.0, 0.0, 2.0, 0.0, 1.0 ] ); + +var idx = arr.lastIndexOf( 0.0 ); +// returns 3 + +idx = arr.lastIndexOf( 3.0 ); +// returns -1 +``` + +By default, the method searches the entire array (`fromIndex = -1`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Float64Array( [ 1.0, 0.0, 2.0, 0.0, 1.0 ] ); + +var idx = arr.lastIndexOf( 0.0, 2 ); +// returns 1 +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Float64Array( [ 1.0, 0.0, 2.0, 0.0, 1.0 ] ); + +var idx = arr.lastIndexOf( 0.0, -3 ); +// returns 1 +``` + +The method does **not** distinguish between signed and unsigned zero. + + + +#### Float64Array.prototype.map( fcn\[, thisArg] ) + +Maps each array element to an element in a new array having the same data type as the host array. + + + +```javascript +function fcn( v ) { + return v * 2.0; +} + +var arr1 = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.map( fcn ); +// returns [ 2.0, 4.0, 6.0 ] +``` + +A callback is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function fcn( v ) { + this.count += 1; + return v * 2.0; +} + +var ctx = { + 'count': 0 +}; + +var arr1 = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.map( fcn, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Float64Array.prototype.reduce( fcn\[, initialValue] ) + +Applies a function against an accumulator and each element in an array and returns the accumulated result. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Float64Array( [ 2.0, 1.0, 3.0 ] ); + +var v = arr.reduce( fcn ); +// returns 12.0 +``` + +If not provided an initial value, the method invokes a provided function with the first array element as the first argument and the second array element as the second argument. + +If provided an initial value, the method invokes a provided function with the initial value as the first argument and the first array element as the second argument. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Float64Array( [ 2.0, 1.0, 3.0 ] ); + +var v = arr.reduce( fcn, 0.0 ); +// returns 14.0 +``` + +A callback is provided four arguments: + +- `acc`: accumulated result +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + + + +#### Float64Array.prototype.reduceRight( fcn\[, initialValue] ) + +Applies a function against an accumulator and each element in an array and returns the accumulated result, iterating from right to left. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Float64Array( [ 2.0, 1.0, 3.0 ] ); + +var v = arr.reduceRight( fcn ); +// returns 8.0 +``` + +If not provided an initial value, the method invokes a provided function with the last array element as the first argument and the second-to-last array element as the second argument. + +If provided an initial value, the method invokes a provided function with the initial value as the first argument and the last array element as the second argument. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Float64Array( [ 2.0, 1.0, 3.0 ] ); + +var v = arr.reduce( fcn, 0.0 ); +// returns 14.0 +``` + +A callback is provided four arguments: + +- `acc`: accumulated result +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + + + +#### Float64Array.prototype.reverse() + +Reverses an array **in-place** (thus mutating the array on which the method is invoked). + + + +```javascript +var arr = new Float64Array( [ 2.0, 0.0, 3.0 ] ); + +// Reverse the array: +arr.reverse(); + +var v = arr[ 0 ]; +// returns 3.0 + +v = arr[ 1 ]; +// returns 0.0 + +v = arr[ 2 ]; +// returns 2.0 +``` + + + +#### Float64Array.prototype.set( arr\[, offset] ) + +Sets array elements. + + + +```javascript +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); +// returns [ 1.0, 2.0, 3.0 ] + +// Set the first two array elements: +arr.set( [ 4.0, 5.0 ] ); + +var v = arr[ 0 ]; +// returns 4.0 + +v = arr[ 1 ]; +// returns 5.0 +``` + +By default, the method starts writing values at the first array index. To specify an alternative index, provide an index `offset`. + + + +```javascript +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); +// returns [ 1.0, 2.0, 3.0 ] + +// Set the last two array elements: +arr.set( [ 4.0, 5.0 ], 1 ); + +var v = arr[ 1 ]; +// returns 4.0 + +v = arr[ 2 ]; +// returns 5.0 +``` + + + +#### Float64Array.prototype.slice( \[begin\[, end]] ) + +Copies array elements to a new array with the same underlying data type as the host array. + + + +```javascript +var arr1 = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.slice(); + +var bool = ( arr1 === arr2 ); +// returns false + +bool = ( arr1.buffer === arr2.buffer ); +// returns false + +var v = arr2[ 0 ]; +// returns 1.0 + +v = arr2[ 1 ]; +// returns 2.0 + +v = arr2[ 2 ]; +// returns 3.0 +``` + +By default, the method copies elements beginning with the first array element. To specify an alternative array index at which to begin copying, provide a `begin` index (inclusive). + + + +```javascript +var arr1 = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.slice( 1 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 2.0 + +v = arr2[ 1 ]; +// returns 3.0 +``` + +By default, the method copies all array elements after `begin`. To specify an alternative array index at which to end copying, provide an `end` index (exclusive). + + + +```javascript +var arr1 = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.slice( 0, 2 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 1.0 + +v = arr2[ 1 ]; +// returns 2.0 +``` + +When a `begin` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr1 = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.slice( -arr1.length, -1 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 1.0 + +v = arr2[ 1 ]; +// returns 2.0 +``` + + + +#### Float64Array.prototype.some( predicate\[, thisArg] ) + +Tests whether at least one array element passes a test implemented by a `predicate` function. + + + +```javascript +function predicate( v ) { + return ( v >= 2.0 ); +} + +var arr = new Float64Array( [ 1.0, 2.0 ] ); + +var bool = arr.some( predicate ); +// returns true +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 2.0 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Float64Array( [ 1.0, 1.0 ] ); + +var bool = arr.some( predicate, ctx ); +// returns false + +var n = ctx.count; +// returns 2 +``` + + + +#### Float64Array.prototype.sort( \[compareFunction] ) + +Sorts an array **in-place** (thus mutating the array on which the method is invoked). + + + +```javascript +var arr = new Float64Array( [ 2.0, 3.0, 0.0 ] ); + +// Sort the array (in ascending order): +arr.sort(); + +var v = arr[ 0 ]; +// returns 0.0 + +v = arr[ 1 ]; +// returns 2.0 + +v = arr[ 2 ]; +// returns 3.0 +``` + +By default, the method sorts array elements in ascending order. To impose a custom order, provide a `compareFunction`. + + + +```javascript +function descending( a, b ) { + return b - a; +} + +var arr = new Float64Array( [ 2.0, 3.0, 0.0 ] ); + +// Sort the array (in descending order): +arr.sort( descending ); + +var v = arr[ 0 ]; +// returns 3.0 + +v = arr[ 1 ]; +// returns 2.0 + +v = arr[ 2 ]; +// returns 0.0 +``` + +The comparison function is provided two array elements, `a` and `b`, per invocation, and its return value determines the sort order as follows: + +- If the comparison function returns a value **less** than zero, then the method sorts `a` to an index lower than `b` (i.e., `a` should come **before** `b`). +- If the comparison function returns a value **greater** than zero, then the method sorts `a` to an index higher than `b` (i.e., `b` should come **before** `a`). +- If the comparison function returns **zero**, then the relative order of `a` and `b` _should_ remain unchanged. + + + +#### Float64Array.prototype.subarray( \[begin\[, end]] ) + +Creates a new typed array view over the same underlying [`ArrayBuffer`][@stdlib/array/buffer] and with the same underlying data type as the host array. + + + +```javascript +var arr1 = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.subarray(); +// returns [ 1.0, 2.0, 3.0 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +By default, the method creates a typed array view beginning with the first array element. To specify an alternative array index at which to begin, provide a `begin` index (inclusive). + + + +```javascript +var arr1 = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.subarray( 1 ); +// returns [ 2.0, 3.0 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +By default, the method creates a typed array view which includes all array elements after `begin`. To limit the number of array elements after `begin`, provide an `end` index (exclusive). + + + +```javascript +var arr1 = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.subarray( 0, 2 ); +// returns [ 1.0, 2.0 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +When a `begin` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr1 = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.subarray( -arr1.length, -1 ); +// returns [ 1.0, 2.0 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +If the method is unable to resolve indices to a non-empty array subsequence, the method returns an empty typed array. + + + +```javascript +var arr1 = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var arr2 = arr1.subarray( 10, -1 ); +// returns [] +``` + + + +#### Float64Array.prototype.toLocaleString( \[locales\[, options]] ) + +Serializes an array as a locale-specific `string`. + + + +```javascript +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var str = arr.toLocaleString(); +// returns '1,2,3' +``` + + + +#### Float64Array.prototype.toString() + +Serializes an array as a `string`. + + + +```javascript +var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + +var str = arr.toString(); +// returns '1,2,3' +``` + + + +#### Float64Array.prototype.values() + +Returns an iterator for iterating over array elements. + + + +```javascript +var arr = new Float64Array( [ 1.0, 2.0 ] ); + +// Create an iterator: +var it = arr.values(); + +// Iterate over array elements... +var v = it.next().value; +// returns 1.0 + +v = it.next().value; +// returns 2.0 + +var bool = it.next().done; +// returns true +``` + +
+ + + +* * * + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var randu = require( '@stdlib/random/base/randu' ); +var ctor = require( '@stdlib/array/float64' ); + +var arr; +var i; + +arr = new ctor( 10 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = randu() * 100.0; +} +console.log( arr ); +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/float64/benchmark/benchmark.copy_within.js b/float64/benchmark/benchmark.copy_within.js new file mode 100644 index 00000000..52cb63a7 --- /dev/null +++ b/float64/benchmark/benchmark.copy_within.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':copyWithin', function benchmark( b ) { + var arr; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + arr = arr.copyWithin( 1, 0 ); + if ( arr[ 0 ] !== i ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/benchmark/benchmark.copy_within.length.js b/float64/benchmark/benchmark.copy_within.length.js new file mode 100644 index 00000000..ebfc0c95 --- /dev/null +++ b/float64/benchmark/benchmark.copy_within.length.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float64Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + arr = arr.copyWithin( 1, 0 ); + if ( arr[ 0 ] !== i ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':copyWithin:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.data.js b/float64/benchmark/benchmark.data.js new file mode 100644 index 00000000..f4a417b0 --- /dev/null +++ b/float64/benchmark/benchmark.data.js @@ -0,0 +1,75 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::get,index', function benchmark( b ) { + var arr; + var N; + var v; + var i; + + arr = new Float64Array( 2 ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr[ i%N ]; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::set,index', function benchmark( b ) { + var arr; + var N; + var i; + + arr = new Float64Array( 2 ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ i%N ] = i; + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] || arr[ 1 ] !== arr[ 1 ] ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/benchmark/benchmark.entries.js b/float64/benchmark/benchmark.entries.js new file mode 100644 index 00000000..0eee5195 --- /dev/null +++ b/float64/benchmark/benchmark.entries.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':entries', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Float64Array( [ 1.0, 2.0 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.entries(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/benchmark/benchmark.every.js b/float64/benchmark/benchmark.every.js new file mode 100644 index 00000000..7499ada3 --- /dev/null +++ b/float64/benchmark/benchmark.every.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':every', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0.0; + } +}); + +bench( pkg+'::this_context:every', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate, {} ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0.0; + } +}); diff --git a/float64/benchmark/benchmark.every.length.js b/float64/benchmark/benchmark.every.length.js new file mode 100644 index 00000000..b90ff3e2 --- /dev/null +++ b/float64/benchmark/benchmark.every.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value >= 0.0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float64Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':every:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.fill.js b/float64/benchmark/benchmark.fill.js new file mode 100644 index 00000000..7137c71f --- /dev/null +++ b/float64/benchmark/benchmark.fill.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':fill', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr = arr.fill( v ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/benchmark/benchmark.fill.length.js b/float64/benchmark/benchmark.fill.length.js new file mode 100644 index 00000000..f896f8ee --- /dev/null +++ b/float64/benchmark/benchmark.fill.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float64Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr = arr.fill( v ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':fill:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.filter.js b/float64/benchmark/benchmark.filter.js new file mode 100644 index 00000000..8e4ce6a5 --- /dev/null +++ b/float64/benchmark/benchmark.filter.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isFloat64Array = require( '@stdlib/assert/is-float64array' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':filter', function benchmark( b ) { + var arr; + var out; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat64Array( out ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0.0; + } +}); + +bench( pkg+'::this_context:filter', function benchmark( b ) { + var arr; + var out; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate, {} ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat64Array( out ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0.0; + } +}); diff --git a/float64/benchmark/benchmark.filter.length.js b/float64/benchmark/benchmark.filter.length.js new file mode 100644 index 00000000..ebcae45a --- /dev/null +++ b/float64/benchmark/benchmark.filter.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isFloat64Array = require( '@stdlib/assert/is-float64array' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value >= 0.0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float64Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat64Array( out ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':filter:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.find.js b/float64/benchmark/benchmark.find.js new file mode 100644 index 00000000..196c22c0 --- /dev/null +++ b/float64/benchmark/benchmark.find.js @@ -0,0 +1,82 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':find', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float64Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0.0; + } +}); + +bench( pkg+'::this_context:find', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float64Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate, {} ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0.0; + } +}); diff --git a/float64/benchmark/benchmark.find.length.js b/float64/benchmark/benchmark.find.length.js new file mode 100644 index 00000000..07c54448 --- /dev/null +++ b/float64/benchmark/benchmark.find.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0.0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - tuple length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float64Array( len ); + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':find:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.find_index.js b/float64/benchmark/benchmark.find_index.js new file mode 100644 index 00000000..44f1b1da --- /dev/null +++ b/float64/benchmark/benchmark.find_index.js @@ -0,0 +1,82 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':findIndex', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float64Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0.0; + } +}); + +bench( pkg+'::this_context:findIndex', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float64Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate, {} ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0.0; + } +}); diff --git a/float64/benchmark/benchmark.find_index.length.js b/float64/benchmark/benchmark.find_index.length.js new file mode 100644 index 00000000..78d12368 --- /dev/null +++ b/float64/benchmark/benchmark.find_index.length.js @@ -0,0 +1,104 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0.0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float64Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':findIndex:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.for_each.js b/float64/benchmark/benchmark.for_each.js new file mode 100644 index 00000000..a5d013bc --- /dev/null +++ b/float64/benchmark/benchmark.for_each.js @@ -0,0 +1,88 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':forEach', function benchmark( b ) { + var count; + var arr; + var N; + var i; + + arr = new Float64Array( 2 ); + N = arr.length; + + count = 0; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn ); + if ( count !== N*(i+1) ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( count !== N*i ) { + b.fail( 'unexpected result' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn() { + count += 1; + } +}); + +bench( pkg+'::this_context:forEach', function benchmark( b ) { + var count; + var arr; + var N; + var i; + + arr = new Float64Array( 2 ); + N = arr.length; + + count = 0; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn, {} ); + if ( count !== N*(i+1) ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( count !== N*i ) { + b.fail( 'unexpected result' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn() { + count += 1; + } +}); diff --git a/float64/benchmark/benchmark.for_each.length.js b/float64/benchmark/benchmark.for_each.length.js new file mode 100644 index 00000000..1b33a73f --- /dev/null +++ b/float64/benchmark/benchmark.for_each.length.js @@ -0,0 +1,106 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var count; + var arr; + + arr = new Float64Array( len ); + count = 0; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn ); + if ( count !== count ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( count !== count ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } + + /** + * Callback invoked for each tuple element. + * + * @private + */ + function fcn() { + count += 1; + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':forEach:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.from.js b/float64/benchmark/benchmark.from.js new file mode 100644 index 00000000..2d3e3759 --- /dev/null +++ b/float64/benchmark/benchmark.from.js @@ -0,0 +1,237 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var ITERATOR_SYMBOL = require( '@stdlib/symbol/iterator' ); +var isFloat64Array = require( '@stdlib/assert/is-float64array' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// VARIABLES // + +var opts = { + 'skip': ( ITERATOR_SYMBOL === null ) +}; + + +// MAIN // + +bench( pkg+'::typed_array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Float64Array( [ 1.0, 2.0 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Float64Array.from( buf ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isFloat64Array( arr ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array,clbk:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Float64Array( [ 1.0, 2.0 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Float64Array.from( buf, clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isFloat64Array( arr ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1.0; + } +}); + +bench( pkg+'::array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1.0, 2.0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Float64Array.from( buf ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isFloat64Array( arr ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::array,clbk:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1.0, 2.0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Float64Array.from( buf, clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isFloat64Array( arr ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1.0; + } +}); + +bench( pkg+'::iterable:from', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Float64Array.from( createIterable() ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isFloat64Array( arr ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out; + var i; + + out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + + i = 0; + + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + i += 1; + if ( i <= 2 ) { + return { + 'value': 0.0, + 'done': false + }; + } + return { + 'done': true + }; + } + } +}); + +bench( pkg+'::iterable,clbk:from:', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Float64Array.from( createIterable(), clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isFloat64Array( arr ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out; + var i; + + out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + + i = 0; + + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + i += 1; + if ( i <= 2 ) { + return { + 'value': 1.0, + 'done': false + }; + } + return { + 'done': true + }; + } + } + + function clbk( v ) { + return v + 1.0; + } +}); diff --git a/float64/benchmark/benchmark.includes.js b/float64/benchmark/benchmark.includes.js new file mode 100644 index 00000000..411edf6a --- /dev/null +++ b/float64/benchmark/benchmark.includes.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':includes', function benchmark( b ) { + var bool; + var arr; + var v; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1.0; + bool = arr.includes( v ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/benchmark/benchmark.includes.length.js b/float64/benchmark/benchmark.includes.length.js new file mode 100644 index 00000000..9c649244 --- /dev/null +++ b/float64/benchmark/benchmark.includes.length.js @@ -0,0 +1,96 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float64Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1.0; + bool = arr.includes( v ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':includes:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.index_of.js b/float64/benchmark/benchmark.index_of.js new file mode 100644 index 00000000..ccbf9a32 --- /dev/null +++ b/float64/benchmark/benchmark.index_of.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':indexOf', function benchmark( b ) { + var out; + var arr; + var v; + var i; + + arr = new Float64Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1.0; + out = arr.indexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/benchmark/benchmark.index_of.length.js b/float64/benchmark/benchmark.index_of.length.js new file mode 100644 index 00000000..6f574280 --- /dev/null +++ b/float64/benchmark/benchmark.index_of.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float64Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1.0; + out = arr.indexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':indexOf:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.join.js b/float64/benchmark/benchmark.join.js new file mode 100644 index 00000000..96c057f1 --- /dev/null +++ b/float64/benchmark/benchmark.join.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':join', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i % 127; + out = arr.join(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/benchmark/benchmark.join.length.js b/float64/benchmark/benchmark.join.length.js new file mode 100644 index 00000000..55bf7ae0 --- /dev/null +++ b/float64/benchmark/benchmark.join.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float64Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i % 127; + out = arr.join(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':join:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.js b/float64/benchmark/benchmark.js new file mode 100644 index 00000000..27c72668 --- /dev/null +++ b/float64/benchmark/benchmark.js @@ -0,0 +1,47 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isFloat64Array = require( '@stdlib/assert/is-float64array' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new ctor( 0 ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isFloat64Array( arr ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/benchmark/benchmark.keys.js b/float64/benchmark/benchmark.keys.js new file mode 100644 index 00000000..e01f172d --- /dev/null +++ b/float64/benchmark/benchmark.keys.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':keys', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.keys(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/benchmark/benchmark.last_index_of.js b/float64/benchmark/benchmark.last_index_of.js new file mode 100644 index 00000000..3bd0469b --- /dev/null +++ b/float64/benchmark/benchmark.last_index_of.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':lastIndexOf', function benchmark( b ) { + var out; + var arr; + var v; + var i; + + arr = new Float64Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1.0; + out = arr.lastIndexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/benchmark/benchmark.last_index_of.length.js b/float64/benchmark/benchmark.last_index_of.length.js new file mode 100644 index 00000000..4843100c --- /dev/null +++ b/float64/benchmark/benchmark.last_index_of.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float64Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1.0; + out = arr.lastIndexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':lastIndexOf:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.length.js b/float64/benchmark/benchmark.length.js new file mode 100644 index 00000000..5be86c40 --- /dev/null +++ b/float64/benchmark/benchmark.length.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isFloat64Array = require( '@stdlib/assert/is-float64array' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new ctor( len ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isFloat64Array( arr ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.map.js b/float64/benchmark/benchmark.map.js new file mode 100644 index 00000000..652e6483 --- /dev/null +++ b/float64/benchmark/benchmark.map.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isFloat64Array = require( '@stdlib/assert/is-float64array' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':map', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat64Array( out ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1.0; + } +}); + +bench( pkg+'::this_context:map', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn, {} ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat64Array( out ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1.0; + } +}); diff --git a/float64/benchmark/benchmark.map.length.js b/float64/benchmark/benchmark.map.length.js new file mode 100644 index 00000000..5b974ee4 --- /dev/null +++ b/float64/benchmark/benchmark.map.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isFloat64Array = require( '@stdlib/assert/is-float64array' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Maps an array element to a new value. +* +* @private +* @param {*} value - array element +* @returns {*} new value +*/ +function fcn( value ) { + return value + 1.0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float64Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat64Array( out ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':map:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.of.js b/float64/benchmark/benchmark.of.js new file mode 100644 index 00000000..25d5c5e3 --- /dev/null +++ b/float64/benchmark/benchmark.of.js @@ -0,0 +1,48 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isFloat64Array = require( '@stdlib/assert/is-float64array' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':of', function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Float64Array.of( i, 2.0 ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isFloat64Array( arr ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/benchmark/benchmark.properties.js b/float64/benchmark/benchmark.properties.js new file mode 100644 index 00000000..8fbfb46d --- /dev/null +++ b/float64/benchmark/benchmark.properties.js @@ -0,0 +1,145 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isArrayBuffer = require( '@stdlib/assert/is-arraybuffer' ); +var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::get:buffer', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.buffer; + if ( typeof v !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isArrayBuffer( v ) ) { + b.fail( 'should return an ArrayBuffer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteLength', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteLength; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteOffset', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteOffset; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:BYTES_PER_ELEMENT', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.BYTES_PER_ELEMENT; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:length', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.length; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/benchmark/benchmark.reduce.js b/float64/benchmark/benchmark.reduce.js new file mode 100644 index 00000000..fd1a058b --- /dev/null +++ b/float64/benchmark/benchmark.reduce.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reduce', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( acc, v ) { + return acc + v + 1.0; + } +}); + +bench( pkg+'::initial_value:reduce', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn, 3.14 ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1.0; + } +}); diff --git a/float64/benchmark/benchmark.reduce.length.js b/float64/benchmark/benchmark.reduce.length.js new file mode 100644 index 00000000..7b4fd883 --- /dev/null +++ b/float64/benchmark/benchmark.reduce.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Updates an accumulated value. +* +* @private +* @param {*} acc - accumulated value +* @param {*} value - array element +* @returns {*} accumulated value +*/ +function fcn( acc, value ) { + return acc + value + 1.0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float64Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reduce:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.reduce_right.js b/float64/benchmark/benchmark.reduce_right.js new file mode 100644 index 00000000..738859bb --- /dev/null +++ b/float64/benchmark/benchmark.reduce_right.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reduceRight', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( acc, v ) { + return acc + v + 1.0; + } +}); + +bench( pkg+'::initial_value:reduceRight', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn, 3.14 ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1.0; + } +}); diff --git a/float64/benchmark/benchmark.reduce_right.length.js b/float64/benchmark/benchmark.reduce_right.length.js new file mode 100644 index 00000000..bb2b39bf --- /dev/null +++ b/float64/benchmark/benchmark.reduce_right.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Updates an accumulated value. +* +* @private +* @param {*} acc - accumulated value +* @param {*} value - array element +* @returns {*} accumulated value +*/ +function fcn( acc, value ) { + return acc + value + 1.0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float64Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reduceRight:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.reverse.js b/float64/benchmark/benchmark.reverse.js new file mode 100644 index 00000000..972570e0 --- /dev/null +++ b/float64/benchmark/benchmark.reverse.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isFloat64Array = require( '@stdlib/assert/is-float64array' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reverse', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.reverse(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat64Array( out ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/benchmark/benchmark.reverse.length.js b/float64/benchmark/benchmark.reverse.length.js new file mode 100644 index 00000000..05138a82 --- /dev/null +++ b/float64/benchmark/benchmark.reverse.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isFloat64Array = require( '@stdlib/assert/is-float64array' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float64Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.reverse(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat64Array( out ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reverse:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.set.js b/float64/benchmark/benchmark.set.js new file mode 100644 index 00000000..026c58dd --- /dev/null +++ b/float64/benchmark/benchmark.set.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::array:set', function benchmark( b ) { + var values; + var buf; + var arr; + var N; + var v; + var i; + + values = []; + for ( i = 0; i < 10; i++ ) { + values.push( i ); + } + N = values.length; + + arr = new Float64Array( 2 ); + buf = [ 0.0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = values[ i%N ]; + v = arr.set( buf ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array:set', function benchmark( b ) { + var values; + var buf; + var arr; + var N; + var v; + var i; + + values = new Float64Array( 20 ); + N = values.length; + for ( i = 0; i < N; i++ ) { + values[ i ] = i; + } + + arr = new Float64Array( 2 ); + buf = new Float64Array( 1 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = values[ i%N ]; + v = arr.set( buf ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/benchmark/benchmark.set.length.js b/float64/benchmark/benchmark.set.length.js new file mode 100644 index 00000000..d93bcd49 --- /dev/null +++ b/float64/benchmark/benchmark.set.length.js @@ -0,0 +1,114 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randi = require( '@stdlib/random/base/randi' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var values; + var arr1; + var arr2; + var arr; + var N; + var i; + + arr1 = []; + arr2 = []; + for ( i = 0; i < len; i++ ) { + arr1.push( randi() ); + arr2.push( randi() ); + } + arr = new Float64Array( len ); + + values = [ + arr1, + arr2 + ]; + N = values.length; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr.set( values[ i%N ] ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':set:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.slice.js b/float64/benchmark/benchmark.slice.js new file mode 100644 index 00000000..27eb72d8 --- /dev/null +++ b/float64/benchmark/benchmark.slice.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isFloat64Array = require( '@stdlib/assert/is-float64array' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':slice', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.slice(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat64Array( out ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/benchmark/benchmark.slice.length.js b/float64/benchmark/benchmark.slice.length.js new file mode 100644 index 00000000..a808ebf9 --- /dev/null +++ b/float64/benchmark/benchmark.slice.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isFloat64Array = require( '@stdlib/assert/is-float64array' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float64Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.slice(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat64Array( out ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':slice:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.some.js b/float64/benchmark/benchmark.some.js new file mode 100644 index 00000000..9cec5ef7 --- /dev/null +++ b/float64/benchmark/benchmark.some.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':some', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0.0; + } +}); + +bench( pkg+'::this_context:some', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate, {} ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0.0; + } +}); diff --git a/float64/benchmark/benchmark.some.length.js b/float64/benchmark/benchmark.some.length.js new file mode 100644 index 00000000..efa5670b --- /dev/null +++ b/float64/benchmark/benchmark.some.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0.0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float64Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':some:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.sort.js b/float64/benchmark/benchmark.sort.js new file mode 100644 index 00000000..caf0421c --- /dev/null +++ b/float64/benchmark/benchmark.sort.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var randi = require( '@stdlib/random/base/randi' ); +var isFloat64Array = require( '@stdlib/assert/is-float64array' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':sort', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float64Array( [ randi(), randi() ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = randi(); + out = arr.sort(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat64Array( out ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/benchmark/benchmark.sort.length.js b/float64/benchmark/benchmark.sort.length.js new file mode 100644 index 00000000..9f27d46e --- /dev/null +++ b/float64/benchmark/benchmark.sort.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randi = require( '@stdlib/random/base/randi' ); +var isFloat64Array = require( '@stdlib/assert/is-float64array' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var data; + var arr; + var i; + + data = []; + for ( i = 0; i < len; i++ ) { + data.push( randi() ); + } + arr = new Float64Array( data ); + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ i%len ] = randi(); + out = arr.sort(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat64Array( out ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':sort:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.subarray.js b/float64/benchmark/benchmark.subarray.js new file mode 100644 index 00000000..797cd5e9 --- /dev/null +++ b/float64/benchmark/benchmark.subarray.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isFloat64Array = require( '@stdlib/assert/is-float64array' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':subarray', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.subarray(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat64Array( out ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/benchmark/benchmark.subarray.length.js b/float64/benchmark/benchmark.subarray.length.js new file mode 100644 index 00000000..fbfc2c33 --- /dev/null +++ b/float64/benchmark/benchmark.subarray.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isFloat64Array = require( '@stdlib/assert/is-float64array' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float64Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.subarray(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isFloat64Array( out ) ) { + b.fail( 'should return a Float64Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':subarray:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.to_locale_string.js b/float64/benchmark/benchmark.to_locale_string.js new file mode 100644 index 00000000..005b9334 --- /dev/null +++ b/float64/benchmark/benchmark.to_locale_string.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':toLocaleString', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toLocaleString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/benchmark/benchmark.to_locale_string.length.js b/float64/benchmark/benchmark.to_locale_string.length.js new file mode 100644 index 00000000..2a99382f --- /dev/null +++ b/float64/benchmark/benchmark.to_locale_string.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float64Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toLocaleString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':toLocaleString:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.to_string.js b/float64/benchmark/benchmark.to_string.js new file mode 100644 index 00000000..a7275fc6 --- /dev/null +++ b/float64/benchmark/benchmark.to_string.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':toString', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/benchmark/benchmark.to_string.length.js b/float64/benchmark/benchmark.to_string.length.js new file mode 100644 index 00000000..39f880d6 --- /dev/null +++ b/float64/benchmark/benchmark.to_string.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float64Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':toString:len='+len, f ); + } +} + +main(); diff --git a/float64/benchmark/benchmark.values.js b/float64/benchmark/benchmark.values.js new file mode 100644 index 00000000..4d4bca6a --- /dev/null +++ b/float64/benchmark/benchmark.values.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Float64Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':values', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Float64Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.values(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/float64/docs/repl.txt b/float64/docs/repl.txt new file mode 100644 index 00000000..73fac219 --- /dev/null +++ b/float64/docs/repl.txt @@ -0,0 +1,959 @@ + +{{alias}}() + A typed array constructor which returns a typed array representing an array + of double-precision floating-point numbers in the platform byte order. + + Returns + ------- + out: Float64Array + A typed array. + + Examples + -------- + > var arr = new {{alias}}() + + + +{{alias}}( length ) + Returns a typed array having a specified length. + + Parameters + ---------- + length: integer + Typed array length. + + Returns + ------- + out: Float64Array + A typed array. + + Examples + -------- + > var arr = new {{alias}}( 5 ) + [ 0.0, 0.0, 0.0, 0.0, 0.0 ] + + +{{alias}}( typedarray ) + Creates a typed array from another typed array. + + Parameters + ---------- + typedarray: TypedArray + Typed array from which to generate another typed array. + + Returns + ------- + out: Float64Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias:@stdlib/array/float32}}( [ 0.5, 0.5, 0.5 ] ); + > var arr2 = new {{alias}}( arr1 ) + [ 0.5, 0.5, 0.5 ] + + +{{alias}}( obj ) + Creates a typed array from an array-like object or iterable. + + Parameters + ---------- + obj: Object + Array-like object or iterable from which to generate a typed array. + + Returns + ------- + out: Float64Array + A typed array. + + Examples + -------- + > var arr1 = [ 0.5, 0.5, 0.5 ]; + > var arr2 = new {{alias}}( arr1 ) + [ 0.5, 0.5, 0.5 ] + + +{{alias}}( buffer[, byteOffset[, length]] ) + Returns a typed array view of an ArrayBuffer. + + Parameters + ---------- + buffer: ArrayBuffer + Underlying ArrayBuffer. + + byteOffset: integer (optional) + Integer byte offset specifying the location of the first typed array + element. Default: 0. + + length: integer (optional) + View length. If not provided, the view spans from the byteOffset to + the end of the underlying ArrayBuffer. + + Returns + ------- + out: Float64Array + A typed array. + + Examples + -------- + > var buf = new {{alias:@stdlib/array/buffer}}( 32 ); + > var arr = new {{alias}}( buf, 0, 4 ) + [ 0.0, 0.0, 0.0, 0.0 ] + + +{{alias}}.from( src[, map[, thisArg]] ) + Creates a new typed array from an array-like object or an iterable. + + A callback is provided the following arguments: + + - value: source value. + - index: source index. + + Parameters + ---------- + src: ArrayLike|Iterable + Source of array elements. + + map: Function (optional) + Callback to invoke for each source element. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Float64Array + A typed array. + + Examples + -------- + > function mapFcn( v ) { return v * 2.0; }; + > var arr = {{alias}}.from( [ 1.0, -1.0 ], mapFcn ) + [ 2.0, -2.0 ] + + +{{alias}}.of( element0[, element1[, ...elementN]] ) + Creates a new typed array from a variable number of arguments. + + Parameters + ---------- + element0: number + Array element. + + element1: number (optional) + Array element. + + elementN: number (optional) + Array elements. + + Returns + ------- + out: Float64Array + A typed array. + + Examples + -------- + > var arr = {{alias}}.of( 2.0, -2.0 ) + [ 2.0, -2.0 ] + + +{{alias}}.BYTES_PER_ELEMENT + Number of bytes per view element. + + Examples + -------- + > {{alias}}.BYTES_PER_ELEMENT + 8 + + +{{alias}}.name + Typed array constructor name. + + Examples + -------- + > {{alias}}.name + 'Float64Array' + + +{{alias}}.prototype.buffer + Read-only property which returns the ArrayBuffer referenced by the typed + array. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.buffer + + + +{{alias}}.prototype.byteLength + Read-only property which returns the length (in bytes) of the typed array. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.byteLength + 40 + + +{{alias}}.prototype.byteOffset + Read-only property which returns the offset (in bytes) of the typed array + from the start of its ArrayBuffer. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.byteOffset + 0 + + +{{alias}}.prototype.BYTES_PER_ELEMENT + Number of bytes per view element. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.BYTES_PER_ELEMENT + 8 + + +{{alias}}.prototype.length + Read-only property which returns the number of view elements. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.length + 5 + + +{{alias}}.prototype.copyWithin( target, start[, end] ) + Copies a sequence of elements within the array starting at `start` and + ending at `end` (non-inclusive) to the position starting at `target`. + + Parameters + ---------- + target: integer + Target start index position. + + start: integer + Source start index position. + + end: integer (optional) + Source end index position. Default: out.length. + + Returns + ------- + out: Float64Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 2.0, -2.0, 1.0, -1.0, 1.0 ] ); + > arr.copyWithin( 3, 0, 2 ); + > arr[ 3 ] + 2.0 + > arr[ 4 ] + -2.0 + + +{{alias}}.prototype.entries() + Returns an iterator for iterating over array key-value pairs. + + Returns + ------- + iter: Iterator + Iterator for iterating over array key-value pairs. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, -1.0 ] ); + > it = arr.entries(); + > it.next().value + [ 0, 1.0 ] + > it.next().value + [ 1, -1.0 ] + > it.next().done + true + + +{{alias}}.prototype.every( predicate[, thisArg] ) + Tests whether all array elements pass a test implemented by a predicate + function. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. If a predicate function + returns a truthy value, an array element passes; otherwise, an array + element fails. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + bool: boolean + Boolean indicating whether all array elements pass. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, -1.0 ] ); + > function predicate( v ) { return ( v >= 0.0 ); }; + > arr.every( predicate ) + false + + +{{alias}}.prototype.fill( value[, start[, end]] ) + Fills an array from a start index to an end index (non-inclusive) with a + provided value. + + Parameters + ---------- + value: number + Fill value. + + start: integer (optional) + Start index. If less than zero, the start index is resolved relative to + the last array element. Default: 0. + + end: integer (optional) + End index (non-inclusive). If less than zero, the end index is resolved + relative to the last array element. Default: out.length. + + Returns + ------- + out: Float64Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, -1.0 ] ); + > arr.fill( 2.0 ); + > arr[ 0 ] + 2.0 + > arr[ 1 ] + 2.0 + + +{{alias}}.prototype.filter( predicate[, thisArg] ) + Creates a new array which includes those elements for which a predicate + function returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + The returned array has the same data type as the host array. + + If a predicate function does not return a truthy value for any array + element, the method returns `null`. + + Parameters + ---------- + predicate: Function + Predicate function which filters array elements. If a predicate function + returns a truthy value, an array element is included in the output + array; otherwise, an array element is not included in the output array. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Float64Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > function predicate( v ) { return ( v >= 0.0 ); }; + > var arr2 = arr1.filter( predicate ); + > arr2.length + 2 + + +{{alias}}.prototype.find( predicate[, thisArg] ) + Returns the first array element for which a provided predicate function + returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + If a predicate function never returns a truthy value, the method returns + `undefined`. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + value: number|undefined + Array element. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > function predicate( v ) { return ( v < 0.0 ); }; + > var v = arr.find( predicate ) + -1.0 + + +{{alias}}.prototype.findIndex( predicate[, thisArg] ) + Returns the index of the first array element for which a provided predicate + function returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + If a predicate function never returns a truthy value, the method returns + `-1`. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + idx: integer + Array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > function predicate( v ) { return ( v < 0.0 ); }; + > var idx = arr.findIndex( predicate ) + 2 + + +{{alias}}.prototype.forEach( fcn[, thisArg] ) + Invokes a callback for each array element. + + A provided function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + fcn: Function + Function to invoke for each array element. + + thisArg: Any (optional) + Callback execution context. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > var str = ' '; + > function fcn( v, i ) { str += i + ':' + v + ' '; }; + > arr.forEach( fcn ); + > str + ' 0:1 1:0 2:-1 ' + + +{{alias}}.prototype.includes( searchElement[, fromIndex] ) + Returns a boolean indicating whether an array includes a search element. + + The method does not distinguish between signed and unsigned zero. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: 0. + + Returns + ------- + bool: boolean + Boolean indicating whether an array includes a search element. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > var bool = arr.includes( 2.0 ) + false + > bool = arr.includes( -1.0 ) + true + + +{{alias}}.prototype.indexOf( searchElement[, fromIndex] ) + Returns the index of the first array element strictly equal to a search + element. + + The method does not distinguish between signed and unsigned zero. + + If unable to locate a search element, the method returns `-1`. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: 0. + + Returns + ------- + idx: integer + Array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > var idx = arr.indexOf( 2.0 ) + -1 + > idx = arr.indexOf( -1.0 ) + 2 + + +{{alias}}.prototype.join( [separator] ) + Serializes an array by joining all array elements as a string. + + Parameters + ---------- + separator: string (optional) + String delineating array elements. Default: ','. + + Returns + ------- + str: string + Array serialized as a string. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > arr.join( '|' ) + '1|0|-1' + + +{{alias}}.prototype.keys() + Returns an iterator for iterating over array keys. + + Returns + ------- + iter: Iterator + Iterator for iterating over array keys. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, -1.0 ] ); + > it = arr.keys(); + > it.next().value + 0 + > it.next().value + 1 + > it.next().done + true + + +{{alias}}.prototype.lastIndexOf( searchElement[, fromIndex] ) + Returns the index of the last array element strictly equal to a search + element. + + The method iterates from the last array element to the first array element. + + The method does not distinguish between signed and unsigned zero. + + If unable to locate a search element, the method returns `-1`. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: -1. + + Returns + ------- + idx: integer + array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0, 0.0, 1.0 ] ); + > var idx = arr.lastIndexOf( 2.0 ) + -1 + > idx = arr.lastIndexOf( 0.0 ) + 3 + + +{{alias}}.prototype.map( fcn[, thisArg] ) + Maps each array element to an element in a new typed array. + + A provided function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + The returned array has the same data type as the host array. + + Parameters + ---------- + fcn: Function + Function which maps array elements to elements in the new array. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Float64Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > function fcn( v ) { return v * 2.0; }; + > var arr2 = arr1.map( fcn ); + [ 2.0, 0.0, -2.0 ] + + +{{alias}}.prototype.reduce( fcn[, initialValue] ) + Applies a function against an accumulator and each element in an array and + returns the accumulated result. + + The provided function is provided the following arguments: + + - acc: accumulated result. + - value: current array element. + - index: index of the current array element. + - arr: array on which the method is invoked. + + If provided an initial value, the method invokes a provided function with + the initial value as the first argument and the first array element as the + second argument. + + If not provided an initial value, the method invokes a provided function + with the first array element as the first argument and the second array + element as the second argument. + + Parameters + ---------- + fcn: Function + Function to apply. + + initialValue: Any (optional) + Initial accumulation value. + + Returns + ------- + out: Any + Accumulated result. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > function fcn( acc, v ) { return acc + (v*v); }; + > var v = arr.reduce( fcn, 0.0 ) + 2.0 + + +{{alias}}.prototype.reduceRight( fcn[, initialValue] ) + Applies a function against an accumulator and each element in an array and + returns the accumulated result, iterating from right to left. + + The provided function is provided the following arguments: + + - acc: accumulated result. + - value: current array element. + - index: index of the current array element. + - arr: array on which the method is invoked. + + If provided an initial value, the method invokes a provided function with + the initial value as the first argument and the last array element as the + second argument. + + If not provided an initial value, the method invokes a provided function + with the last array element as the first argument and the second-to-last + array element as the second argument. + + Parameters + ---------- + fcn: Function + Function to apply. + + initialValue: Any (optional) + Initial accumulation value. + + Returns + ------- + out: Any + Accumulated result. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > function fcn( acc, v ) { return acc + (v*v); }; + > var v = arr.reduceRight( fcn, 0.0 ) + 2.0 + + +{{alias}}.prototype.reverse() + Reverses an array *in-place*. + + This method mutates the array on which the method is invoked. + + Returns + ------- + out: Float64Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ) + [ 1.0, 0.0, -1.0 ] + > arr.reverse() + [ -1.0, 0.0, 1.0 ] + + +{{alias}}.prototype.set( arr[, offset] ) + Sets array elements. + + Parameters + ---------- + arr: ArrayLike + Source array containing array values to set. + + offset: integer (optional) + Array index at which to start writing values. Default: 0. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > arr.set( [ -2.0, 2.0 ], 1 ); + > arr[ 1 ] + -2.0 + > arr[ 2 ] + 2.0 + + +{{alias}}.prototype.slice( [begin[, end]] ) + Copies array elements to a new array with the same underlying data type as + the host array. + + If the method is unable to resolve indices to a non-empty array subsequence, + the method returns `null`. + + Parameters + ---------- + begin: integer (optional) + Start element index (inclusive). If less than zero, the start index is + resolved relative to the last array element. Default: 0. + + end: integer (optional) + End element index (exclusive). If less than zero, the end index is + resolved relative to the last array element. Default: arr.length. + + Returns + ------- + out: Float64Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1.0, 0.0, -1.0 ] ); + > var arr2 = arr1.slice( 1 ); + > arr2.length + 2 + > arr2[ 0 ] + 0.0 + > arr2[ 1 ] + -1.0 + + +{{alias}}.prototype.some( predicate[, thisArg] ) + Tests whether at least one array element passes a test implemented by a + predicate function. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. If a predicate function + returns a truthy value, a array element passes; otherwise, an array + element fails. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + bool: boolean + Boolean indicating whether at least one array element passes. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, -1.0 ] ); + > function predicate( v ) { return ( v < 0.0 ); }; + > arr.some( predicate ) + true + + +{{alias}}.prototype.sort( [compareFunction] ) + Sorts an array *in-place*. + + The comparison function is provided two array elements per invocation: `a` + and `b`. + + The comparison function return value determines the sort order as follows: + + - If the comparison function returns a value less than zero, then the method + sorts `a` to an index lower than `b` (i.e., `a` should come *before* `b`). + + - If the comparison function returns a value greater than zero, then the + method sorts `a` to an index higher than `b` (i.e., `b` should come *before* + `a`). + + - If the comparison function returns zero, then the relative order of `a` + and `b` should remain unchanged. + + This method mutates the array on which the method is invoked. + + Parameters + ---------- + compareFunction: Function (optional) + Function which specifies the sort order. The default sort order is + ascending order. + + Returns + ------- + out: Float64Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, -1.0, 0.0, 2.0, -2.0 ] ); + > arr.sort() + [ -2.0, -1.0, 0.0, 1.0, 2.0 ] + + +{{alias}}.prototype.subarray( [begin[, end]] ) + Creates a new typed array over the same underlying ArrayBuffer and with the + same underlying data type as the host array. + + If the method is unable to resolve indices to a non-empty array subsequence, + the method returns an empty typed array. + + Parameters + ---------- + begin: integer (optional) + Start element index (inclusive). If less than zero, the start index is + resolved relative to the last array element. Default: 0. + + end: integer (optional) + End element index (exclusive). If less than zero, the end index is + resolved relative to the last array element. Default: arr.length. + + Returns + ------- + out: Float64Array + A new typed array view. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1.0, -1.0, 0.0, 2.0, -2.0 ] ); + > var arr2 = arr1.subarray( 2 ) + [ 0.0, 2.0, -2.0 ] + + +{{alias}}.prototype.toLocaleString( [locales[, options]] ) + Serializes an array as a locale-specific string. + + Parameters + ---------- + locales: string|Array (optional) + A BCP 47 language tag, or an array of such tags. + + options: Object (optional) + Options. + + Returns + ------- + str: string + A typed array string representation. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, -1.0, 0.0 ] ); + > arr.toLocaleString() + '1,-1,0' + + +{{alias}}.prototype.toString() + Serializes an array as a string. + + Returns + ------- + str: string + A typed array string representation. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, -1.0, 0.0 ] ); + > arr.toString() + '1,-1,0' + + +{{alias}}.prototype.values() + Returns an iterator for iterating over array elements. + + Returns + ------- + iter: Iterator + Iterator for iterating over array elements. + + Examples + -------- + > var arr = new {{alias}}( [ 1.0, -1.0 ] ); + > it = arr.values(); + > it.next().value + 1.0 + > it.next().value + -1.0 + > it.next().done + true + + + See Also + -------- + diff --git a/float64/docs/types/index.d.ts b/float64/docs/types/index.d.ts new file mode 100644 index 00000000..815b76e6 --- /dev/null +++ b/float64/docs/types/index.d.ts @@ -0,0 +1,26 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +// EXPORTS // + +/** +* Typed array constructor which returns a typed array representing an array of double-precision floating-point numbers in the platform byte order. +*/ +export = Float64Array; diff --git a/float64/docs/types/test.ts b/float64/docs/types/test.ts new file mode 100644 index 00000000..70821049 --- /dev/null +++ b/float64/docs/types/test.ts @@ -0,0 +1,37 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// tslint:disable: no-construct +// tslint:disable: no-unused-expression + +import Float64Array = require( './index' ); + + +// TESTS // + +// The function returns a typed array instance... +{ + new Float64Array( 10 ); // $ExpectType Float64Array + new Float64Array( [ 2.1, 3.9, 5.2, 7.3 ] ); // $ExpectType Float64Array +} + +// The constructor function has to be invoked with `new`... +{ + Float64Array( 10 ); // $ExpectError + Float64Array( [ 2.1, 3.9, 5.2, 7.3 ] ); // $ExpectError +} diff --git a/float64/examples/index.js b/float64/examples/index.js new file mode 100644 index 00000000..a47829c7 --- /dev/null +++ b/float64/examples/index.js @@ -0,0 +1,31 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var randu = require( '@stdlib/random/base/randu' ); +var ctor = require( './../lib' ); + +var arr; +var i; + +arr = new ctor( 10 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = randu() * 100.0; +} +console.log( arr ); diff --git a/float64/lib/float64array.js b/float64/lib/float64array.js new file mode 100644 index 00000000..75b826d4 --- /dev/null +++ b/float64/lib/float64array.js @@ -0,0 +1,28 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MAIN // + +var ctor = ( typeof Float64Array === 'function' ) ? Float64Array : void 0; // eslint-disable-line stdlib/require-globals + + +// EXPORTS // + +module.exports = ctor; diff --git a/float64/lib/index.js b/float64/lib/index.js new file mode 100644 index 00000000..b1cb9b25 --- /dev/null +++ b/float64/lib/index.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Typed array constructor which returns a typed array representing an array of double-precision floating-point numbers in the platform byte order. +* +* @module @stdlib/array/float64 +* +* @example +* var ctor = require( '@stdlib/array/float64' ); +* +* var arr = new ctor( 10 ); +* // returns +*/ + +// MODULES // + +var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' ); +var builtin = require( './float64array.js' ); +var polyfill = require( './polyfill.js' ); + + +// MAIN // + +var ctor; +if ( hasFloat64ArraySupport() ) { + ctor = builtin; +} else { + ctor = polyfill; +} + + +// EXPORTS // + +module.exports = ctor; diff --git a/float64/lib/polyfill.js b/float64/lib/polyfill.js new file mode 100644 index 00000000..f5e8b1ae --- /dev/null +++ b/float64/lib/polyfill.js @@ -0,0 +1,37 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// TODO: write polyfill + +// MAIN // + +/** +* Typed array which represents an array of double-precision floating-point numbers in the platform byte order. +* +* @throws {Error} not implemented +*/ +function polyfill() { + throw new Error( 'not implemented' ); +} + + +// EXPORTS // + +module.exports = polyfill; diff --git a/float64/package.json b/float64/package.json new file mode 100644 index 00000000..cc999e00 --- /dev/null +++ b/float64/package.json @@ -0,0 +1,67 @@ +{ + "name": "@stdlib/array/float64", + "version": "0.0.0", + "description": "Float64Array.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structure", + "array", + "typed", + "typed array", + "typed-array", + "float64array", + "float64", + "double", + "double-precision", + "ieee754" + ] +} diff --git a/float64/test/test.copy_within.js b/float64/test/test.copy_within.js new file mode 100644 index 00000000..01647bc0 --- /dev/null +++ b/float64/test/test.copy_within.js @@ -0,0 +1,320 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var hasProp = require( '@stdlib/assert/has-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var Float64Array = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof Float64Array, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'a typed array instance has a `copyWithin` method for copying a sequence of elements within a typed array', function test( t ) { + var arr = new Float64Array( 2 ); + t.strictEqual( hasProp( arr, 'copyWithin' ), true, 'has property' ); + t.strictEqual( isFunction( arr.copyWithin ), true, 'has method' ); + t.end(); +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a typed array instance', function test( t ) { + var values; + var arr; + var i; + + arr = new Float64Array( 2 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0 ); + }; + } +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a typed array instance (end)', function test( t ) { + var values; + var arr; + var i; + + arr = new Float64Array( 2 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0, 5 ); + }; + } +}); + +tape( 'the method copies a sequence of elements within a typed array', function test( t ) { + var arr; + var p; + + arr = [ + 0.0, + 1.0, + 2.0, + 3.0, + 4.0 + ]; + + p = new Float64Array( arr ); + p.copyWithin( 0, 3 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3.0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4.0, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2.0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3.0, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4.0, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative target)', function test( t ) { + var arr; + var p; + + arr = [ + 0.0, + 1.0, + 2.0, + 3.0, + 4.0 + ]; + + p = new Float64Array( arr ); + p.copyWithin( -p.length, 3 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3.0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4.0, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2.0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3.0, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4.0, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative start)', function test( t ) { + var arr; + var p; + + arr = [ + 0.0, + 1.0, + 2.0, + 3.0, + 4.0 + ]; + + p = new Float64Array( arr ); + p.copyWithin( 0, -2 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3.0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4.0, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2.0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3.0, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4.0, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (end=length)', function test( t ) { + var arr; + var p; + + arr = [ + 0.0, + 1.0, + 2.0, + 3.0, + 4.0 + ]; + + p = new Float64Array( arr ); + p.copyWithin( 0, 3, p.length ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3.0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4.0, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2.0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3.0, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4.0, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (non-inclusive end)', function test( t ) { + var arr; + var p; + + arr = [ + 0.0, + 1.0, + 2.0, + 3.0, + 4.0 + ]; + + p = new Float64Array( arr ); + p.copyWithin( 2, 0, 2 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0.0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1.0, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0.0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1.0, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 4 ], 4.0, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative end)', function test( t ) { + var arr; + var p; + + arr = [ + 0.0, + 1.0, + 2.0, + 3.0, + 4.0 + ]; + + p = new Float64Array( arr ); + p.copyWithin( 2, 0, -3 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0.0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1.0, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0.0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1.0, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 4 ], 4.0, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (target >= length)', function test( t ) { + var arr; + var p; + + arr = [ + 0.0, + 1.0, + 2.0, + 3.0, + 4.0 + ]; + + p = new Float64Array( arr ); + p.copyWithin( p.length, 3 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0.0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1.0, 'returns expected value' ); + t.strictEqual( p[ 2 ], 2.0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3.0, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4.0, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (target > start)', function test( t ) { + var arr; + var p; + + arr = [ + 0.0, + 1.0, + 2.0, + 3.0, + 4.0 + ]; + + p = new Float64Array( arr ); + p.copyWithin( 2, 0 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0.0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1.0, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0.0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1.0, 'returns expected value' ); + t.strictEqual( p[ 4 ], 2.0, 'returns expected value' ); + + t.end(); +}); diff --git a/float64/test/test.js b/float64/test/test.js new file mode 100644 index 00000000..cbf283b9 --- /dev/null +++ b/float64/test/test.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' ); +var polyfill = require( './../lib/polyfill.js' ); +var ctor = require( './../lib' ); + + +// VARIABLES // + +var hasFloat64Arrays = hasFloat64ArraySupport(); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'if an environment supports `Float64Array`, the export is an alias for `Float64Array`', function test( t ) { + var Foo; + + Foo = proxyquire( './../lib', { + '@stdlib/assert/has-float64array-support': isTrue, + './float64array.js': Mock + }); + t.strictEqual( Foo, Mock, 'returns builtin' ); + + if ( hasFloat64Arrays ) { + t.strictEqual( ctor, Float64Array, 'is alias' ); // eslint-disable-line stdlib/require-globals + } + + t.end(); + + function Mock() { + return this; + } + + function isTrue() { + return true; + } +}); + +tape( 'if an environment does not support `Float64Array`, the export is a polyfill', function test( t ) { + var Foo; + + Foo = proxyquire( './../lib', { + '@stdlib/assert/has-float64array-support': isFalse + }); + + t.strictEqual( Foo, polyfill, 'returns polyfill' ); + t.end(); + + function isFalse() { + return false; + } +}); diff --git a/float64/test/test.polyfill.js b/float64/test/test.polyfill.js new file mode 100644 index 00000000..9d6fcb19 --- /dev/null +++ b/float64/test/test.polyfill.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var ctor = require( './../lib/polyfill.js' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error when invoked', function test( t ) { + t.throws( foo, Error, 'throws an error' ); + t.end(); + + function foo() { + var f = new ctor(); // eslint-disable-line no-unused-vars + } +}); + +// TODO: tests diff --git a/from-iterator/README.md b/from-iterator/README.md new file mode 100644 index 00000000..e0b13d75 --- /dev/null +++ b/from-iterator/README.md @@ -0,0 +1,197 @@ + + +# iterator2array + +> Create (or fill) an array from an iterator. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var iterator2array = require( '@stdlib/array/from-iterator' ); +``` + +#### iterator2array( iterator\[, out]\[, mapFcn\[, thisArg]] ) + +Creates (or fills) an array from an `iterator`. + +```javascript +var randu = require( '@stdlib/random/iter/randu' ); + +var opts = { + 'iter': 10 +}; + +var arr = iterator2array( randu( opts ) ); +// returns +``` + +By default, the function creates and fills a generic `array`. To fill an array-like `object`, provide an `out` argument. + +```javascript +var Float64Array = require( '@stdlib/array/float64' ); +var randu = require( '@stdlib/random/iter/randu' ); + +var out = new Float64Array( 10 ); + +var arr = iterator2array( randu(), out ); +// returns + +var bool = ( out === arr ); +// returns true +``` + +To invoke a function for each iterated value, provide a callback function. + +```javascript +var array2iterator = require( '@stdlib/array/to-iterator' ); + +function fcn( v ) { + return v * 10.0; +} + +var arr = iterator2array( array2iterator( [ 1, 2, 3, 4 ] ), fcn ); +// returns [ 10.0, 20.0, 30.0, 40.0 ] +``` + +The invoked function is provided two arguments: + +- `value`: iterated value +- `index`: iterated value index + +```javascript +var Float64Array = require( '@stdlib/array/float64' ); +var randu = require( '@stdlib/random/iter/randu' ); + +function fcn( v, i ) { + return v * (i+1); +} + +var arr = iterator2array( randu(), new Float64Array( 10 ), fcn ); +// returns +``` + +To set the callback function execution context, provide a `thisArg`. + +```javascript +var Float64Array = require( '@stdlib/array/float64' ); +var randu = require( '@stdlib/random/iter/randu' ); + +function fcn( v ) { + this.count += 1; + return v * 10.0; +} + +var ctx = { + 'count': 0 +}; + +var arr = iterator2array( randu(), new Float64Array( 10 ), fcn, ctx ); +// returns + +var count = ctx.count; +// returns 10 +``` + +
+ + + + + +
+ +## Notes + +- If provided an output array, the function fills the output array with iterated values. +- Iteration stops when an output array is full **or** an iterator finishes; whichever comes first. +- By providing an output typed array, one avoids the temporary memory allocation when using the built-in `TypedArray.from`. + +
+ + + + + +
+ +## Examples + + + +```javascript +var Float64Array = require( '@stdlib/array/float64' ); +var randu = require( '@stdlib/random/iter/randu' ); +var iterator2array = require( '@stdlib/array/from-iterator' ); + +var opts; +var arr; +var it; +var i; + +function scale( v, i ) { + return v * (i+1); +} + +// Create an iterator for generating uniformly distributed pseudorandom numbers: +opts = { + 'iter': 10 +}; +it = randu( opts ); + +// Fill an array with scaled iterator values: +arr = iterator2array( it, new Float64Array( opts.iter ), scale ); + +for ( i = 0; i < arr.length; i++ ) { + console.log( arr[ i ] ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/from-iterator/benchmark/benchmark.js b/from-iterator/benchmark/benchmark.js new file mode 100644 index 00000000..7f7d74c4 --- /dev/null +++ b/from-iterator/benchmark/benchmark.js @@ -0,0 +1,130 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isArray = require( '@stdlib/assert/is-array' ); +var array2iterator = require( '@stdlib/array/to-iterator' ); +var pkg = require( './../package.json' ).name; +var iterator2array = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var values; + var arr; + var i; + + values = array2iterator( [ 1, 2, 3, 4 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = iterator2array( values ); + if ( !isArray( arr ) ) { + b.fail( 'should return an array' ); + } + } + b.toc(); + if ( !isArray( arr ) ) { + b.fail( 'should return an array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::map', function benchmark( b ) { + var values; + var arr; + var i; + + values = array2iterator( [ 1, 2, 3, 4 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = iterator2array( values, transform ); + if ( !isArray( arr ) ) { + b.fail( 'should return an array' ); + } + } + b.toc(); + if ( !isArray( arr ) ) { + b.fail( 'should return an array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function transform( v, i ) { + return v + i; + } +}); + +bench( pkg+'::fill', function benchmark( b ) { + var values; + var arr; + var out; + var i; + + values = array2iterator( [ 1, 2, 3, 4 ] ); + out = [ 0, 0, 0, 0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = iterator2array( values, out ); + if ( !isArray( arr ) ) { + b.fail( 'should return an array' ); + } + } + b.toc(); + if ( !isArray( arr ) || arr !== out ) { + b.fail( 'should return an array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::map,fill', function benchmark( b ) { + var values; + var arr; + var out; + var i; + + values = array2iterator( [ 1, 2, 3, 4 ] ); + out = [ 0, 0, 0, 0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = iterator2array( values, out, transform ); + if ( !isArray( arr ) ) { + b.fail( 'should return an array' ); + } + } + b.toc(); + if ( !isArray( arr ) || arr !== out ) { + b.fail( 'should return an array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function transform( v, i ) { + return v + i; + } +}); diff --git a/from-iterator/docs/repl.txt b/from-iterator/docs/repl.txt new file mode 100644 index 00000000..7813ee59 --- /dev/null +++ b/from-iterator/docs/repl.txt @@ -0,0 +1,42 @@ + +{{alias}}( iterator[, out][, mapFcn[, thisArg]] ) + Creates (or fills) an array from an iterator. + + When invoked, an input function is provided two arguments: + + - value: iterated value + - index: iterated value index (zero-based) + + If provided an output array, the function fills the output array with + iterated values. + + Iteration stops when an output array is full or an iterator finishes; + whichever comes first. + + Parameters + ---------- + iterator: Object + Source iterator. + + out: ArrayLikeObject (optional) + Output array-like object. + + mapFcn: Function (optional) + Function to invoke for each iterated value. + + thisArg: any (optional) + Execution context. + + Returns + ------- + out: ArrayLikeObject + Output array. + + Examples + -------- + > var opts = { 'iter': 10 }; + > var arr = {{alias}}( {{alias:@stdlib/random/iter/randu}}( opts ) ) + + See Also + -------- + diff --git a/from-iterator/docs/types/index.d.ts b/from-iterator/docs/types/index.d.ts new file mode 100644 index 00000000..19780434 --- /dev/null +++ b/from-iterator/docs/types/index.d.ts @@ -0,0 +1,108 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/// + +import { Iterator as Iter, IterableIterator } from '@stdlib/types/iter'; +import { Collection } from '@stdlib/types/object'; + +// Define a union type representing both iterable and non-iterable iterators: +type Iterator = Iter | IterableIterator; + +/** +* Map function invoked for each iterated value. +* +* @returns iterator value +*/ +type Nullary = () => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @returns iterator value +*/ +type Unary = ( value: any ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @returns iterator value +*/ +type Binary = ( value: any, index: number ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @returns iterator value +*/ +type MapFunction = Nullary | Unary | Binary; + +/** +* Creates (or fills) an array from an iterator. +* +* @param iterator - source iterator +* @param mapFcn - function to invoke for each iterated value +* @param thisArg - execution context +* @returns output array +* +* @example +* var randu = require( `@stdlib/random/iter/randu` ); +* +* var iter = randu({ +* 'iter': 10 +* }); +* +* var arr = iterator2array( iter ); +* // returns +*/ +declare function iterator2array( iterator: Iterator, mapFcn?: MapFunction, thisArg?: any ): Collection; // tslint:disable-line:max-line-length + +/** +* Creates (or fills) an array from an iterator. +* +* @param iterator - source iterator +* @param out - output array +* @param mapFcn - function to invoke for each iterated value +* @param thisArg - execution context +* @returns output array +* +* @example +* var Float64Array = require( `@stdlib/array/float64` ); +* var randu = require( `@stdlib/random/iter/randu` ); +* +* var iter = randu({ +* 'iter': 10 +* }); +* +* var out = new Float64Array( 10 ); +* var arr = iterator2array( iter, out ); +* // returns +*/ +declare function iterator2array( iterator: Iterator, out: Collection, mapFcn?: MapFunction, thisArg?: any ): Collection; // tslint:disable-line:max-line-length + + +// EXPORTS // + +export = iterator2array; diff --git a/from-iterator/docs/types/test.ts b/from-iterator/docs/types/test.ts new file mode 100644 index 00000000..67042955 --- /dev/null +++ b/from-iterator/docs/types/test.ts @@ -0,0 +1,87 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import randu = require( '@stdlib/random/iter/randu' ); +import iterator2array = require( './index' ); + +/** +* Multiplies a value by 10. +* +* @param v - iterated value +* @returns new value +*/ +function times10( v: number ): number { + return v * 10.0; +} + + +// TESTS // + +// The function returns an iterator... +{ + const iter = randu(); + iterator2array( iter ); // $ExpectType Collection + iterator2array( iter, times10 ); // $ExpectType Collection + iterator2array( iter, times10, {} ); // $ExpectType Collection + const out = new Float64Array( 10 ); + iterator2array( iter, out ); // $ExpectType Collection + iterator2array( iter, out, times10 ); // $ExpectType Collection + iterator2array( iter, out, times10, {} ); // $ExpectType Collection +} + +// The compiler throws an error if the function is provided a first argument which is not an iterator... +{ + iterator2array( 'abc' ); // $ExpectError + iterator2array( 123 ); // $ExpectError + iterator2array( true ); // $ExpectError + iterator2array( false ); // $ExpectError + iterator2array( {} ); // $ExpectError + iterator2array( [] ); // $ExpectError + iterator2array( null ); // $ExpectError + iterator2array( undefined ); // $ExpectError +} + +// The compiler throws an error if the function is provided a second argument which is not a map function or output array... +{ + const iter = randu(); + iterator2array( iter, 123 ); // $ExpectError + iterator2array( iter, {} ); // $ExpectError + iterator2array( iter, true ); // $ExpectError + iterator2array( iter, false ); // $ExpectError + iterator2array( iter, null ); // $ExpectError +} + +// The compiler throws an error if the function is provided a third argument which is not a map function (when provided an output array)... +{ + const iter = randu(); + const out = new Float64Array( 10 ); + iterator2array( iter, out, 'abc' ); // $ExpectError + iterator2array( iter, out, 123 ); // $ExpectError + iterator2array( iter, out, [] ); // $ExpectError + iterator2array( iter, out, {} ); // $ExpectError + iterator2array( iter, out, true ); // $ExpectError + iterator2array( iter, out, false ); // $ExpectError + iterator2array( iter, out, null ); // $ExpectError +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + const iter = randu(); + iterator2array(); // $ExpectError + iterator2array( iter, [], times10, {}, {} ); // $ExpectError +} diff --git a/from-iterator/examples/index.js b/from-iterator/examples/index.js new file mode 100644 index 00000000..78c9ee02 --- /dev/null +++ b/from-iterator/examples/index.js @@ -0,0 +1,45 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var Float64Array = require( '@stdlib/array/float64' ); +var randu = require( '@stdlib/random/iter/randu' ); +var iterator2array = require( './../lib' ); + +var opts; +var arr; +var it; +var i; + +function scale( v, i ) { + return v * (i+1); +} + +// Create an iterator for generating uniformly distributed pseudorandom numbers: +opts = { + 'iter': 10 +}; +it = randu( opts ); + +// Fill an array with scaled iterator values: +arr = iterator2array( it, new Float64Array( opts.iter ), scale ); + +for ( i = 0; i < arr.length; i++ ) { + console.log( arr[ i ] ); +} diff --git a/from-iterator/lib/index.js b/from-iterator/lib/index.js new file mode 100644 index 00000000..7be53da8 --- /dev/null +++ b/from-iterator/lib/index.js @@ -0,0 +1,45 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Create (or fill) an array from an iterator. +* +* @module @stdlib/array/from-iterator +* +* @example +* var randu = require( '@stdlib/random/iter/randu' ); +* var iterator2array = require( '@stdlib/array/from-iterator' ); +* +* var iter = randu({ +* 'iter': 10 +* }); +* +* var arr = iterator2array( iter ); +* // returns +*/ + +// MODULES // + +var main = require( './main.js' ); + + +// EXPORTS // + +module.exports = main; diff --git a/from-iterator/lib/main.js b/from-iterator/lib/main.js new file mode 100644 index 00000000..52bc68ac --- /dev/null +++ b/from-iterator/lib/main.js @@ -0,0 +1,140 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isFunction = require( '@stdlib/assert/is-function' ); +var isCollection = require( '@stdlib/assert/is-collection' ); +var isIteratorLike = require( '@stdlib/assert/is-iterator-like' ); +var hasOwnProp = require( '@stdlib/assert/has-own-property' ); + + +// MAIN // + +/** +* Creates (or fills) an array from an iterator. +* +* @param {Iterator} iterator - source iterator +* @param {Collection} [out] - output array +* @param {Function} [mapFcn] - function to invoke for each iterated value +* @param {*} [thisArg] - execution context +* @throws {TypeError} iterator argument must be an iterator +* @throws {TypeError} callback argument must be a function +* @returns {Collection} output array +* +* @example +* var randu = require( '@stdlib/random/iter/randu' ); +* +* var iter = randu({ +* 'iter': 10 +* }); +* +* var arr = iterator2array( iter ); +* // returns +*/ +function iterator2array() { + var iterator; + var thisArg; + var fcn; + var out; + var len; + var i; + var v; + + iterator = arguments[ 0 ]; + if ( arguments.length > 1 ) { + if ( isCollection( arguments[ 1 ] ) ) { + out = arguments[ 1 ]; + if ( arguments.length > 2 ) { + fcn = arguments[ 2 ]; + if ( !isFunction( fcn ) ) { + throw new TypeError( 'invalid argument. Callback argument must be a function. Value: `' + fcn + '`.' ); + } + thisArg = arguments[ 3 ]; + } + } else { + fcn = arguments[ 1 ]; + if ( !isFunction( fcn ) ) { + throw new TypeError( 'invalid argument. Callback argument must be a function. Value: `' + fcn + '`.' ); + } + thisArg = arguments[ 2 ]; + } + } + if ( !isIteratorLike( iterator ) ) { + throw new TypeError( 'invalid argument. Iterator argument must be an iterator protocol-compliant object. Value: `' + iterator + '`.' ); + } + i = -1; + if ( out === void 0 ) { + out = []; + if ( fcn ) { + while ( true ) { + i += 1; + v = iterator.next(); + if ( hasOwnProp( v, 'value' ) ) { + out.push( fcn.call( thisArg, v.value, i ) ); + } + if ( v.done ) { + break; + } + } + return out; + } + while ( true ) { + v = iterator.next(); + if ( hasOwnProp( v, 'value' ) ) { + out.push( v.value ); + } + if ( v.done ) { + break; + } + } + return out; + } + len = out.length; + if ( fcn ) { + while ( i < len-1 ) { + i += 1; + v = iterator.next(); + if ( hasOwnProp( v, 'value' ) ) { + out[ i ] = fcn.call( thisArg, v.value, i ); + } + if ( v.done ) { + break; + } + } + return out; + } + while ( i < len-1 ) { + i += 1; + v = iterator.next(); + if ( hasOwnProp( v, 'value' ) ) { + out[ i ] = v.value; + } + if ( v.done ) { + break; + } + } + return out; +} + + +// EXPORTS // + +module.exports = iterator2array; diff --git a/from-iterator/package.json b/from-iterator/package.json new file mode 100644 index 00000000..a9e3e970 --- /dev/null +++ b/from-iterator/package.json @@ -0,0 +1,72 @@ +{ + "name": "@stdlib/array/from-iterator", + "version": "0.0.0", + "description": "Create (or fill) an array from an iterator.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "utils", + "util", + "utilities", + "utility", + "typed", + "array", + "arr", + "typed-array", + "typed array", + "iterator", + "iterate", + "iteration", + "iter", + "to", + "convert", + "fill", + "map" + ] +} diff --git a/from-iterator/test/test.js b/from-iterator/test/test.js new file mode 100644 index 00000000..9d66ad27 --- /dev/null +++ b/from-iterator/test/test.js @@ -0,0 +1,554 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var noop = require( '@stdlib/utils/noop' ); +var randu = require( '@stdlib/random/iter/randu' ); +var Float64Array = require( '@stdlib/array/float64' ); +var array2iterator = require( '@stdlib/array/to-iterator' ); +var iterator2array = require( './../lib' ); + + +// FUNCTIONS // + +function createIterator( arr ) { + var len; + var it; + var i; + + len = arr.length; + i = -1; + + it = {}; + it.next = next; + + return it; + + function next() { + var out; + i += 1; + if ( i < len ) { + out = {}; + out.value = arr[ i ]; + out.done = ( i === len-1 ); + return out; + } + return { + 'done': true + }; + } +} + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.equal( typeof iterator2array, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error if provided an iterator argument which is not an iterator', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [], + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + iterator2array( value ); + }; + } +}); + +tape( 'the function throws an error if provided an iterator argument which is not an iterator (callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [], + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + iterator2array( value, noop ); + }; + } +}); + +tape( 'the function throws an error if provided an iterator argument which is not an iterator (output argument)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [], + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + iterator2array( value, [] ); + }; + } +}); + +tape( 'the function throws an error if provided an iterator argument which is not an iterator (output + callback arguments)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [], + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + iterator2array( value, [], noop ); + }; + } +}); + +tape( 'the function throws an error if provided a callback argument which is not a function', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + iterator2array( randu(), value ); + }; + } +}); + +tape( 'the function throws an error if provided a callback argument which is not a function (output argument)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + [], + {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + iterator2array( randu(), [], value ); + }; + } +}); + +tape( 'the function throws an error if provided insufficient arguments', function test( t ) { + t.throws( iterator2array, TypeError, 'throws an error' ); + t.end(); +}); + +tape( 'the function creates an array from an iterator', function test( t ) { + var expected; + var values; + var actual; + var it; + + values = [ 1, 2, 3, 4 ]; + it = array2iterator( values ); + + actual = iterator2array( it ); + expected = values; + + t.deepEqual( actual, expected, 'returns expected value' ); + t.end(); +}); + +tape( 'the function creates an array from an iterator (value+done)', function test( t ) { + var expected; + var values; + var actual; + var it; + + values = [ 1, 2, 3, 4 ]; + it = createIterator( values ); + + actual = iterator2array( it ); + expected = values; + + t.deepEqual( actual, expected, 'returns expected value' ); + t.end(); +}); + +tape( 'the function supports providing a callback to be invoked for each iterated value', function test( t ) { + var expected; + var values; + var actual; + var it; + + values = [ 1, 2, 3, 4 ]; + it = array2iterator( values ); + + actual = iterator2array( it, scale ); + expected = [ 1, 4, 9, 16 ]; + + t.deepEqual( actual, expected, 'returns expected value' ); + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'the function supports providing a callback to be invoked for each iterated value (value+done)', function test( t ) { + var expected; + var values; + var actual; + var it; + + values = [ 1, 2, 3, 4 ]; + it = createIterator( values ); + + actual = iterator2array( it, scale ); + expected = [ 1, 4, 9, 16 ]; + + t.deepEqual( actual, expected, 'returns expected value' ); + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'the function supports filling a provided output array', function test( t ) { + var expected; + var values; + var actual; + var out; + var it; + + values = [ 1, 2, 3, 4 ]; + it = array2iterator( values ); + + out = new Float64Array( values.length ); + actual = iterator2array( it, out ); + expected = new Float64Array( values ); + + t.equal( actual, out, 'returns expected value' ); + t.deepEqual( actual, expected, 'returns expected value' ); + t.end(); +}); + +tape( 'the function supports filling a provided output array (short iterator)', function test( t ) { + var expected; + var values; + var actual; + var out; + var it; + + values = [ 1, 2 ]; + it = array2iterator( values ); + + out = new Float64Array( 4 ); + actual = iterator2array( it, out ); + expected = new Float64Array( [ 1, 2, 0, 0 ] ); + + t.equal( actual, out, 'returns expected value' ); + t.deepEqual( actual, expected, 'returns expected value' ); + t.end(); +}); + +tape( 'the function supports filling a provided output array (value+done)', function test( t ) { + var expected; + var values; + var actual; + var out; + var it; + + values = [ 1, 2, 3, 4 ]; + it = createIterator( values ); + + out = new Float64Array( values.length ); + actual = iterator2array( it, out ); + expected = new Float64Array( values ); + + t.equal( actual, out, 'returns expected value' ); + t.deepEqual( actual, expected, 'returns expected value' ); + t.end(); +}); + +tape( 'the function supports filling a provided output array (value+done; short iterator)', function test( t ) { + var expected; + var values; + var actual; + var out; + var it; + + values = [ 1, 2 ]; + it = createIterator( values ); + + out = new Float64Array( 4 ); + actual = iterator2array( it, out ); + expected = new Float64Array( [ 1, 2, 0, 0 ] ); + + t.equal( actual, out, 'returns expected value' ); + t.deepEqual( actual, expected, 'returns expected value' ); + t.end(); +}); + +tape( 'the function supports filling a provided output array (callback)', function test( t ) { + var expected; + var values; + var actual; + var out; + var it; + + values = [ 1, 2, 3, 4 ]; + it = array2iterator( values ); + + out = new Float64Array( values.length ); + actual = iterator2array( it, out, scale ); + expected = new Float64Array( [ 1, 4, 9, 16 ] ); + + t.equal( actual, out, 'returns expected value' ); + t.deepEqual( actual, expected, 'returns expected value' ); + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'the function supports filling a provided output array (callback; short iterator)', function test( t ) { + var expected; + var values; + var actual; + var out; + var it; + + values = [ 1, 2 ]; + it = array2iterator( values ); + + out = new Float64Array( 4 ); + actual = iterator2array( it, out, scale ); + expected = new Float64Array( [ 1, 4, 0, 0 ] ); + + t.equal( actual, out, 'returns expected value' ); + t.deepEqual( actual, expected, 'returns expected value' ); + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'the function supports filling a provided output array (value+done; callback)', function test( t ) { + var expected; + var values; + var actual; + var out; + var it; + + values = [ 1, 2, 3, 4 ]; + it = createIterator( values ); + + out = new Float64Array( values.length ); + actual = iterator2array( it, out, scale ); + expected = new Float64Array( [ 1, 4, 9, 16 ] ); + + t.equal( actual, out, 'returns expected value' ); + t.deepEqual( actual, expected, 'returns expected value' ); + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'the function supports filling a provided output array (value+done; callback; short iterator)', function test( t ) { + var expected; + var values; + var actual; + var out; + var it; + + values = [ 1, 2 ]; + it = createIterator( values ); + + out = new Float64Array( 4 ); + actual = iterator2array( it, out, scale ); + expected = new Float64Array( [ 1, 4, 0, 0 ] ); + + t.equal( actual, out, 'returns expected value' ); + t.deepEqual( actual, expected, 'returns expected value' ); + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'the function supports specifying the evaluation context of a provided callback', function test( t ) { + var expected; + var actual; + var values; + var ctx; + var it; + + values = [ 1, 2, 3, 4 ]; + it = array2iterator( values ); + + ctx = { + 'count': 0 + }; + actual = iterator2array( it, scale, ctx ); + expected = [ 1, 4, 9, 16 ]; + + t.equal( ctx.count, 4, 'returns expected value' ); + t.deepEqual( actual, expected, 'returns expected value' ); + t.end(); + + function scale( v, i ) { + this.count += 1; // eslint-disable-line no-invalid-this + return v * (i+1); + } +}); + +tape( 'the function supports specifying the evaluation context of a provided callback (output argument)', function test( t ) { + var expected; + var values; + var actual; + var out; + var ctx; + var it; + + values = [ 1, 2, 3, 4 ]; + it = array2iterator( values ); + + ctx = { + 'count': 0 + }; + out = new Float64Array( values.length ); + actual = iterator2array( it, out, scale, ctx ); + expected = new Float64Array( [ 1, 4, 9, 16 ] ); + + t.equal( ctx.count, 4, 'returns expected value' ); + t.deepEqual( actual, expected, 'returns expected value' ); + t.end(); + + function scale( v, i ) { + this.count += 1; // eslint-disable-line no-invalid-this + return v * (i+1); + } +}); + +tape( 'if provided an output argument, the function supports infinite iterators', function test( t ) { + var out = iterator2array( randu(), new Float64Array( 10 ) ); + t.equal( out.length, 10, 'has expected length' ); + t.end(); +}); + +tape( 'if provided an output argument, the function supports infinite iterators (callback)', function test( t ) { + var out = iterator2array( randu(), new Float64Array( 10 ), scale ); + t.equal( out.length, 10, 'has expected length' ); + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); diff --git a/generic/benchmark/benchmark.fast_elements_array_length_heuristic.js b/generic/benchmark/benchmark.fast_elements_array_length_heuristic.js new file mode 100644 index 00000000..92d3b118 --- /dev/null +++ b/generic/benchmark/benchmark.fast_elements_array_length_heuristic.js @@ -0,0 +1,196 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isArray = require( '@stdlib/assert/is-array' ); +var floor = require( '@stdlib/math/base/special/floor' ); +var randu = require( '@stdlib/random/base/randu' ); +var pow = require( '@stdlib/math/base/special/pow' ); + + +// VARIABLES // + +var NAME = 'js-array-length-fast-elements-heuristic'; + +/* +* In some engines, heuristics have been used to ensure "fast elements" (i.e., contiguous memory) for generic arrays. For historical background, see +* +* - https://www.html5rocks.com/en/tutorials/speed/v8/#toc-topic-numbers +* - https://github.com/thlorenz/v8-perf/blob/ee76ddf1e414f3299bd03943ef212072dd16200f/data-types.md#fast-elements +* +* Apparently, in more recent V8 versions, the limit at which dictionary mode is triggered when preallocating arrays has increased to ~32 million. +* +* - https://github.com/v8/v8/blob/2feb99dc8ac75f20d2e5c9c1b343e923476851ea/src/objects/js-array.h#L87-L88 +*/ +var MAX_FAST_ELEMENTS_HEURISTIC = 64000|0; // eslint-disable-line id-length + + +// FUNCTIONS // + +/** +* Copies an array using a heuristic for ensuring "fast" elements. +* +* @private +* @param {Array} arr - array to copy +* @returns {Array} array copy +*/ +function copy1( arr ) { + var out; + var len; + var i; + + len = arr.length; + if ( len > MAX_FAST_ELEMENTS_HEURISTIC ) { + out = new Array( MAX_FAST_ELEMENTS_HEURISTIC ); + for ( i = 0; i < MAX_FAST_ELEMENTS_HEURISTIC; i++ ) { + out[ i ] = arr[ i ]; + } + for ( i = MAX_FAST_ELEMENTS_HEURISTIC; i < len; i++ ) { + out.push( arr[ i ] ); + } + } else { + out = new Array( len ); + for ( i = 0; i < len; i++ ) { + out[ i ] = arr[ i ]; + } + } + return out; +} + +/** +* Copies an array by preallocating output array memory. +* +* @private +* @param {Array} arr - array to copy +* @returns {Array} array copy +*/ +function copy2( arr ) { + var out; + var len; + var i; + + len = arr.length; + out = new Array( len ); + for ( i = 0; i < len; i++ ) { + out[ i ] = arr[ i ]; + } + return out; +} + +/** +* Copies an array using dynamic memory allocation. +* +* @private +* @param {Array} arr - array to copy +* @returns {Array} array copy +*/ +function copy3( arr ) { + var out; + var len; + var i; + + len = arr.length; + out = []; + for ( i = 0; i < len; i++ ) { + out.push( arr[ i ] ); + } + return out; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {Function} fcn - function to benchmark +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( fcn, len ) { + var arr; + var i; + + arr = []; + for ( i = 0; i < len; i++ ) { + arr.push( 0 ); + } + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = floor( randu()*100.0 )|0; // cast to int32 + out = fcn( arr ); + if ( out.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isArray( out ) ) { + b.fail( 'should return an array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + + f = createBenchmark( copy1, len ); + bench( NAME+'::heuristic:len='+len, f ); + + f = createBenchmark( copy2, len ); + bench( NAME+'::preallocate:len='+len, f ); + + f = createBenchmark( copy3, len ); + bench( NAME+'::dynamic:len='+len, f ); + } +} + +main(); diff --git a/incrspace/README.md b/incrspace/README.md new file mode 100644 index 00000000..3c5640b3 --- /dev/null +++ b/incrspace/README.md @@ -0,0 +1,127 @@ + + +# Incrspace + +> Generate a linearly spaced numeric array using a provided increment. + +
+ +## Usage + +```javascript +var incrspace = require( '@stdlib/array/incrspace' ); +``` + +#### incrspace( start, stop\[, increment] ) + +Generates a linearly spaced numeric `array`. If an `increment` is not provided, the default `increment` is `1`. + +```javascript +var arr = incrspace( 0, 11, 2 ); +// returns [ 0, 2, 4, 6, 8, 10 ] +``` + +
+ + + +
+ +### Notes + +- The output `array` is guaranteed to include the `start` value but does **not** include the `stop` value. Beware that values subsequent to the `start` value are subject to floating-point errors. Hence, + + ```javascript + var arr = incrspace( 0.1, 0.5, 0.2 ); + // returns [ 0.1, ~0.3 ] + ``` + + where `arr[1]` is only guaranteed to be approximately equal to `0.3`. + + If you desire more control over element precision, consider using [roundn][@stdlib/math/base/special/roundn]: + + ```javascript + var roundn = require( '@stdlib/math/base/special/roundn' ); + var arr; + var out; + var i; + + // Create an array subject to floating-point errors: + arr = incrspace( 0, 1.01, 0.02 ); + + // Round each value to the nearest hundredth: + out = []; + for ( i = 0; i < arr.length; i++ ) { + out.push( roundn( arr[ i ], -2 ) ); + } + + console.log( out.join( '\n' ) ); + ``` + +
+ + + +
+ +## Examples + + + +```javascript +var incrspace = require( '@stdlib/array/incrspace' ); +var out; + +// Default behavior: +console.log( '\nDefault:' ); +out = incrspace( 0, 10 ); +console.log( out.join( '\n' ) ); + +// Specify increment: +console.log( '\nIncrement 2:' ); +out = incrspace( 0, 10, 2 ); +console.log( out.join( '\n' ) ); + +console.log( '\nIncrement 2:' ); +out = incrspace( 0, 11, 2 ); +console.log( out.join( '\n' ) ); + +console.log( '\nIncrement 0.02:' ); +out = incrspace( 0, 1.01, 0.02 ); +console.log( out.join( '\n' ) ); + +// Create an array using a negative increment: +console.log( '\nDecremented values:' ); +out = incrspace( 10, 0, -2 ); +console.log( out.join( '\n' ) ); +``` + +
+ + + + + + diff --git a/incrspace/benchmark/benchmark.js b/incrspace/benchmark/benchmark.js new file mode 100644 index 00000000..031adc21 --- /dev/null +++ b/incrspace/benchmark/benchmark.js @@ -0,0 +1,79 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var round = require( '@stdlib/math/base/special/round' ); +var randu = require( '@stdlib/random/base/randu' ); +var isArray = require( '@stdlib/assert/is-array' ); +var pkg = require( './../package.json' ).name; +var incrspace = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var start; + var stop; + var i; + var v; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + start = round( randu()*100.0 ); + stop = start + 100; + v = incrspace( start, stop ); + if ( typeof v !== 'object' ) { + b.fail( 'should return an array' ); + } + } + b.toc(); + if ( !isArray( v ) ) { + b.fail( 'should return an array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':incr=10', function benchmark( b ) { + var start; + var incr; + var stop; + var i; + var v; + + incr = 10; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + start = round( randu()*100.0 ); + stop = start + (100*incr); + v = incrspace( start, stop, incr ); + if ( typeof v !== 'object' ) { + b.fail( 'should return an array' ); + } + } + b.toc(); + if ( !isArray( v ) ) { + b.fail( 'should return an array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/incrspace/benchmark/benchmark.length.js b/incrspace/benchmark/benchmark.length.js new file mode 100644 index 00000000..6fa425e9 --- /dev/null +++ b/incrspace/benchmark/benchmark.length.js @@ -0,0 +1,97 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var round = require( '@stdlib/math/base/special/round' ); +var randu = require( '@stdlib/random/base/randu' ); +var isArray = require( '@stdlib/assert/is-array' ); +var pkg = require( './../package.json' ).name; +var incrspace = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var start; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + start = round( randu() * 10.0 ); + v = incrspace( start, start + len ); + if ( typeof v !== 'object' ) { + b.fail( 'should return an array' ); + } + } + b.toc(); + if ( !isArray( v ) ) { + b.fail( 'should return an array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':len='+len, f ); + } +} + +main(); diff --git a/incrspace/docs/repl.txt b/incrspace/docs/repl.txt new file mode 100644 index 00000000..7655937d --- /dev/null +++ b/incrspace/docs/repl.txt @@ -0,0 +1,33 @@ + +{{alias}}( start, stop[, increment] ) + Generates a linearly spaced numeric array using a provided increment. + + If an `increment` is not provided, the default `increment` is `1`. + + The output array is guaranteed to include the `start` value but does not + include the `stop` value. + + Parameters + ---------- + start: number + First array value. + + stop: number + Array element bound. + + increment: number (optional) + Increment. Default: `1`. + + Returns + ------- + arr: Array + Linearly spaced numeric array. + + Examples + -------- + > var arr = {{alias}}( 0, 11, 2 ) + [ 0, 2, 4, 6, 8, 10 ] + + See Also + -------- + diff --git a/incrspace/docs/types/index.d.ts b/incrspace/docs/types/index.d.ts new file mode 100644 index 00000000..876c0bb9 --- /dev/null +++ b/incrspace/docs/types/index.d.ts @@ -0,0 +1,39 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/** +* Generates a linearly spaced numeric array using a provided increment. +* +* @param x1 - first array value +* @param x2 - array element bound +* @param increment - increment (default: 1) +* @throws length of created array must be less than `4294967295` (`2**32 - 1`) +* @returns linearly spaced numeric array +* +* @example +* var arr = incrspace( 0, 11, 2 ); +* // returns [ 0, 2, 4, 6, 8, 10 ] +*/ +declare function incrspace( x1: number, x2: number, increment?: number ): Array; // tslint-disable-line max-line-length + + +// EXPORTS // + +export = incrspace; diff --git a/incrspace/docs/types/test.ts b/incrspace/docs/types/test.ts new file mode 100644 index 00000000..68d956aa --- /dev/null +++ b/incrspace/docs/types/test.ts @@ -0,0 +1,60 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import incrspace = require( './index' ); + + +// TESTS // + +// The function returns an array of numbers... +{ + incrspace( 0, 11, 2 ); // $ExpectType number[] + incrspace( 0, 10 ); // $ExpectType number[] +} + +// The function does not compile if provided values other than two numbers for the first two parameters... +{ + incrspace( true, 10 ); // $ExpectError + incrspace( false, 10 ); // $ExpectError + incrspace( '5', 10 ); // $ExpectError + incrspace( [], 10 ); // $ExpectError + incrspace( {}, 20 ); // $ExpectError + incrspace( ( x: number ): number => x, 20 ); // $ExpectError + + incrspace( 9, true ); // $ExpectError + incrspace( 9, false ); // $ExpectError + incrspace( 5, '5' ); // $ExpectError + incrspace( 8, [] ); // $ExpectError + incrspace( 9, {} ); // $ExpectError + incrspace( 8, ( x: number ): number => x ); // $ExpectError +} + +// The function does not compile if provided a value other than a number for the third parameter... +{ + incrspace( 3, 20, true ); // $ExpectError + incrspace( 4, 20, false ); // $ExpectError + incrspace( 2, 20, '5' ); // $ExpectError + incrspace( 2, 20, [] ); // $ExpectError + incrspace( 9, 20, ( x: number ): number => x ); // $ExpectError +} + +// The function does not compile if provided insufficient arguments... +{ + incrspace(); // $ExpectError + incrspace( 3 ); // $ExpectError +} diff --git a/incrspace/examples/index.js b/incrspace/examples/index.js new file mode 100644 index 00000000..2bf1492a --- /dev/null +++ b/incrspace/examples/index.js @@ -0,0 +1,45 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var incrspace = require( './../lib' ); +var out; + +// Default behavior: +console.log( '\nDefault:' ); +out = incrspace( 0, 10 ); +console.log( out.join( '\n' ) ); + +// Specify increment: +console.log( '\nIncrement 2:' ); +out = incrspace( 0, 10, 2 ); +console.log( out.join( '\n' ) ); + +console.log( '\nIncrement 2:' ); +out = incrspace( 0, 11, 2 ); +console.log( out.join( '\n' ) ); + +console.log( '\nIncrement 0.02:' ); +out = incrspace( 0, 1.01, 0.02 ); +console.log( out.join( '\n' ) ); + +// Create an array using a negative increment: +console.log( '\nDecremented values:' ); +out = incrspace( 10, 0, -2 ); +console.log( out.join( '\n' ) ); diff --git a/incrspace/lib/incrspace.js b/incrspace/lib/incrspace.js new file mode 100644 index 00000000..871f0e8a --- /dev/null +++ b/incrspace/lib/incrspace.js @@ -0,0 +1,85 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var ceil = require( '@stdlib/math/base/special/ceil' ); +var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive; +var isnan = require( '@stdlib/math/base/assert/is-nan' ); +var MAX_LENGTH = require( '@stdlib/constants/uint32/max' ); + + +// MAIN // + +/** +* Generates a linearly spaced numeric array using a provided increment. +* +* @param {number} x1 - first array value +* @param {number} x2 - array element bound +* @param {number} [increment=1] - increment +* @throws {TypeError} first argument must be numeric +* @throws {TypeError} second argument must be numeric +* @throws {TypeError} third argument must be numeric +* @throws {RangeError} length of created array must be less than `4294967295` (`2**32 - 1`) +* @returns {Array} linearly spaced numeric array +* +* @example +* var arr = incrspace( 0, 11, 2 ); +* // returns [ 0, 2, 4, 6, 8, 10 ] +*/ +function incrspace( x1, x2, increment ) { + var arr; + var len; + var inc; + var i; + if ( !isNumber( x1 ) || isnan( x1 ) ) { + throw new TypeError( 'invalid argument. Start must be numeric. Value: `' + x1 + '`.' ); + } + if ( !isNumber( x2 ) || isnan( x2 ) ) { + throw new TypeError( 'invalid argument. Stop must be numeric. Value: `' + x2 + '`.' ); + } + if ( arguments.length < 3 ) { + inc = 1; + } else { + inc = increment; + if ( !isNumber( inc ) || isnan( inc ) ) { + throw new TypeError( 'invalid argument. Increment must be numeric. Value: `' + inc + '`.' ); + } + } + len = ceil( ( x2-x1 ) / inc ); + + if ( len > MAX_LENGTH ) { + throw new RangeError( 'invalid arguments. Generated array exceeds maximum array length.' ); + } + if ( len <= 1 ) { + return [ x1 ]; + } + arr = []; + arr.push( x1 ); + for ( i = 1; i < len; i++ ) { + arr.push( x1 + (inc*i) ); + } + return arr; +} + + +// EXPORTS // + +module.exports = incrspace; diff --git a/incrspace/lib/index.js b/incrspace/lib/index.js new file mode 100644 index 00000000..559188dc --- /dev/null +++ b/incrspace/lib/index.js @@ -0,0 +1,40 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Generate a linearly spaced numeric array using a provided increment. +* +* @module @stdlib/array/incrspace +* +* @example +* var incrspace = require( '@stdlib/array/incrspace' ); +* +* var arr = incrspace( 0, 11, 2 ); +* // returns [ 0, 2, 4, 6, 8, 10 ] +*/ + +// MODULES // + +var incrspace = require( './incrspace.js' ); + + +// EXPORTS // + +module.exports = incrspace; diff --git a/incrspace/package.json b/incrspace/package.json new file mode 100644 index 00000000..cc9f7ff7 --- /dev/null +++ b/incrspace/package.json @@ -0,0 +1,65 @@ +{ + "name": "@stdlib/array/incrspace", + "version": "0.0.0", + "description": "Generate a linearly spaced numeric array using a provided increment.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdmath", + "utilities", + "utils", + "mathematics", + "math", + "generic", + "array", + "matlab", + "linear", + "linspace", + "sequence", + "increment" + ] +} diff --git a/incrspace/test/test.js b/incrspace/test/test.js new file mode 100644 index 00000000..23dd8090 --- /dev/null +++ b/incrspace/test/test.js @@ -0,0 +1,178 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var incrspace = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.equal( typeof incrspace, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error if the `start` value is not a number primitive', function test( t ) { + var values; + var i; + + values = [ + '5', + null, + true, + undefined, + NaN, + [], + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + incrspace( value, 10 ); + }; + } +}); + +tape( 'the function throws an error if the `stop` value is not a number primitive', function test( t ) { + var values; + var i; + + values = [ + '5', + null, + true, + undefined, + NaN, + [], + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + incrspace( 0, value ); + }; + } +}); + +tape( 'the function throws an error if the `increment` value is not a number primitive', function test( t ) { + var values; + var i; + + values = [ + '5', + null, + true, + undefined, + NaN, + [], + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + incrspace( 0, 10, value ); + }; + } +}); + +tape( 'the function returns a linearly spaced array', function test( t ) { + var expected; + var actual; + var start; + var stop; + + start = 0; + stop = 10; + + // Default behavior: + actual = incrspace( start, stop ); + expected = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]; + t.deepEqual( actual, expected ); + + // Specify the increment: + actual = incrspace( start, stop, 2 ); + expected = [ 0, 2, 4, 6, 8 ]; + t.deepEqual( actual, expected ); + + actual = incrspace( start, 11, 2 ); + expected = [ 0, 2, 4, 6, 8, 10 ]; + t.deepEqual( actual, expected ); + + // Decrement: + actual = incrspace( stop, start, -2 ); + expected = [ 10, 8, 6, 4, 2 ]; + t.deepEqual( actual, expected ); + + // Large array: + actual = incrspace( start, 1e6, 1 ); + t.equal( actual.length, 1e6 ); + + t.end(); +}); + +tape( 'the function throws an error if the maximum array length is exceeded', function test( t ) { + var values; + var i; + + values = [ + 0.000000000000001, + 0.00000000000000000000001, + 0.000000000000000000000000001, + 0 + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), RangeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + incrspace( 0, 10, value ); + }; + } +}); + +tape( 'the function returns a single element array for incompatible increments', function test( t ) { + t.deepEqual( incrspace(0, 10, -1), [ 0 ] ); + t.deepEqual( incrspace(0, 10, 11), [ 0 ] ); + t.end(); +}); diff --git a/int16/README.md b/int16/README.md new file mode 100644 index 00000000..a321d743 --- /dev/null +++ b/int16/README.md @@ -0,0 +1,1431 @@ + + +# Int16Array + +> [Typed array][mdn-typed-array] constructor which returns a [typed array][mdn-typed-array] representing an array of twos-complement 16-bit signed integers in the platform byte order. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var Int16Array = require( '@stdlib/array/int16' ); +``` + +#### Int16Array() + +A [typed array][mdn-typed-array] constructor which returns a [typed array][mdn-typed-array] representing an array of twos-complement 16-bit signed integers in the platform byte order. + + + +```javascript +var arr = new Int16Array(); +// returns +``` + +#### Int16Array( length ) + +Returns a [typed array][mdn-typed-array] having a specified length. + + + +```javascript +var arr = new Int16Array( 5 ); +// returns [ 0, 0, 0, 0, 0 ] +``` + +#### Int16Array( typedarray ) + +Creates a [typed array][mdn-typed-array] from another [typed array][mdn-typed-array]. + + + +```javascript +var Float32Array = require( '@stdlib/array/float32' ); + +var arr1 = new Float32Array( [ 5.0, 5.0, 5.0 ] ); +var arr2 = new Int16Array( arr1 ); +// returns [ 5, 5, 5 ] +``` + +#### Int16Array( obj ) + +Creates a [typed array][mdn-typed-array] from an array-like `object` or iterable. + + + +```javascript +var arr = new Int16Array( [ 5.0, 5.0, 5.0 ] ); +// returns [ 5, 5, 5 ] +``` + +#### Int16Array( buffer\[, byteOffset\[, length]] ) + +Returns a [typed array][mdn-typed-array] view of an [`ArrayBuffer`][@stdlib/array/buffer]. + + + +```javascript +var ArrayBuffer = require( '@stdlib/array/buffer' ); + +var buf = new ArrayBuffer( 8 ); +var arr = new Int16Array( buf, 0, 4 ); +// returns [ 0, 0, 0, 0 ] +``` + +* * * + +### Properties + + + +#### Int16Array.BYTES_PER_ELEMENT + +Number of bytes per view element. + + + +```javascript +var nbytes = Int16Array.BYTES_PER_ELEMENT; +// returns 2 +``` + + + +#### Int16Array.name + +[Typed array][mdn-typed-array] constructor name. + + + +```javascript +var str = Int16Array.name; +// returns 'Int16Array' +``` + + + +#### Int16Array.prototype.buffer + +**Read-only** property which returns the [`ArrayBuffer`][@stdlib/array/buffer] referenced by the [typed array][mdn-typed-array]. + + + +```javascript +var arr = new Int16Array( 5 ); +var buf = arr.buffer; +// returns +``` + + + +#### Int16Array.prototype.byteLength + +**Read-only** property which returns the length (in bytes) of the [typed array][mdn-typed-array]. + + + +```javascript +var arr = new Int16Array( 5 ); +var byteLength = arr.byteLength; +// returns 10 +``` + + + +#### Int16Array.prototype.byteOffset + +**Read-only** property which returns the offset (in bytes) of the [typed array][mdn-typed-array] from the start of its [`ArrayBuffer`][@stdlib/array/buffer]. + + + +```javascript +var arr = new Int16Array( 5 ); +var byteOffset = arr.byteOffset; +// returns 0 +``` + + + +#### Int16Array.prototype.BYTES_PER_ELEMENT + +Number of bytes per view element. + + + +```javascript +var arr = new Int16Array( 5 ); +var nbytes = arr.BYTES_PER_ELEMENT; +// returns 2 +``` + + + +#### Int16Array.prototype.length + +**Read-only** property which returns the number of view elements. + + + +```javascript +var arr = new Int16Array( 5 ); +var len = arr.length; +// returns 5 +``` + +* * * + +### Methods + + + +#### Int16Array.from( src\[, map\[, thisArg]] ) + +Creates a new typed array from an array-like `object` or an iterable. + +```javascript +var arr = Int16Array.from( [ 1, 2 ] ); +// returns [ 1, 2 ] +``` + +To invoke a function for each `src` value, provide a callback function. + +```javascript +function mapFcn( v ) { + return v * 2; +} + +var arr = Int16Array.from( [ 1, 2 ], mapFcn ); +// returns [ 2, 4 ] +``` + +A callback function is provided two arguments: + +- `value`: source value +- `index`: source index + +To set the callback execution context, provide a `thisArg`. + +```javascript +function mapFcn( v ) { + this.count += 1; + return v * 2; +} + +var ctx = { + 'count': 0 +}; + +var arr = Int16Array.from( [ 1, 2 ], mapFcn, ctx ); +// returns [ 2, 4 ] + +var n = ctx.count; +// returns 2 +``` + + + +#### Int16Array.of( element0\[, element1\[, ...elementN]] ) + +Creates a new typed array from a variable number of arguments. + +```javascript +var arr = Int16Array.of( 1, 2 ); +// returns [ 1, 2 ] +``` + + + +#### Int16Array.prototype.copyWithin( target, start\[, end] ) + +Copies a sequence of elements within an array starting at `start` and ending at `end` (non-inclusive) to the position starting at `target`. + + + +```javascript +var arr = new Int16Array( [ 1, 2, 3, 4, 5 ] ); + +// Copy the last two elements to the first two elements: +arr.copyWithin( 0, 3 ); + +var v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 5 +``` + +By default, `end` equals the number of array elements (i.e., one more than the last array index). To limit the sequence length, provide an `end` argument. + + + +```javascript +var arr = new Int16Array( [ 1, 2, 3, 4, 5 ] ); + +// Copy the first two elements to the last two elements: +arr.copyWithin( 3, 0, 2 ); + +var v = arr[ 3 ]; +// returns 1 + +v = arr[ 4 ]; +// returns 2 +``` + +When a `target`, `start`, and/or `end` index is negative, the respective index is determined relative to the last array element. The following example achieves the same behavior as the previous example: + + + +```javascript +var arr = new Int16Array( [ 1, 2, 3, 4, 5 ] ); + +// Copy the first two elements to the last two elements: +arr.copyWithin( -2, -5, -3 ); + +var v = arr[ 3 ]; +// returns 1 + +v = arr[ 4 ]; +// returns 2 +``` + + + +#### Int16Array.prototype.entries() + +Returns an iterator for iterating over array key-value pairs. + + + +```javascript +var arr = new Int16Array( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.entries(); + +// Iterate over key-value pairs... +var v = it.next().value; +// returns [ 0, 1 ] + +v = it.next().value; +// returns [ 1, 2 ] + +var bool = it.next().done; +// returns true +``` + + + +#### Int16Array.prototype.every( predicate\[, thisArg] ) + +Tests whether all array elements pass a test implemented by a `predicate` function. + + + +```javascript +function predicate( v ) { + return ( v <= 1 ); +} + +var arr = new Int16Array( [ 1, 2 ] ); + +var bool = arr.every( predicate ); +// returns false +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 1 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Int16Array( [ 1, 2 ] ); + +var bool = arr.every( predicate, ctx ); +// returns true + +var n = ctx.count; +// returns 2 +``` + + + +#### Int16Array.prototype.fill( value\[, start\[, end]] ) + +Fills an array from a `start` index to an `end` index (non-inclusive) with a provided `value`. + + + +```javascript +var arr = new Int16Array( 2 ); + +// Set all array elements to the same value: +arr.fill( 2 ); + +var v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 2 + +// Set all array elements starting from the first index to the same value: +arr.fill( 3, 1 ); + +v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 3 + +// Set all array elements, except the last element, to the same value: +arr.fill( 4, 0, arr.length-1 ); + +v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 3 +``` + +When a `start` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr = new Int16Array( 2 ); + +// Set all array elements, except the last element, to the same value: +arr.fill( 2, -arr.length, -1 ); + +var v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 0 +``` + + + +#### Int16Array.prototype.filter( predicate\[, thisArg] ) + +Creates a new array (of the same data type as the host array) which includes those elements for which a `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v >= 2 ); +} + +var arr1 = new Int16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate ); +// returns [ 2, 3 ] +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns an empty array. + + + +```javascript +function predicate( v ) { + return ( v >= 10 ); +} + +var arr1 = new Int16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate ); +// returns [] +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr1 = new Int16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Int16Array.prototype.find( predicate\[, thisArg] ) + +Returns the first array element for which a provided `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v > 2 ); +} + +var arr = new Int16Array( [ 1, 2, 3 ] ); + +var v = arr.find( predicate ); +// returns 3 +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns `undefined`. + + + +```javascript +function predicate( v ) { + return ( v < 1 ); +} + +var arr = new Int16Array( [ 1, 2, 3 ] ); + +var v = arr.find( predicate ); +// returns undefined +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v > 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Int16Array( [ 1, 2, 3 ] ); + +var v = arr.find( predicate, ctx ); +// returns 3 + +var n = ctx.count; +// returns 3 +``` + + + +#### Int16Array.prototype.findIndex( predicate\[, thisArg] ) + +Returns the index of the first array element for which a provided `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v >= 3 ); +} + +var arr = new Int16Array( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate ); +// returns 2 +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns `-1`. + + + +```javascript +function predicate( v ) { + return ( v < 1 ); +} + +var arr = new Int16Array( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate ); +// returns -1 +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 3 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Int16Array( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate, ctx ); +// returns 2 + +var n = ctx.count; +// returns 3 +``` + + + +#### Int16Array.prototype.forEach( fcn\[, thisArg] ) + +Invokes a callback for each array element. + + + +```javascript +var arr = new Int16Array( [ 1, 2, 3 ] ); + +var str = ''; + +function fcn( v, i ) { + str += i + ':' + v; + if ( i < arr.length-1 ) { + str += ' '; + } +} + +arr.forEach( fcn ); + +console.log( str ); +// => '0:1 1:2 2:3' +``` + +The callback is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function fcn() { + this.count += 1; +} + +var ctx = { + 'count': 0 +}; + +var arr = new Int16Array( [ 1, 2, 3 ] ); + +arr.forEach( fcn, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Int16Array.prototype.includes( searchElement\[, fromIndex] ) + +Returns a `boolean` indicating whether an array includes a search element. + + + +```javascript +var arr = new Int16Array( [ 1, 2, 3 ] ); + +var bool = arr.includes( 3 ); +// returns true + +bool = arr.includes( 0 ); +// returns false +``` + +By default, the method searches the entire array (`fromIndex = 0`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Int16Array( [ 1, 2, 3 ] ); + +var bool = arr.includes( 1, 1 ); +// returns false +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Int16Array( [ 1, 2, 3 ] ); + +bool = arr.includes( 1, -2 ); +// returns false +``` + + + +#### Int16Array.prototype.indexOf( searchElement\[, fromIndex] ) + +Returns the index of the first array element strictly equal to a search element. + + + +```javascript +var arr = new Int16Array( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 3 ); +// returns 2 + +idx = arr.indexOf( 0 ); +// returns -1 +``` + +By default, the method searches the entire array (`fromIndex = 0`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Int16Array( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 1, 1 ); +// returns -1 +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Int16Array( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 1, -2 ); +// returns -1 +``` + + + +#### Int16Array.prototype.join( \[separator] ) + +Serializes an array by joining all array elements as a string. + + + +```javascript +var arr = new Int16Array( [ 1, 2, 3 ] ); + +var str = arr.join(); +// returns '1,2,3' +``` + +By default, the method delineates array elements using a comma `,`. To specify a custom separator, provide a `separator` string. + + + +```javascript +var arr = new Int16Array( [ 1, 2, 3 ] ); + +var str = arr.join( '|' ); +// returns '1|2|3' +``` + + + +#### Int16Array.prototype.keys() + +Returns an iterator for iterating over array keys. + + + +```javascript +var arr = new Int16Array( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.keys(); + +// Iterate over keys... +var v = it.next().value; +// returns 0 + +v = it.next().value; +// returns 1 + +var bool = it.next().done; +// returns true +``` + + + +#### Int16Array.prototype.lastIndexOf( searchElement\[, fromIndex] ) + +Returns the index of the last array element strictly equal to a search element, iterating from right to left. + + + +```javascript +var arr = new Int16Array( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0 ); +// returns 3 + +idx = arr.lastIndexOf( 3 ); +// returns -1 +``` + +By default, the method searches the entire array (`fromIndex = -1`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Int16Array( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0, 2 ); +// returns 1 +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Int16Array( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0, -3 ); +// returns 1 +``` + + + +#### Int16Array.prototype.map( fcn\[, thisArg] ) + +Maps each array element to an element in a new array having the same data type as the host array. + + + +```javascript +function fcn( v ) { + return v * 2; +} + +var arr1 = new Int16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.map( fcn ); +// returns [ 2, 4, 6 ] +``` + +A callback is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function fcn( v ) { + this.count += 1; + return v * 2; +} + +var ctx = { + 'count': 0 +}; + +var arr1 = new Int16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.map( fcn, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Int16Array.prototype.reduce( fcn\[, initialValue] ) + +Applies a function against an accumulator and each element in an array and returns the accumulated result. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Int16Array( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn ); +// returns 12 +``` + +If not provided an initial value, the method invokes a provided function with the first array element as the first argument and the second array element as the second argument. + +If provided an initial value, the method invokes a provided function with the initial value as the first argument and the first array element as the second argument. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Int16Array( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn, 0 ); +// returns 14 +``` + +A callback is provided four arguments: + +- `acc`: accumulated result +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + + + +#### Int16Array.prototype.reduceRight( fcn\[, initialValue] ) + +Applies a function against an accumulator and each element in an array and returns the accumulated result, iterating from right to left. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Int16Array( [ 2, 1, 3 ] ); + +var v = arr.reduceRight( fcn ); +// returns 8 +``` + +If not provided an initial value, the method invokes a provided function with the last array element as the first argument and the second-to-last array element as the second argument. + +If provided an initial value, the method invokes a provided function with the initial value as the first argument and the last array element as the second argument. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Int16Array( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn, 0 ); +// returns 14 +``` + +A callback is provided four arguments: + +- `acc`: accumulated result +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + + + +#### Int16Array.prototype.reverse() + +Reverses an array **in-place** (thus mutating the array on which the method is invoked). + + + +```javascript +var arr = new Int16Array( [ 2, 0, 3 ] ); + +// Reverse the array: +arr.reverse(); + +var v = arr[ 0 ]; +// returns 3 + +v = arr[ 1 ]; +// returns 0 + +v = arr[ 2 ]; +// returns 2 +``` + + + +#### Int16Array.prototype.set( arr\[, offset] ) + +Sets array elements. + + + +```javascript +var arr = new Int16Array( [ 1, 2, 3 ] ); +// returns [ 1, 2, 3 ] + +// Set the first two array elements: +arr.set( [ 4, 5 ] ); + +var v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 5 +``` + +By default, the method starts writing values at the first array index. To specify an alternative index, provide an index `offset`. + + + +```javascript +var arr = new Int16Array( [ 1, 2, 3 ] ); +// returns [ 1, 2, 3 ] + +// Set the last two array elements: +arr.set( [ 4, 5 ], 1 ); + +var v = arr[ 1 ]; +// returns 4 + +v = arr[ 2 ]; +// returns 5 +``` + + + +#### Int16Array.prototype.slice( \[begin\[, end]] ) + +Copies array elements to a new array with the same underlying data type as the host array. + + + +```javascript +var arr1 = new Int16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice(); + +var bool = ( arr1 === arr2 ); +// returns false + +bool = ( arr1.buffer === arr2.buffer ); +// returns false + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 + +v = arr2[ 2 ]; +// returns 3 +``` + +By default, the method copies elements beginning with the first array element. To specify an alternative array index at which to begin copying, provide a `begin` index (inclusive). + + + +```javascript +var arr1 = new Int16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( 1 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 2 + +v = arr2[ 1 ]; +// returns 3 +``` + +By default, the method copies all array elements after `begin`. To specify an alternative array index at which to end copying, provide an `end` index (exclusive). + + + +```javascript +var arr1 = new Int16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( 0, 2 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 +``` + +When a `begin` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr1 = new Int16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( -arr1.length, -1 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 +``` + + + +#### Int16Array.prototype.some( predicate\[, thisArg] ) + +Tests whether at least one array element passes a test implemented by a `predicate` function. + + + +```javascript +function predicate( v ) { + return ( v >= 2 ); +} + +var arr = new Int16Array( [ 1, 2 ] ); + +var bool = arr.some( predicate ); +// returns true +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Int16Array( [ 1, 1 ] ); + +var bool = arr.some( predicate, ctx ); +// returns false + +var n = ctx.count; +// returns 2 +``` + + + +#### Int16Array.prototype.sort( \[compareFunction] ) + +Sorts an array **in-place** (thus mutating the array on which the method is invoked). + + + +```javascript +var arr = new Int16Array( [ 2, 3, 0 ] ); + +// Sort the array (in ascending order): +arr.sort(); + +var v = arr[ 0 ]; +// returns 0 + +v = arr[ 1 ]; +// returns 2 + +v = arr[ 2 ]; +// returns 3 +``` + +By default, the method sorts array elements in ascending order. To impose a custom order, provide a `compareFunction`. + + + +```javascript +function descending( a, b ) { + return b - a; +} + +var arr = new Int16Array( [ 2, 3, 0 ] ); + +// Sort the array (in descending order): +arr.sort( descending ); + +var v = arr[ 0 ]; +// returns 3 + +v = arr[ 1 ]; +// returns 2 + +v = arr[ 2 ]; +// returns 0 +``` + +The comparison function is provided two array elements, `a` and `b`, per invocation, and its return value determines the sort order as follows: + +- If the comparison function returns a value **less** than zero, then the method sorts `a` to an index lower than `b` (i.e., `a` should come **before** `b`). +- If the comparison function returns a value **greater** than zero, then the method sorts `a` to an index higher than `b` (i.e., `b` should come **before** `a`). +- If the comparison function returns **zero**, then the relative order of `a` and `b` _should_ remain unchanged. + + + +#### Int16Array.prototype.subarray( \[begin\[, end]] ) + +Creates a new typed array view over the same underlying [`ArrayBuffer`][@stdlib/array/buffer] and with the same underlying data type as the host array. + + + +```javascript +var arr1 = new Int16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray(); +// returns [ 1, 2, 3 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +By default, the method creates a typed array view beginning with the first array element. To specify an alternative array index at which to begin, provide a `begin` index (inclusive). + + + +```javascript +var arr1 = new Int16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 1 ); +// returns [ 2, 3 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +By default, the method creates a typed array view which includes all array elements after `begin`. To limit the number of array elements after `begin`, provide an `end` index (exclusive). + + + +```javascript +var arr1 = new Int16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 0, 2 ); +// returns [ 1, 2 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +When a `begin` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr1 = new Int16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( -arr1.length, -1 ); +// returns [ 1, 2 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +If the method is unable to resolve indices to a non-empty array subsequence, the method returns an empty typed array. + + + +```javascript +var arr1 = new Int16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 10, -1 ); +// returns [] +``` + + + +#### Int16Array.prototype.toLocaleString( \[locales\[, options]] ) + +Serializes an array as a locale-specific `string`. + + + +```javascript +var arr = new Int16Array( [ 1, 2, 3 ] ); + +var str = arr.toLocaleString(); +// returns '1,2,3' +``` + + + +#### Int16Array.prototype.toString() + +Serializes an array as a `string`. + + + +```javascript +var arr = new Int16Array( [ 1, 2, 3 ] ); + +var str = arr.toString(); +// returns '1,2,3' +``` + + + +#### Int16Array.prototype.values() + +Returns an iterator for iterating over array elements. + + + +```javascript +var arr = new Int16Array( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.values(); + +// Iterate over array elements... +var v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 2 + +var bool = it.next().done; +// returns true +``` + +
+ + + +* * * + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var randu = require( '@stdlib/random/base/randu' ); +var round = require( '@stdlib/math/base/special/round' ); +var ctor = require( '@stdlib/array/int16' ); + +var arr; +var i; + +arr = new ctor( 10 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = round( randu()*100.0 ); +} +console.log( arr ); +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/int16/benchmark/benchmark.copy_within.js b/int16/benchmark/benchmark.copy_within.js new file mode 100644 index 00000000..b6f86773 --- /dev/null +++ b/int16/benchmark/benchmark.copy_within.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':copyWithin', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 255; + arr[ 0 ] = v; + arr = arr.copyWithin( 1, 0 ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/benchmark/benchmark.copy_within.length.js b/int16/benchmark/benchmark.copy_within.length.js new file mode 100644 index 00000000..b0f5e42d --- /dev/null +++ b/int16/benchmark/benchmark.copy_within.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 255; + arr[ 0 ] = v; + arr = arr.copyWithin( 1, 0 ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':copyWithin:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.data.js b/int16/benchmark/benchmark.data.js new file mode 100644 index 00000000..4ced1398 --- /dev/null +++ b/int16/benchmark/benchmark.data.js @@ -0,0 +1,75 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::get,index', function benchmark( b ) { + var arr; + var N; + var v; + var i; + + arr = new Int16Array( 2 ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr[ i%N ]; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::set,index', function benchmark( b ) { + var arr; + var N; + var i; + + arr = new Int16Array( 2 ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ i%N ] = i; + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] || arr[ 1 ] !== arr[ 1 ] ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/benchmark/benchmark.entries.js b/int16/benchmark/benchmark.entries.js new file mode 100644 index 00000000..b0427cb1 --- /dev/null +++ b/int16/benchmark/benchmark.entries.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':entries', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Int16Array( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.entries(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/benchmark/benchmark.every.js b/int16/benchmark/benchmark.every.js new file mode 100644 index 00000000..67572362 --- /dev/null +++ b/int16/benchmark/benchmark.every.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':every', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); + +bench( pkg+'::this_context:every', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate, {} ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); diff --git a/int16/benchmark/benchmark.every.length.js b/int16/benchmark/benchmark.every.length.js new file mode 100644 index 00000000..a94be9da --- /dev/null +++ b/int16/benchmark/benchmark.every.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value >= 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':every:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.fill.js b/int16/benchmark/benchmark.fill.js new file mode 100644 index 00000000..145d1ef8 --- /dev/null +++ b/int16/benchmark/benchmark.fill.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':fill', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr = arr.fill( v ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/benchmark/benchmark.fill.length.js b/int16/benchmark/benchmark.fill.length.js new file mode 100644 index 00000000..b18ef85a --- /dev/null +++ b/int16/benchmark/benchmark.fill.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr = arr.fill( v ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':fill:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.filter.js b/int16/benchmark/benchmark.filter.js new file mode 100644 index 00000000..14a278ee --- /dev/null +++ b/int16/benchmark/benchmark.filter.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt16Array = require( '@stdlib/assert/is-int16array' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':filter', function benchmark( b ) { + var arr; + var out; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt16Array( out ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); + +bench( pkg+'::this_context:filter', function benchmark( b ) { + var arr; + var out; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate, {} ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt16Array( out ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); diff --git a/int16/benchmark/benchmark.filter.length.js b/int16/benchmark/benchmark.filter.length.js new file mode 100644 index 00000000..ac3e8441 --- /dev/null +++ b/int16/benchmark/benchmark.filter.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isInt16Array = require( '@stdlib/assert/is-int16array' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value >= 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt16Array( out ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':filter:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.find.js b/int16/benchmark/benchmark.find.js new file mode 100644 index 00000000..293ae591 --- /dev/null +++ b/int16/benchmark/benchmark.find.js @@ -0,0 +1,82 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':find', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int16Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:find', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int16Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate, {} ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/int16/benchmark/benchmark.find.length.js b/int16/benchmark/benchmark.find.length.js new file mode 100644 index 00000000..da60e8cc --- /dev/null +++ b/int16/benchmark/benchmark.find.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - tuple length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int16Array( len ); + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':find:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.find_index.js b/int16/benchmark/benchmark.find_index.js new file mode 100644 index 00000000..475627ee --- /dev/null +++ b/int16/benchmark/benchmark.find_index.js @@ -0,0 +1,82 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':findIndex', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int16Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:findIndex', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int16Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate, {} ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/int16/benchmark/benchmark.find_index.length.js b/int16/benchmark/benchmark.find_index.length.js new file mode 100644 index 00000000..6a9ed79c --- /dev/null +++ b/int16/benchmark/benchmark.find_index.length.js @@ -0,0 +1,104 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':findIndex:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.for_each.js b/int16/benchmark/benchmark.for_each.js new file mode 100644 index 00000000..fe74266a --- /dev/null +++ b/int16/benchmark/benchmark.for_each.js @@ -0,0 +1,88 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':forEach', function benchmark( b ) { + var count; + var arr; + var N; + var i; + + arr = new Int16Array( 2 ); + N = arr.length; + + count = 0; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn ); + if ( count !== N*(i+1) ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( count !== N*i ) { + b.fail( 'unexpected result' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn() { + count += 1; + } +}); + +bench( pkg+'::this_context:forEach', function benchmark( b ) { + var count; + var arr; + var N; + var i; + + arr = new Int16Array( 2 ); + N = arr.length; + + count = 0; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn, {} ); + if ( count !== N*(i+1) ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( count !== N*i ) { + b.fail( 'unexpected result' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn() { + count += 1; + } +}); diff --git a/int16/benchmark/benchmark.for_each.length.js b/int16/benchmark/benchmark.for_each.length.js new file mode 100644 index 00000000..b1c24068 --- /dev/null +++ b/int16/benchmark/benchmark.for_each.length.js @@ -0,0 +1,106 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var count; + var arr; + + arr = new Int16Array( len ); + count = 0; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn ); + if ( count !== count ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( count !== count ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } + + /** + * Callback invoked for each tuple element. + * + * @private + */ + function fcn() { + count += 1; + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':forEach:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.from.js b/int16/benchmark/benchmark.from.js new file mode 100644 index 00000000..74ad4ec0 --- /dev/null +++ b/int16/benchmark/benchmark.from.js @@ -0,0 +1,237 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var ITERATOR_SYMBOL = require( '@stdlib/symbol/iterator' ); +var isInt16Array = require( '@stdlib/assert/is-int16array' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// VARIABLES // + +var opts = { + 'skip': ( ITERATOR_SYMBOL === null ) +}; + + +// MAIN // + +bench( pkg+'::typed_array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Int16Array( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int16Array.from( buf ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt16Array( arr ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array,clbk:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Int16Array( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int16Array.from( buf, clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt16Array( arr ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1; + } +}); + +bench( pkg+'::array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1, 2 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int16Array.from( buf ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt16Array( arr ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::array,clbk:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1, 2 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int16Array.from( buf, clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt16Array( arr ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1; + } +}); + +bench( pkg+'::iterable:from', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int16Array.from( createIterable() ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt16Array( arr ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out; + var i; + + out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + + i = 0; + + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + i += 1; + if ( i <= 2 ) { + return { + 'value': 0, + 'done': false + }; + } + return { + 'done': true + }; + } + } +}); + +bench( pkg+'::iterable,clbk:from:', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int16Array.from( createIterable(), clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt16Array( arr ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out; + var i; + + out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + + i = 0; + + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + i += 1; + if ( i <= 2 ) { + return { + 'value': 1, + 'done': false + }; + } + return { + 'done': true + }; + } + } + + function clbk( v ) { + return v + 1; + } +}); diff --git a/int16/benchmark/benchmark.includes.js b/int16/benchmark/benchmark.includes.js new file mode 100644 index 00000000..62c3d8dd --- /dev/null +++ b/int16/benchmark/benchmark.includes.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':includes', function benchmark( b ) { + var bool; + var arr; + var v; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + bool = arr.includes( v ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/benchmark/benchmark.includes.length.js b/int16/benchmark/benchmark.includes.length.js new file mode 100644 index 00000000..d69dfe98 --- /dev/null +++ b/int16/benchmark/benchmark.includes.length.js @@ -0,0 +1,96 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + bool = arr.includes( v ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':includes:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.index_of.js b/int16/benchmark/benchmark.index_of.js new file mode 100644 index 00000000..bab8a1a7 --- /dev/null +++ b/int16/benchmark/benchmark.index_of.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':indexOf', function benchmark( b ) { + var out; + var arr; + var v; + var i; + + arr = new Int16Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.indexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/benchmark/benchmark.index_of.length.js b/int16/benchmark/benchmark.index_of.length.js new file mode 100644 index 00000000..c2258f75 --- /dev/null +++ b/int16/benchmark/benchmark.index_of.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.indexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':indexOf:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.join.js b/int16/benchmark/benchmark.join.js new file mode 100644 index 00000000..6f68e402 --- /dev/null +++ b/int16/benchmark/benchmark.join.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':join', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i % 127; + out = arr.join(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/benchmark/benchmark.join.length.js b/int16/benchmark/benchmark.join.length.js new file mode 100644 index 00000000..4d4344de --- /dev/null +++ b/int16/benchmark/benchmark.join.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i % 127; + out = arr.join(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':join:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.js b/int16/benchmark/benchmark.js new file mode 100644 index 00000000..b7de8c21 --- /dev/null +++ b/int16/benchmark/benchmark.js @@ -0,0 +1,47 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt16Array = require( '@stdlib/assert/is-int16array' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new ctor( 0 ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isInt16Array( arr ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/benchmark/benchmark.keys.js b/int16/benchmark/benchmark.keys.js new file mode 100644 index 00000000..5affbd12 --- /dev/null +++ b/int16/benchmark/benchmark.keys.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':keys', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.keys(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/benchmark/benchmark.last_index_of.js b/int16/benchmark/benchmark.last_index_of.js new file mode 100644 index 00000000..00d3186a --- /dev/null +++ b/int16/benchmark/benchmark.last_index_of.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':lastIndexOf', function benchmark( b ) { + var out; + var arr; + var v; + var i; + + arr = new Int16Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.lastIndexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/benchmark/benchmark.last_index_of.length.js b/int16/benchmark/benchmark.last_index_of.length.js new file mode 100644 index 00000000..aa69337d --- /dev/null +++ b/int16/benchmark/benchmark.last_index_of.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.lastIndexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':lastIndexOf:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.length.js b/int16/benchmark/benchmark.length.js new file mode 100644 index 00000000..e61203ec --- /dev/null +++ b/int16/benchmark/benchmark.length.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isInt16Array = require( '@stdlib/assert/is-int16array' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new ctor( len ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isInt16Array( arr ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.map.js b/int16/benchmark/benchmark.map.js new file mode 100644 index 00000000..4405af65 --- /dev/null +++ b/int16/benchmark/benchmark.map.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt16Array = require( '@stdlib/assert/is-int16array' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':map', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt16Array( out ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); + +bench( pkg+'::this_context:map', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn, {} ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt16Array( out ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/int16/benchmark/benchmark.map.length.js b/int16/benchmark/benchmark.map.length.js new file mode 100644 index 00000000..2b3c70f8 --- /dev/null +++ b/int16/benchmark/benchmark.map.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isInt16Array = require( '@stdlib/assert/is-int16array' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Maps an array element to a new value. +* +* @private +* @param {*} value - array element +* @returns {*} new value +*/ +function fcn( value ) { + return value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt16Array( out ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':map:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.of.js b/int16/benchmark/benchmark.of.js new file mode 100644 index 00000000..837f9e3c --- /dev/null +++ b/int16/benchmark/benchmark.of.js @@ -0,0 +1,48 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt16Array = require( '@stdlib/assert/is-int16array' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':of', function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int16Array.of( i, 2 ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt16Array( arr ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/benchmark/benchmark.properties.js b/int16/benchmark/benchmark.properties.js new file mode 100644 index 00000000..2a061fcd --- /dev/null +++ b/int16/benchmark/benchmark.properties.js @@ -0,0 +1,145 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isArrayBuffer = require( '@stdlib/assert/is-arraybuffer' ); +var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::get:buffer', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.buffer; + if ( typeof v !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isArrayBuffer( v ) ) { + b.fail( 'should return an ArrayBuffer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteLength', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteLength; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteOffset', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteOffset; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:BYTES_PER_ELEMENT', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.BYTES_PER_ELEMENT; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:length', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.length; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/benchmark/benchmark.reduce.js b/int16/benchmark/benchmark.reduce.js new file mode 100644 index 00000000..c377afa4 --- /dev/null +++ b/int16/benchmark/benchmark.reduce.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reduce', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( acc, v ) { + return acc + v + 1; + } +}); + +bench( pkg+'::initial_value:reduce', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn, 3 ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/int16/benchmark/benchmark.reduce.length.js b/int16/benchmark/benchmark.reduce.length.js new file mode 100644 index 00000000..3320230b --- /dev/null +++ b/int16/benchmark/benchmark.reduce.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Updates an accumulated value. +* +* @private +* @param {*} acc - accumulated value +* @param {*} value - array element +* @returns {*} accumulated value +*/ +function fcn( acc, value ) { + return acc + value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reduce:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.reduce_right.js b/int16/benchmark/benchmark.reduce_right.js new file mode 100644 index 00000000..13069993 --- /dev/null +++ b/int16/benchmark/benchmark.reduce_right.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reduceRight', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( acc, v ) { + return acc + v + 1; + } +}); + +bench( pkg+'::initial_value:reduceRight', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn, 3 ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/int16/benchmark/benchmark.reduce_right.length.js b/int16/benchmark/benchmark.reduce_right.length.js new file mode 100644 index 00000000..524c9acd --- /dev/null +++ b/int16/benchmark/benchmark.reduce_right.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Updates an accumulated value. +* +* @private +* @param {*} acc - accumulated value +* @param {*} value - array element +* @returns {*} accumulated value +*/ +function fcn( acc, value ) { + return acc + value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reduceRight:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.reverse.js b/int16/benchmark/benchmark.reverse.js new file mode 100644 index 00000000..d831070b --- /dev/null +++ b/int16/benchmark/benchmark.reverse.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt16Array = require( '@stdlib/assert/is-int16array' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reverse', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.reverse(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt16Array( out ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/benchmark/benchmark.reverse.length.js b/int16/benchmark/benchmark.reverse.length.js new file mode 100644 index 00000000..28d24815 --- /dev/null +++ b/int16/benchmark/benchmark.reverse.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isInt16Array = require( '@stdlib/assert/is-int16array' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.reverse(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt16Array( out ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reverse:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.set.js b/int16/benchmark/benchmark.set.js new file mode 100644 index 00000000..419bb419 --- /dev/null +++ b/int16/benchmark/benchmark.set.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::array:set', function benchmark( b ) { + var values; + var buf; + var arr; + var N; + var v; + var i; + + values = []; + for ( i = 0; i < 10; i++ ) { + values.push( i ); + } + N = values.length; + + arr = new Int16Array( 2 ); + buf = [ 0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = values[ i%N ]; + v = arr.set( buf ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array:set', function benchmark( b ) { + var values; + var buf; + var arr; + var N; + var v; + var i; + + values = new Int16Array( 20 ); + N = values.length; + for ( i = 0; i < N; i++ ) { + values[ i ] = i; + } + + arr = new Int16Array( 2 ); + buf = new Int16Array( 1 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = values[ i%N ]; + v = arr.set( buf ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/benchmark/benchmark.set.length.js b/int16/benchmark/benchmark.set.length.js new file mode 100644 index 00000000..a5ba2d8f --- /dev/null +++ b/int16/benchmark/benchmark.set.length.js @@ -0,0 +1,114 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randi = require( '@stdlib/random/base/randi' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var values; + var arr1; + var arr2; + var arr; + var N; + var i; + + arr1 = []; + arr2 = []; + for ( i = 0; i < len; i++ ) { + arr1.push( randi() ); + arr2.push( randi() ); + } + arr = new Int16Array( len ); + + values = [ + arr1, + arr2 + ]; + N = values.length; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr.set( values[ i%N ] ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':set:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.slice.js b/int16/benchmark/benchmark.slice.js new file mode 100644 index 00000000..a4d7f810 --- /dev/null +++ b/int16/benchmark/benchmark.slice.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt16Array = require( '@stdlib/assert/is-int16array' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':slice', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.slice(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt16Array( out ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/benchmark/benchmark.slice.length.js b/int16/benchmark/benchmark.slice.length.js new file mode 100644 index 00000000..891f92d3 --- /dev/null +++ b/int16/benchmark/benchmark.slice.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isInt16Array = require( '@stdlib/assert/is-int16array' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.slice(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt16Array( out ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':slice:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.some.js b/int16/benchmark/benchmark.some.js new file mode 100644 index 00000000..336fd656 --- /dev/null +++ b/int16/benchmark/benchmark.some.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':some', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:some', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate, {} ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/int16/benchmark/benchmark.some.length.js b/int16/benchmark/benchmark.some.length.js new file mode 100644 index 00000000..07549123 --- /dev/null +++ b/int16/benchmark/benchmark.some.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':some:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.sort.js b/int16/benchmark/benchmark.sort.js new file mode 100644 index 00000000..d9a420e7 --- /dev/null +++ b/int16/benchmark/benchmark.sort.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var randi = require( '@stdlib/random/base/randi' ); +var isInt16Array = require( '@stdlib/assert/is-int16array' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':sort', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int16Array( [ randi(), randi() ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = randi(); + out = arr.sort(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt16Array( out ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/benchmark/benchmark.sort.length.js b/int16/benchmark/benchmark.sort.length.js new file mode 100644 index 00000000..cc05c62a --- /dev/null +++ b/int16/benchmark/benchmark.sort.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randi = require( '@stdlib/random/base/randi' ); +var isInt16Array = require( '@stdlib/assert/is-int16array' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var data; + var arr; + var i; + + data = []; + for ( i = 0; i < len; i++ ) { + data.push( randi() ); + } + arr = new Int16Array( data ); + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ i%len ] = randi(); + out = arr.sort(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt16Array( out ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':sort:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.subarray.js b/int16/benchmark/benchmark.subarray.js new file mode 100644 index 00000000..a0833f73 --- /dev/null +++ b/int16/benchmark/benchmark.subarray.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt16Array = require( '@stdlib/assert/is-int16array' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':subarray', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.subarray(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt16Array( out ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/benchmark/benchmark.subarray.length.js b/int16/benchmark/benchmark.subarray.length.js new file mode 100644 index 00000000..8501c8da --- /dev/null +++ b/int16/benchmark/benchmark.subarray.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isInt16Array = require( '@stdlib/assert/is-int16array' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.subarray(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt16Array( out ) ) { + b.fail( 'should return an Int16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':subarray:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.to_locale_string.js b/int16/benchmark/benchmark.to_locale_string.js new file mode 100644 index 00000000..9e0bd74b --- /dev/null +++ b/int16/benchmark/benchmark.to_locale_string.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':toLocaleString', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toLocaleString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/benchmark/benchmark.to_locale_string.length.js b/int16/benchmark/benchmark.to_locale_string.length.js new file mode 100644 index 00000000..c1e68877 --- /dev/null +++ b/int16/benchmark/benchmark.to_locale_string.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toLocaleString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':toLocaleString:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.to_string.js b/int16/benchmark/benchmark.to_string.js new file mode 100644 index 00000000..6e6d5d95 --- /dev/null +++ b/int16/benchmark/benchmark.to_string.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':toString', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/benchmark/benchmark.to_string.length.js b/int16/benchmark/benchmark.to_string.length.js new file mode 100644 index 00000000..306e398d --- /dev/null +++ b/int16/benchmark/benchmark.to_string.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':toString:len='+len, f ); + } +} + +main(); diff --git a/int16/benchmark/benchmark.values.js b/int16/benchmark/benchmark.values.js new file mode 100644 index 00000000..a34f4ca6 --- /dev/null +++ b/int16/benchmark/benchmark.values.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':values', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Int16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.values(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int16/docs/repl.txt b/int16/docs/repl.txt new file mode 100644 index 00000000..403ece47 --- /dev/null +++ b/int16/docs/repl.txt @@ -0,0 +1,953 @@ + +{{alias}}() + A typed array constructor which returns a typed array representing an array + of twos-complement 16-bit signed integers in the platform byte order. + + Returns + ------- + out: Int16Array + A typed array. + + Examples + -------- + > var arr = new {{alias}}() + + + +{{alias}}( length ) + Returns a typed array having a specified length. + + Parameters + ---------- + length: integer + Typed array length. + + Returns + ------- + out: Int16Array + A typed array. + + Examples + -------- + > var arr = new {{alias}}( 5 ) + [ 0, 0, 0, 0, 0 ] + + +{{alias}}( typedarray ) + Creates a typed array from another typed array. + + Parameters + ---------- + typedarray: TypedArray + Typed array from which to generate another typed array. + + Returns + ------- + out: Int16Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias:@stdlib/array/int32}}( [ 5, 5, 5 ] ); + > var arr2 = new {{alias}}( arr1 ) + [ 5, 5, 5 ] + + +{{alias}}( obj ) + Creates a typed array from an array-like object or iterable. + + Parameters + ---------- + obj: Object + Array-like object or iterable from which to generate a typed array. + + Returns + ------- + out: Int16Array + A typed array. + + Examples + -------- + > var arr1 = [ 5.0, 5.0, 5.0 ]; + > var arr2 = new {{alias}}( arr1 ) + [ 5, 5, 5 ] + + +{{alias}}( buffer[, byteOffset[, length]] ) + Returns a typed array view of an ArrayBuffer. + + Parameters + ---------- + buffer: ArrayBuffer + Underlying ArrayBuffer. + + byteOffset: integer (optional) + Integer byte offset specifying the location of the first typed array + element. Default: 0. + + length: integer (optional) + View length. If not provided, the view spans from the byteOffset to + the end of the underlying ArrayBuffer. + + Returns + ------- + out: Int16Array + A typed array. + + Examples + -------- + > var buf = new {{alias:@stdlib/array/buffer}}( 8 ); + > var arr = new {{alias}}( buf, 0, 4 ) + [ 0, 0, 0, 0 ] + + +{{alias}}.from( src[, map[, thisArg]] ) + Creates a new typed array from an array-like object or an iterable. + + A callback is provided the following arguments: + + - value: source value. + - index: source index. + + Parameters + ---------- + src: ArrayLike|Iterable + Source of array elements. + + map: Function (optional) + Callback to invoke for each source element. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Int16Array + A typed array. + + Examples + -------- + > function mapFcn( v ) { return v * 2; }; + > var arr = {{alias}}.from( [ 1, 2 ], mapFcn ) + [ 2, 4 ] + + +{{alias}}.of( element0[, element1[, ...elementN]] ) + Creates a new typed array from a variable number of arguments. + + Parameters + ---------- + element0: number + Array element. + + element1: number (optional) + Array element. + + elementN: number (optional) + Array elements. + + Returns + ------- + out: Int16Array + A typed array. + + Examples + -------- + > var arr = {{alias}}.of( 1, 2 ) + [ 1, 2 ] + + +{{alias}}.BYTES_PER_ELEMENT + Number of bytes per view element. + + Examples + -------- + > {{alias}}.BYTES_PER_ELEMENT + 2 + + +{{alias}}.name + Typed array constructor name. + + Examples + -------- + > {{alias}}.name + 'Int16Array' + + +{{alias}}.prototype.buffer + Read-only property which returns the ArrayBuffer referenced by the typed + array. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.buffer + + + +{{alias}}.prototype.byteLength + Read-only property which returns the length (in bytes) of the typed array. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.byteLength + 10 + + +{{alias}}.prototype.byteOffset + Read-only property which returns the offset (in bytes) of the typed array + from the start of its ArrayBuffer. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.byteOffset + 0 + + +{{alias}}.prototype.BYTES_PER_ELEMENT + Number of bytes per view element. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.BYTES_PER_ELEMENT + 2 + + +{{alias}}.prototype.length + Read-only property which returns the number of view elements. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.length + 5 + + +{{alias}}.prototype.copyWithin( target, start[, end] ) + Copies a sequence of elements within the array starting at `start` and + ending at `end` (non-inclusive) to the position starting at `target`. + + Parameters + ---------- + target: integer + Target start index position. + + start: integer + Source start index position. + + end: integer (optional) + Source end index position. Default: out.length. + + Returns + ------- + out: Int16Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3, 4, 5 ] ); + > arr.copyWithin( 3, 0, 2 ); + > arr[ 3 ] + 1 + > arr[ 4 ] + 2 + + +{{alias}}.prototype.entries() + Returns an iterator for iterating over array key-value pairs. + + Returns + ------- + iter: Iterator + Iterator for iterating over array key-value pairs. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.entries(); + > it.next().value + [ 0, 1 ] + > it.next().value + [ 1, 2 ] + > it.next().done + true + + +{{alias}}.prototype.every( predicate[, thisArg] ) + Tests whether all array elements pass a test implemented by a predicate + function. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. If a predicate function + returns a truthy value, an array element passes; otherwise, an array + element fails. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + bool: boolean + Boolean indicating whether all array elements pass. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > function predicate( v ) { return ( v <= 1 ); }; + > arr.every( predicate ) + false + + +{{alias}}.prototype.fill( value[, start[, end]] ) + Fills an array from a start index to an end index (non-inclusive) with a + provided value. + + Parameters + ---------- + value: number + Fill value. + + start: integer (optional) + Start index. If less than zero, the start index is resolved relative to + the last array element. Default: 0. + + end: integer (optional) + End index (non-inclusive). If less than zero, the end index is resolved + relative to the last array element. Default: out.length. + + Returns + ------- + out: Int16Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > arr.fill( 3 ); + > arr[ 0 ] + 3 + > arr[ 1 ] + 3 + + +{{alias}}.prototype.filter( predicate[, thisArg] ) + Creates a new array which includes those elements for which a predicate + function returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + The returned array has the same data type as the host array. + + If a predicate function does not return a truthy value for any array + element, the method returns `null`. + + Parameters + ---------- + predicate: Function + Predicate function which filters array elements. If a predicate function + returns a truthy value, an array element is included in the output + array; otherwise, an array element is not included in the output array. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Int16Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 1 ); }; + > var arr2 = arr1.filter( predicate ); + > arr2.length + 2 + + +{{alias}}.prototype.find( predicate[, thisArg] ) + Returns the first array element for which a provided predicate function + returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + If a predicate function never returns a truthy value, the method returns + `undefined`. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + value: number|undefined + Array element. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 2 ); }; + > var v = arr.find( predicate ) + 3 + + +{{alias}}.prototype.findIndex( predicate[, thisArg] ) + Returns the index of the first array element for which a provided predicate + function returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + If a predicate function never returns a truthy value, the method returns + `-1`. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + idx: integer + Array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 2 ); }; + > var idx = arr.findIndex( predicate ) + 2 + + +{{alias}}.prototype.forEach( fcn[, thisArg] ) + Invokes a callback for each array element. + + A provided function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + fcn: Function + Function to invoke for each array element. + + thisArg: Any (optional) + Callback execution context. + + Examples + -------- + > var arr = new {{alias}}( [ 3, 2, 1 ] ); + > var str = ' '; + > function fcn( v, i ) { str += i + ':' + v + ' '; }; + > arr.forEach( fcn ); + > str + ' 0:3 1:2 2:1 ' + + +{{alias}}.prototype.includes( searchElement[, fromIndex] ) + Returns a boolean indicating whether an array includes a search element. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: 0. + + Returns + ------- + bool: boolean + Boolean indicating whether an array includes a search element. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > var bool = arr.includes( 4 ) + false + > bool = arr.includes( 3 ) + true + + +{{alias}}.prototype.indexOf( searchElement[, fromIndex] ) + Returns the index of the first array element strictly equal to a search + element. + + If unable to locate a search element, the method returns `-1`. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: 0. + + Returns + ------- + idx: integer + Array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > var idx = arr.indexOf( 4 ) + -1 + > idx = arr.indexOf( 3 ) + 2 + + +{{alias}}.prototype.join( [separator] ) + Serializes an array by joining all array elements as a string. + + Parameters + ---------- + separator: string (optional) + String delineating array elements. Default: ','. + + Returns + ------- + str: string + Array serialized as a string. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.join( '|' ) + '1|2|3' + + +{{alias}}.prototype.keys() + Returns an iterator for iterating over array keys. + + Returns + ------- + iter: Iterator + Iterator for iterating over array keys. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.keys(); + > it.next().value + 0 + > it.next().value + 1 + > it.next().done + true + + +{{alias}}.prototype.lastIndexOf( searchElement[, fromIndex] ) + Returns the index of the last array element strictly equal to a search + element. + + The method iterates from the last array element to the first array element. + + If unable to locate a search element, the method returns `-1`. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: -1. + + Returns + ------- + idx: integer + array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 0, 2, 0, 1 ] ); + > var idx = arr.lastIndexOf( 3 ) + -1 + > idx = arr.lastIndexOf( 0 ) + 3 + + +{{alias}}.prototype.map( fcn[, thisArg] ) + Maps each array element to an element in a new typed array. + + A provided function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + The returned array has the same data type as the host array. + + Parameters + ---------- + fcn: Function + Function which maps array elements to elements in the new array. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Int16Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( v ) { return v * 2; }; + > var arr2 = arr1.map( fcn ); + [ 2, 4, 6 ] + + +{{alias}}.prototype.reduce( fcn[, initialValue] ) + Applies a function against an accumulator and each element in an array and + returns the accumulated result. + + The provided function is provided the following arguments: + + - acc: accumulated result. + - value: current array element. + - index: index of the current array element. + - arr: array on which the method is invoked. + + If provided an initial value, the method invokes a provided function with + the initial value as the first argument and the first array element as the + second argument. + + If not provided an initial value, the method invokes a provided function + with the first array element as the first argument and the second array + element as the second argument. + + Parameters + ---------- + fcn: Function + Function to apply. + + initialValue: Any (optional) + Initial accumulation value. + + Returns + ------- + out: Any + Accumulated result. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( acc, v ) { return acc + (v*v); }; + > var v = arr.reduce( fcn, 0 ) + 14 + + +{{alias}}.prototype.reduceRight( fcn[, initialValue] ) + Applies a function against an accumulator and each element in an array and + returns the accumulated result, iterating from right to left. + + The provided function is provided the following arguments: + + - acc: accumulated result. + - value: current array element. + - index: index of the current array element. + - arr: array on which the method is invoked. + + If provided an initial value, the method invokes a provided function with + the initial value as the first argument and the last array element as the + second argument. + + If not provided an initial value, the method invokes a provided function + with the last array element as the first argument and the second-to-last + array element as the second argument. + + Parameters + ---------- + fcn: Function + Function to apply. + + initialValue: Any (optional) + Initial accumulation value. + + Returns + ------- + out: Any + Accumulated result. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( acc, v ) { return acc + (v*v); }; + > var v = arr.reduceRight( fcn, 0 ) + 14 + + +{{alias}}.prototype.reverse() + Reverses an array *in-place*. + + This method mutates the array on which the method is invoked. + + Returns + ------- + out: Int16Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ) + [ 1, 2, 3 ] + > arr.reverse() + [ 3, 2, 1 ] + + +{{alias}}.prototype.set( arr[, offset] ) + Sets array elements. + + Parameters + ---------- + arr: ArrayLike + Source array containing array values to set. + + offset: integer (optional) + Array index at which to start writing values. Default: 0. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.set( [ 4, 4 ], 1 ); + > arr[ 1 ] + 4 + > arr[ 2 ] + 4 + + +{{alias}}.prototype.slice( [begin[, end]] ) + Copies array elements to a new array with the same underlying data type as + the host array. + + If the method is unable to resolve indices to a non-empty array subsequence, + the method returns `null`. + + Parameters + ---------- + begin: integer (optional) + Start element index (inclusive). If less than zero, the start index is + resolved relative to the last array element. Default: 0. + + end: integer (optional) + End element index (exclusive). If less than zero, the end index is + resolved relative to the last array element. Default: arr.length. + + Returns + ------- + out: Int16Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > var arr2 = arr1.slice( 1 ); + > arr2.length + 2 + > arr2[ 0 ] + 1 + > arr2[ 1 ] + 2 + + +{{alias}}.prototype.some( predicate[, thisArg] ) + Tests whether at least one array element passes a test implemented by a + predicate function. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. If a predicate function + returns a truthy value, a array element passes; otherwise, an array + element fails. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + bool: boolean + Boolean indicating whether at least one array element passes. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > function predicate( v ) { return ( v > 1 ); }; + > arr.some( predicate ) + true + + +{{alias}}.prototype.sort( [compareFunction] ) + Sorts an array *in-place*. + + The comparison function is provided two array elements per invocation: `a` + and `b`. + + The comparison function return value determines the sort order as follows: + + - If the comparison function returns a value less than zero, then the method + sorts `a` to an index lower than `b` (i.e., `a` should come *before* `b`). + + - If the comparison function returns a value greater than zero, then the + method sorts `a` to an index higher than `b` (i.e., `b` should come *before* + `a`). + + - If the comparison function returns zero, then the relative order of `a` + and `b` should remain unchanged. + + This method mutates the array on which the method is invoked. + + Parameters + ---------- + compareFunction: Function (optional) + Function which specifies the sort order. The default sort order is + ascending order. + + Returns + ------- + out: Int16Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 0, 2, 1 ] ); + > arr.sort() + [ 0, 1, 1, 2, 2 ] + + +{{alias}}.prototype.subarray( [begin[, end]] ) + Creates a new typed array over the same underlying ArrayBuffer and with the + same underlying data type as the host array. + + If the method is unable to resolve indices to a non-empty array subsequence, + the method returns an empty typed array. + + Parameters + ---------- + begin: integer (optional) + Start element index (inclusive). If less than zero, the start index is + resolved relative to the last array element. Default: 0. + + end: integer (optional) + End element index (exclusive). If less than zero, the end index is + resolved relative to the last array element. Default: arr.length. + + Returns + ------- + out: Int16Array + A new typed array view. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3, 4, 5 ] ); + > var arr2 = arr1.subarray( 2 ) + [ 3, 4, 5 ] + + +{{alias}}.prototype.toLocaleString( [locales[, options]] ) + Serializes an array as a locale-specific string. + + Parameters + ---------- + locales: string|Array (optional) + A BCP 47 language tag, or an array of such tags. + + options: Object (optional) + Options. + + Returns + ------- + str: string + A typed array string representation. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.toLocaleString() + '1,2,3' + + +{{alias}}.prototype.toString() + Serializes an array as a string. + + Returns + ------- + str: string + A typed array string representation. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.toString() + '1,2,3' + + +{{alias}}.prototype.values() + Returns an iterator for iterating over array elements. + + Returns + ------- + iter: Iterator + Iterator for iterating over array elements. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.values(); + > it.next().value + 1 + > it.next().value + 2 + > it.next().done + true + + + See Also + -------- + diff --git a/int16/docs/types/index.d.ts b/int16/docs/types/index.d.ts new file mode 100644 index 00000000..d865f448 --- /dev/null +++ b/int16/docs/types/index.d.ts @@ -0,0 +1,26 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +// EXPORTS // + +/** +* Typed array constructor which returns a typed array representing an array of twos-complement 16-bit signed integers in the platform byte order. +*/ +export = Int16Array; diff --git a/int16/docs/types/test.ts b/int16/docs/types/test.ts new file mode 100644 index 00000000..67bedcf1 --- /dev/null +++ b/int16/docs/types/test.ts @@ -0,0 +1,37 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// tslint:disable: no-construct +// tslint:disable: no-unused-expression + +import Int16Array = require( './index' ); + + +// TESTS // + +// The function returns a typed array instance... +{ + new Int16Array( 10 ); // $ExpectType Int16Array + new Int16Array( [ 2, 5, 5, 7 ] ); // $ExpectType Int16Array +} + +// The constructor function has to be invoked with `new`... +{ + Int16Array( 10 ); // $ExpectError + Int16Array( [ 2, 5, 5, 7 ] ); // $ExpectError +} diff --git a/int16/examples/index.js b/int16/examples/index.js new file mode 100644 index 00000000..d0978bec --- /dev/null +++ b/int16/examples/index.js @@ -0,0 +1,32 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var randu = require( '@stdlib/random/base/randu' ); +var round = require( '@stdlib/math/base/special/round' ); +var ctor = require( './../lib' ); + +var arr; +var i; + +arr = new ctor( 10 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = round( randu()*100.0 ); +} +console.log( arr ); diff --git a/int16/lib/index.js b/int16/lib/index.js new file mode 100644 index 00000000..72be1012 --- /dev/null +++ b/int16/lib/index.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Typed array constructor which returns a typed array representing an array of twos-complement 16-bit signed integers in the platform byte order. +* +* @module @stdlib/array/int16 +* +* @example +* var ctor = require( '@stdlib/array/int16' ); +* +* var arr = new ctor( 10 ); +* // returns +*/ + +// MODULES // + +var hasInt16ArraySupport = require( '@stdlib/assert/has-int16array-support' ); +var builtin = require( './int16array.js' ); +var polyfill = require( './polyfill.js' ); + + +// MAIN // + +var ctor; +if ( hasInt16ArraySupport() ) { + ctor = builtin; +} else { + ctor = polyfill; +} + + +// EXPORTS // + +module.exports = ctor; diff --git a/int16/lib/int16array.js b/int16/lib/int16array.js new file mode 100644 index 00000000..39cbaf0c --- /dev/null +++ b/int16/lib/int16array.js @@ -0,0 +1,28 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MAIN // + +var ctor = ( typeof Int16Array === 'function' ) ? Int16Array : void 0; // eslint-disable-line stdlib/require-globals + + +// EXPORTS // + +module.exports = ctor; diff --git a/int16/lib/polyfill.js b/int16/lib/polyfill.js new file mode 100644 index 00000000..d7261e19 --- /dev/null +++ b/int16/lib/polyfill.js @@ -0,0 +1,37 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// TODO: write polyfill + +// MAIN // + +/** +* Typed array which represents an array of twos-complement 16-bit signed integers in the platform byte order. +* +* @throws {Error} not implemented +*/ +function polyfill() { + throw new Error( 'not implemented' ); +} + + +// EXPORTS // + +module.exports = polyfill; diff --git a/int16/package.json b/int16/package.json new file mode 100644 index 00000000..b205cdf2 --- /dev/null +++ b/int16/package.json @@ -0,0 +1,69 @@ +{ + "name": "@stdlib/array/int16", + "version": "0.0.0", + "description": "Int16Array.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structure", + "array", + "typed", + "typed array", + "typed-array", + "int16array", + "int16", + "int16_t", + "integer", + "int", + "signed", + "short" + ] +} diff --git a/int16/test/test.copy_within.js b/int16/test/test.copy_within.js new file mode 100644 index 00000000..357839c7 --- /dev/null +++ b/int16/test/test.copy_within.js @@ -0,0 +1,320 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var hasProp = require( '@stdlib/assert/has-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var Int16Array = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof Int16Array, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'a typed array instance has a `copyWithin` method for copying a sequence of elements within a typed array', function test( t ) { + var arr = new Int16Array( 2 ); + t.strictEqual( hasProp( arr, 'copyWithin' ), true, 'has property' ); + t.strictEqual( isFunction( arr.copyWithin ), true, 'has method' ); + t.end(); +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a typed array instance', function test( t ) { + var values; + var arr; + var i; + + arr = new Int16Array( 2 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0 ); + }; + } +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a typed array instance (end)', function test( t ) { + var values; + var arr; + var i; + + arr = new Int16Array( 2 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0, 5 ); + }; + } +}); + +tape( 'the method copies a sequence of elements within a typed array', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int16Array( arr ); + p.copyWithin( 0, 3 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative target)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int16Array( arr ); + p.copyWithin( -p.length, 3 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative start)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int16Array( arr ); + p.copyWithin( 0, -2 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (end=length)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int16Array( arr ); + p.copyWithin( 0, 3, p.length ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (non-inclusive end)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int16Array( arr ); + p.copyWithin( 2, 0, 2 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative end)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int16Array( arr ); + p.copyWithin( 2, 0, -3 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (target >= length)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int16Array( arr ); + p.copyWithin( p.length, 3 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (target > start)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int16Array( arr ); + p.copyWithin( 2, 0 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + t.strictEqual( p[ 4 ], 2, 'returns expected value' ); + + t.end(); +}); diff --git a/int16/test/test.js b/int16/test/test.js new file mode 100644 index 00000000..635243b2 --- /dev/null +++ b/int16/test/test.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var hasInt16ArraySupport = require( '@stdlib/assert/has-int16array-support' ); +var polyfill = require( './../lib/polyfill.js' ); +var ctor = require( './../lib' ); + + +// VARIABLES // + +var hasInt16Arrays = hasInt16ArraySupport(); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'if an environment supports `Int16Array`, the export is an alias for `Int16Array`', function test( t ) { + var Foo; + + Foo = proxyquire( './../lib', { + '@stdlib/assert/has-int16array-support': isTrue, + './int16array.js': Mock + }); + t.strictEqual( Foo, Mock, 'returns builtin' ); + + if ( hasInt16Arrays ) { + t.strictEqual( ctor, Int16Array, 'is alias' ); // eslint-disable-line stdlib/require-globals + } + + t.end(); + + function Mock() { + return this; + } + + function isTrue() { + return true; + } +}); + +tape( 'if an environment does not support `Int16Array`, the export is a polyfill', function test( t ) { + var Foo; + + Foo = proxyquire( './../lib', { + '@stdlib/assert/has-int16array-support': isFalse + }); + + t.strictEqual( Foo, polyfill, 'returns polyfill' ); + t.end(); + + function isFalse() { + return false; + } +}); diff --git a/int16/test/test.polyfill.js b/int16/test/test.polyfill.js new file mode 100644 index 00000000..9d6fcb19 --- /dev/null +++ b/int16/test/test.polyfill.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var ctor = require( './../lib/polyfill.js' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error when invoked', function test( t ) { + t.throws( foo, Error, 'throws an error' ); + t.end(); + + function foo() { + var f = new ctor(); // eslint-disable-line no-unused-vars + } +}); + +// TODO: tests diff --git a/int32/README.md b/int32/README.md new file mode 100644 index 00000000..332e8012 --- /dev/null +++ b/int32/README.md @@ -0,0 +1,1431 @@ + + +# Int32Array + +> [Typed array][mdn-typed-array] constructor which returns a [typed array][mdn-typed-array] representing an array of twos-complement 32-bit signed integers in the platform byte order. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var Int32Array = require( '@stdlib/array/int32' ); +``` + +#### Int32Array() + +A [typed array][mdn-typed-array] constructor which returns a [typed array][mdn-typed-array] representing an array of twos-complement 32-bit signed integers in the platform byte order. + + + +```javascript +var arr = new Int32Array(); +// returns +``` + +#### Int32Array( length ) + +Returns a [typed array][mdn-typed-array] having a specified length. + + + +```javascript +var arr = new Int32Array( 5 ); +// returns [ 0, 0, 0, 0, 0 ] +``` + +#### Int32Array( typedarray ) + +Creates a [typed array][mdn-typed-array] from another [typed array][mdn-typed-array]. + + + +```javascript +var Float32Array = require( '@stdlib/array/float32' ); + +var arr1 = new Float32Array( [ 5.0, 5.0, 5.0 ] ); +var arr2 = new Int32Array( arr1 ); +// returns [ 5, 5, 5 ] +``` + +#### Int32Array( obj ) + +Creates a [typed array][mdn-typed-array] from an array-like `object` or iterable. + + + +```javascript +var arr = new Int32Array( [ 5.0, 5.0, 5.0 ] ); +// returns [ 5, 5, 5 ] +``` + +#### Int32Array( buffer\[, byteOffset\[, length]] ) + +Returns a [typed array][mdn-typed-array] view of an [`ArrayBuffer`][@stdlib/array/buffer]. + + + +```javascript +var ArrayBuffer = require( '@stdlib/array/buffer' ); + +var buf = new ArrayBuffer( 16 ); +var arr = new Int32Array( buf, 0, 4 ); +// returns [ 0, 0, 0, 0 ] +``` + +* * * + +### Properties + + + +#### Int32Array.BYTES_PER_ELEMENT + +Number of bytes per view element. + + + +```javascript +var nbytes = Int32Array.BYTES_PER_ELEMENT; +// returns 4 +``` + + + +#### Int32Array.name + +[Typed array][mdn-typed-array] constructor name. + + + +```javascript +var str = Int32Array.name; +// returns 'Int32Array' +``` + + + +#### Int32Array.prototype.buffer + +**Read-only** property which returns the [`ArrayBuffer`][@stdlib/array/buffer] referenced by the [typed array][mdn-typed-array]. + + + +```javascript +var arr = new Int32Array( 5 ); +var buf = arr.buffer; +// returns +``` + + + +#### Int32Array.prototype.byteLength + +**Read-only** property which returns the length (in bytes) of the [typed array][mdn-typed-array]. + + + +```javascript +var arr = new Int32Array( 5 ); +var byteLength = arr.byteLength; +// returns 20 +``` + + + +#### Int32Array.prototype.byteOffset + +**Read-only** property which returns the offset (in bytes) of the [typed array][mdn-typed-array] from the start of its [`ArrayBuffer`][@stdlib/array/buffer]. + + + +```javascript +var arr = new Int32Array( 5 ); +var byteOffset = arr.byteOffset; +// returns 0 +``` + + + +#### Int32Array.prototype.BYTES_PER_ELEMENT + +Number of bytes per view element. + + + +```javascript +var arr = new Int32Array( 5 ); +var nbytes = arr.BYTES_PER_ELEMENT; +// returns 4 +``` + + + +#### Int32Array.prototype.length + +**Read-only** property which returns the number of view elements. + + + +```javascript +var arr = new Int32Array( 5 ); +var len = arr.length; +// returns 5 +``` + +* * * + +### Methods + + + +#### Int32Array.from( src\[, map\[, thisArg]] ) + +Creates a new typed array from an array-like `object` or an iterable. + +```javascript +var arr = Int32Array.from( [ 1, 2 ] ); +// returns [ 1, 2 ] +``` + +To invoke a function for each `src` value, provide a callback function. + +```javascript +function mapFcn( v ) { + return v * 2; +} + +var arr = Int32Array.from( [ 1, 2 ], mapFcn ); +// returns [ 2, 4 ] +``` + +A callback function is provided two arguments: + +- `value`: source value +- `index`: source index + +To set the callback execution context, provide a `thisArg`. + +```javascript +function mapFcn( v ) { + this.count += 1; + return v * 2; +} + +var ctx = { + 'count': 0 +}; + +var arr = Int32Array.from( [ 1, 2 ], mapFcn, ctx ); +// returns [ 2, 4 ] + +var n = ctx.count; +// returns 2 +``` + + + +#### Int32Array.of( element0\[, element1\[, ...elementN]] ) + +Creates a new typed array from a variable number of arguments. + +```javascript +var arr = Int32Array.of( 1, 2 ); +// returns [ 1, 2 ] +``` + + + +#### Int32Array.prototype.copyWithin( target, start\[, end] ) + +Copies a sequence of elements within an array starting at `start` and ending at `end` (non-inclusive) to the position starting at `target`. + + + +```javascript +var arr = new Int32Array( [ 1, 2, 3, 4, 5 ] ); + +// Copy the last two elements to the first two elements: +arr.copyWithin( 0, 3 ); + +var v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 5 +``` + +By default, `end` equals the number of array elements (i.e., one more than the last array index). To limit the sequence length, provide an `end` argument. + + + +```javascript +var arr = new Int32Array( [ 1, 2, 3, 4, 5 ] ); + +// Copy the first two elements to the last two elements: +arr.copyWithin( 3, 0, 2 ); + +var v = arr[ 3 ]; +// returns 1 + +v = arr[ 4 ]; +// returns 2 +``` + +When a `target`, `start`, and/or `end` index is negative, the respective index is determined relative to the last array element. The following example achieves the same behavior as the previous example: + + + +```javascript +var arr = new Int32Array( [ 1, 2, 3, 4, 5 ] ); + +// Copy the first two elements to the last two elements: +arr.copyWithin( -2, -5, -3 ); + +var v = arr[ 3 ]; +// returns 1 + +v = arr[ 4 ]; +// returns 2 +``` + + + +#### Int32Array.prototype.entries() + +Returns an iterator for iterating over array key-value pairs. + + + +```javascript +var arr = new Int32Array( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.entries(); + +// Iterate over key-value pairs... +var v = it.next().value; +// returns [ 0, 1 ] + +v = it.next().value; +// returns [ 1, 2 ] + +var bool = it.next().done; +// returns true +``` + + + +#### Int32Array.prototype.every( predicate\[, thisArg] ) + +Tests whether all array elements pass a test implemented by a `predicate` function. + + + +```javascript +function predicate( v ) { + return ( v <= 1 ); +} + +var arr = new Int32Array( [ 1, 2 ] ); + +var bool = arr.every( predicate ); +// returns false +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 1 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Int32Array( [ 1, 2 ] ); + +var bool = arr.every( predicate, ctx ); +// returns true + +var n = ctx.count; +// returns 2 +``` + + + +#### Int32Array.prototype.fill( value\[, start\[, end]] ) + +Fills an array from a `start` index to an `end` index (non-inclusive) with a provided `value`. + + + +```javascript +var arr = new Int32Array( 2 ); + +// Set all array elements to the same value: +arr.fill( 2 ); + +var v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 2 + +// Set all array elements starting from the first index to the same value: +arr.fill( 3, 1 ); + +v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 3 + +// Set all array elements, except the last element, to the same value: +arr.fill( 4, 0, arr.length-1 ); + +v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 3 +``` + +When a `start` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr = new Int32Array( 2 ); + +// Set all array elements, except the last element, to the same value: +arr.fill( 2, -arr.length, -1 ); + +var v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 0 +``` + + + +#### Int32Array.prototype.filter( predicate\[, thisArg] ) + +Creates a new array (of the same data type as the host array) which includes those elements for which a `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v >= 2 ); +} + +var arr1 = new Int32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate ); +// returns [ 2, 3 ] +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns an empty array. + + + +```javascript +function predicate( v ) { + return ( v >= 10 ); +} + +var arr1 = new Int32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate ); +// returns [] +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr1 = new Int32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Int32Array.prototype.find( predicate\[, thisArg] ) + +Returns the first array element for which a provided `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v > 2 ); +} + +var arr = new Int32Array( [ 1, 2, 3 ] ); + +var v = arr.find( predicate ); +// returns 3 +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns `undefined`. + + + +```javascript +function predicate( v ) { + return ( v < 1 ); +} + +var arr = new Int32Array( [ 1, 2, 3 ] ); + +var v = arr.find( predicate ); +// returns undefined +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v > 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Int32Array( [ 1, 2, 3 ] ); + +var v = arr.find( predicate, ctx ); +// returns 3 + +var n = ctx.count; +// returns 3 +``` + + + +#### Int32Array.prototype.findIndex( predicate\[, thisArg] ) + +Returns the index of the first array element for which a provided `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v >= 3 ); +} + +var arr = new Int32Array( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate ); +// returns 2 +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns `-1`. + + + +```javascript +function predicate( v ) { + return ( v < 1 ); +} + +var arr = new Int32Array( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate ); +// returns -1 +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 3 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Int32Array( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate, ctx ); +// returns 2 + +var n = ctx.count; +// returns 3 +``` + + + +#### Int32Array.prototype.forEach( fcn\[, thisArg] ) + +Invokes a callback for each array element. + + + +```javascript +var arr = new Int32Array( [ 1, 2, 3 ] ); + +var str = ''; + +function fcn( v, i ) { + str += i + ':' + v; + if ( i < arr.length-1 ) { + str += ' '; + } +} + +arr.forEach( fcn ); + +console.log( str ); +// => '0:1 1:2 2:3' +``` + +The callback is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function fcn() { + this.count += 1; +} + +var ctx = { + 'count': 0 +}; + +var arr = new Int32Array( [ 1, 2, 3 ] ); + +arr.forEach( fcn, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Int32Array.prototype.includes( searchElement\[, fromIndex] ) + +Returns a `boolean` indicating whether an array includes a search element. + + + +```javascript +var arr = new Int32Array( [ 1, 2, 3 ] ); + +var bool = arr.includes( 3 ); +// returns true + +bool = arr.includes( 0 ); +// returns false +``` + +By default, the method searches the entire array (`fromIndex = 0`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Int32Array( [ 1, 2, 3 ] ); + +var bool = arr.includes( 1, 1 ); +// returns false +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Int32Array( [ 1, 2, 3 ] ); + +bool = arr.includes( 1, -2 ); +// returns false +``` + + + +#### Int32Array.prototype.indexOf( searchElement\[, fromIndex] ) + +Returns the index of the first array element strictly equal to a search element. + + + +```javascript +var arr = new Int32Array( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 3 ); +// returns 2 + +idx = arr.indexOf( 0 ); +// returns -1 +``` + +By default, the method searches the entire array (`fromIndex = 0`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Int32Array( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 1, 1 ); +// returns -1 +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Int32Array( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 1, -2 ); +// returns -1 +``` + + + +#### Int32Array.prototype.join( \[separator] ) + +Serializes an array by joining all array elements as a string. + + + +```javascript +var arr = new Int32Array( [ 1, 2, 3 ] ); + +var str = arr.join(); +// returns '1,2,3' +``` + +By default, the method delineates array elements using a comma `,`. To specify a custom separator, provide a `separator` string. + + + +```javascript +var arr = new Int32Array( [ 1, 2, 3 ] ); + +var str = arr.join( '|' ); +// returns '1|2|3' +``` + + + +#### Int32Array.prototype.keys() + +Returns an iterator for iterating over array keys. + + + +```javascript +var arr = new Int32Array( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.keys(); + +// Iterate over keys... +var v = it.next().value; +// returns 0 + +v = it.next().value; +// returns 1 + +var bool = it.next().done; +// returns true +``` + + + +#### Int32Array.prototype.lastIndexOf( searchElement\[, fromIndex] ) + +Returns the index of the last array element strictly equal to a search element, iterating from right to left. + + + +```javascript +var arr = new Int32Array( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0 ); +// returns 3 + +idx = arr.lastIndexOf( 3 ); +// returns -1 +``` + +By default, the method searches the entire array (`fromIndex = -1`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Int32Array( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0, 2 ); +// returns 1 +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Int32Array( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0, -3 ); +// returns 1 +``` + + + +#### Int32Array.prototype.map( fcn\[, thisArg] ) + +Maps each array element to an element in a new array having the same data type as the host array. + + + +```javascript +function fcn( v ) { + return v * 2; +} + +var arr1 = new Int32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.map( fcn ); +// returns [ 2, 4, 6 ] +``` + +A callback is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function fcn( v ) { + this.count += 1; + return v * 2; +} + +var ctx = { + 'count': 0 +}; + +var arr1 = new Int32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.map( fcn, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Int32Array.prototype.reduce( fcn\[, initialValue] ) + +Applies a function against an accumulator and each element in an array and returns the accumulated result. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Int32Array( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn ); +// returns 12 +``` + +If not provided an initial value, the method invokes a provided function with the first array element as the first argument and the second array element as the second argument. + +If provided an initial value, the method invokes a provided function with the initial value as the first argument and the first array element as the second argument. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Int32Array( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn, 0 ); +// returns 14 +``` + +A callback is provided four arguments: + +- `acc`: accumulated result +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + + + +#### Int32Array.prototype.reduceRight( fcn\[, initialValue] ) + +Applies a function against an accumulator and each element in an array and returns the accumulated result, iterating from right to left. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Int32Array( [ 2, 1, 3 ] ); + +var v = arr.reduceRight( fcn ); +// returns 8 +``` + +If not provided an initial value, the method invokes a provided function with the last array element as the first argument and the second-to-last array element as the second argument. + +If provided an initial value, the method invokes a provided function with the initial value as the first argument and the last array element as the second argument. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Int32Array( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn, 0 ); +// returns 14 +``` + +A callback is provided four arguments: + +- `acc`: accumulated result +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + + + +#### Int32Array.prototype.reverse() + +Reverses an array **in-place** (thus mutating the array on which the method is invoked). + + + +```javascript +var arr = new Int32Array( [ 2, 0, 3 ] ); + +// Reverse the array: +arr.reverse(); + +var v = arr[ 0 ]; +// returns 3 + +v = arr[ 1 ]; +// returns 0 + +v = arr[ 2 ]; +// returns 2 +``` + + + +#### Int32Array.prototype.set( arr\[, offset] ) + +Sets array elements. + + + +```javascript +var arr = new Int32Array( [ 1, 2, 3 ] ); +// returns [ 1, 2, 3 ] + +// Set the first two array elements: +arr.set( [ 4, 5 ] ); + +var v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 5 +``` + +By default, the method starts writing values at the first array index. To specify an alternative index, provide an index `offset`. + + + +```javascript +var arr = new Int32Array( [ 1, 2, 3 ] ); +// returns [ 1, 2, 3 ] + +// Set the last two array elements: +arr.set( [ 4, 5 ], 1 ); + +var v = arr[ 1 ]; +// returns 4 + +v = arr[ 2 ]; +// returns 5 +``` + + + +#### Int32Array.prototype.slice( \[begin\[, end]] ) + +Copies array elements to a new array with the same underlying data type as the host array. + + + +```javascript +var arr1 = new Int32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice(); + +var bool = ( arr1 === arr2 ); +// returns false + +bool = ( arr1.buffer === arr2.buffer ); +// returns false + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 + +v = arr2[ 2 ]; +// returns 3 +``` + +By default, the method copies elements beginning with the first array element. To specify an alternative array index at which to begin copying, provide a `begin` index (inclusive). + + + +```javascript +var arr1 = new Int32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( 1 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 2 + +v = arr2[ 1 ]; +// returns 3 +``` + +By default, the method copies all array elements after `begin`. To specify an alternative array index at which to end copying, provide an `end` index (exclusive). + + + +```javascript +var arr1 = new Int32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( 0, 2 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 +``` + +When a `begin` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr1 = new Int32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( -arr1.length, -1 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 +``` + + + +#### Int32Array.prototype.some( predicate\[, thisArg] ) + +Tests whether at least one array element passes a test implemented by a `predicate` function. + + + +```javascript +function predicate( v ) { + return ( v >= 2 ); +} + +var arr = new Int32Array( [ 1, 2 ] ); + +var bool = arr.some( predicate ); +// returns true +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Int32Array( [ 1, 1 ] ); + +var bool = arr.some( predicate, ctx ); +// returns false + +var n = ctx.count; +// returns 2 +``` + + + +#### Int32Array.prototype.sort( \[compareFunction] ) + +Sorts an array **in-place** (thus mutating the array on which the method is invoked). + + + +```javascript +var arr = new Int32Array( [ 2, 3, 0 ] ); + +// Sort the array (in ascending order): +arr.sort(); + +var v = arr[ 0 ]; +// returns 0 + +v = arr[ 1 ]; +// returns 2 + +v = arr[ 2 ]; +// returns 3 +``` + +By default, the method sorts array elements in ascending order. To impose a custom order, provide a `compareFunction`. + + + +```javascript +function descending( a, b ) { + return b - a; +} + +var arr = new Int32Array( [ 2, 3, 0 ] ); + +// Sort the array (in descending order): +arr.sort( descending ); + +var v = arr[ 0 ]; +// returns 3 + +v = arr[ 1 ]; +// returns 2 + +v = arr[ 2 ]; +// returns 0 +``` + +The comparison function is provided two array elements, `a` and `b`, per invocation, and its return value determines the sort order as follows: + +- If the comparison function returns a value **less** than zero, then the method sorts `a` to an index lower than `b` (i.e., `a` should come **before** `b`). +- If the comparison function returns a value **greater** than zero, then the method sorts `a` to an index higher than `b` (i.e., `b` should come **before** `a`). +- If the comparison function returns **zero**, then the relative order of `a` and `b` _should_ remain unchanged. + + + +#### Int32Array.prototype.subarray( \[begin\[, end]] ) + +Creates a new typed array view over the same underlying [`ArrayBuffer`][@stdlib/array/buffer] and with the same underlying data type as the host array. + + + +```javascript +var arr1 = new Int32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray(); +// returns [ 1, 2, 3 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +By default, the method creates a typed array view beginning with the first array element. To specify an alternative array index at which to begin, provide a `begin` index (inclusive). + + + +```javascript +var arr1 = new Int32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 1 ); +// returns [ 2, 3 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +By default, the method creates a typed array view which includes all array elements after `begin`. To limit the number of array elements after `begin`, provide an `end` index (exclusive). + + + +```javascript +var arr1 = new Int32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 0, 2 ); +// returns [ 1, 2 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +When a `begin` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr1 = new Int32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( -arr1.length, -1 ); +// returns [ 1, 2 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +If the method is unable to resolve indices to a non-empty array subsequence, the method returns an empty typed array. + + + +```javascript +var arr1 = new Int32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 10, -1 ); +// returns [] +``` + + + +#### Int32Array.prototype.toLocaleString( \[locales\[, options]] ) + +Serializes an array as a locale-specific `string`. + + + +```javascript +var arr = new Int32Array( [ 1, 2, 3 ] ); + +var str = arr.toLocaleString(); +// returns '1,2,3' +``` + + + +#### Int32Array.prototype.toString() + +Serializes an array as a `string`. + + + +```javascript +var arr = new Int32Array( [ 1, 2, 3 ] ); + +var str = arr.toString(); +// returns '1,2,3' +``` + + + +#### Int32Array.prototype.values() + +Returns an iterator for iterating over array elements. + + + +```javascript +var arr = new Int32Array( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.values(); + +// Iterate over array elements... +var v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 2 + +var bool = it.next().done; +// returns true +``` + +
+ + + +* * * + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var randu = require( '@stdlib/random/base/randu' ); +var round = require( '@stdlib/math/base/special/round' ); +var ctor = require( '@stdlib/array/int32' ); + +var arr; +var i; + +arr = new ctor( 10 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = round( randu()*100.0 ); +} +console.log( arr ); +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/int32/benchmark/benchmark.copy_within.js b/int32/benchmark/benchmark.copy_within.js new file mode 100644 index 00000000..3a07bc95 --- /dev/null +++ b/int32/benchmark/benchmark.copy_within.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':copyWithin', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 255; + arr[ 0 ] = v; + arr = arr.copyWithin( 1, 0 ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/benchmark/benchmark.copy_within.length.js b/int32/benchmark/benchmark.copy_within.length.js new file mode 100644 index 00000000..4216daa8 --- /dev/null +++ b/int32/benchmark/benchmark.copy_within.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 255; + arr[ 0 ] = v; + arr = arr.copyWithin( 1, 0 ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':copyWithin:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.data.js b/int32/benchmark/benchmark.data.js new file mode 100644 index 00000000..0bee1465 --- /dev/null +++ b/int32/benchmark/benchmark.data.js @@ -0,0 +1,75 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::get,index', function benchmark( b ) { + var arr; + var N; + var v; + var i; + + arr = new Int32Array( 2 ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr[ i%N ]; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::set,index', function benchmark( b ) { + var arr; + var N; + var i; + + arr = new Int32Array( 2 ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ i%N ] = i; + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] || arr[ 1 ] !== arr[ 1 ] ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/benchmark/benchmark.entries.js b/int32/benchmark/benchmark.entries.js new file mode 100644 index 00000000..a858f790 --- /dev/null +++ b/int32/benchmark/benchmark.entries.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':entries', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Int32Array( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.entries(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/benchmark/benchmark.every.js b/int32/benchmark/benchmark.every.js new file mode 100644 index 00000000..de59ee23 --- /dev/null +++ b/int32/benchmark/benchmark.every.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':every', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); + +bench( pkg+'::this_context:every', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate, {} ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); diff --git a/int32/benchmark/benchmark.every.length.js b/int32/benchmark/benchmark.every.length.js new file mode 100644 index 00000000..a6834093 --- /dev/null +++ b/int32/benchmark/benchmark.every.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value >= 0.0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':every:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.fill.js b/int32/benchmark/benchmark.fill.js new file mode 100644 index 00000000..9a4992c8 --- /dev/null +++ b/int32/benchmark/benchmark.fill.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':fill', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr = arr.fill( v ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/benchmark/benchmark.fill.length.js b/int32/benchmark/benchmark.fill.length.js new file mode 100644 index 00000000..f94e0b75 --- /dev/null +++ b/int32/benchmark/benchmark.fill.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr = arr.fill( v ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':fill:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.filter.js b/int32/benchmark/benchmark.filter.js new file mode 100644 index 00000000..8bc01e99 --- /dev/null +++ b/int32/benchmark/benchmark.filter.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt32Array = require( '@stdlib/assert/is-int32array' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':filter', function benchmark( b ) { + var arr; + var out; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt32Array( out ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); + +bench( pkg+'::this_context:filter', function benchmark( b ) { + var arr; + var out; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate, {} ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt32Array( out ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); diff --git a/int32/benchmark/benchmark.filter.length.js b/int32/benchmark/benchmark.filter.length.js new file mode 100644 index 00000000..450af284 --- /dev/null +++ b/int32/benchmark/benchmark.filter.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isInt32Array = require( '@stdlib/assert/is-int32array' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value >= 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt32Array( out ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':filter:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.find.js b/int32/benchmark/benchmark.find.js new file mode 100644 index 00000000..f37b3af4 --- /dev/null +++ b/int32/benchmark/benchmark.find.js @@ -0,0 +1,82 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':find', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int32Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:find', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int32Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate, {} ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/int32/benchmark/benchmark.find.length.js b/int32/benchmark/benchmark.find.length.js new file mode 100644 index 00000000..eff79592 --- /dev/null +++ b/int32/benchmark/benchmark.find.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - tuple length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int32Array( len ); + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':find:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.find_index.js b/int32/benchmark/benchmark.find_index.js new file mode 100644 index 00000000..7099aa08 --- /dev/null +++ b/int32/benchmark/benchmark.find_index.js @@ -0,0 +1,82 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':findIndex', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int32Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:findIndex', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int32Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate, {} ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/int32/benchmark/benchmark.find_index.length.js b/int32/benchmark/benchmark.find_index.length.js new file mode 100644 index 00000000..172815ce --- /dev/null +++ b/int32/benchmark/benchmark.find_index.length.js @@ -0,0 +1,104 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':findIndex:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.for_each.js b/int32/benchmark/benchmark.for_each.js new file mode 100644 index 00000000..08f29c70 --- /dev/null +++ b/int32/benchmark/benchmark.for_each.js @@ -0,0 +1,88 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':forEach', function benchmark( b ) { + var count; + var arr; + var N; + var i; + + arr = new Int32Array( 2 ); + N = arr.length; + + count = 0; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn ); + if ( count !== N*(i+1) ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( count !== N*i ) { + b.fail( 'unexpected result' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn() { + count += 1; + } +}); + +bench( pkg+'::this_context:forEach', function benchmark( b ) { + var count; + var arr; + var N; + var i; + + arr = new Int32Array( 2 ); + N = arr.length; + + count = 0; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn, {} ); + if ( count !== N*(i+1) ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( count !== N*i ) { + b.fail( 'unexpected result' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn() { + count += 1; + } +}); diff --git a/int32/benchmark/benchmark.for_each.length.js b/int32/benchmark/benchmark.for_each.length.js new file mode 100644 index 00000000..5cd5e5c9 --- /dev/null +++ b/int32/benchmark/benchmark.for_each.length.js @@ -0,0 +1,106 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var count; + var arr; + + arr = new Int32Array( len ); + count = 0; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn ); + if ( count !== count ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( count !== count ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } + + /** + * Callback invoked for each tuple element. + * + * @private + */ + function fcn() { + count += 1; + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':forEach:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.from.js b/int32/benchmark/benchmark.from.js new file mode 100644 index 00000000..c32f489e --- /dev/null +++ b/int32/benchmark/benchmark.from.js @@ -0,0 +1,237 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var ITERATOR_SYMBOL = require( '@stdlib/symbol/iterator' ); +var isInt32Array = require( '@stdlib/assert/is-int32array' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// VARIABLES // + +var opts = { + 'skip': ( ITERATOR_SYMBOL === null ) +}; + + +// MAIN // + +bench( pkg+'::typed_array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Int32Array( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int32Array.from( buf ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt32Array( arr ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array,clbk:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Int32Array( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int32Array.from( buf, clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt32Array( arr ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1; + } +}); + +bench( pkg+'::array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1, 2 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int32Array.from( buf ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt32Array( arr ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::array,clbk:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1, 2 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int32Array.from( buf, clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt32Array( arr ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1; + } +}); + +bench( pkg+'::iterable:from', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int32Array.from( createIterable() ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt32Array( arr ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out; + var i; + + out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + + i = 0; + + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + i += 1; + if ( i <= 2 ) { + return { + 'value': 0, + 'done': false + }; + } + return { + 'done': true + }; + } + } +}); + +bench( pkg+'::iterable,clbk:from:', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int32Array.from( createIterable(), clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt32Array( arr ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out; + var i; + + out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + + i = 0; + + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + i += 1; + if ( i <= 2 ) { + return { + 'value': 1, + 'done': false + }; + } + return { + 'done': true + }; + } + } + + function clbk( v ) { + return v + 1; + } +}); diff --git a/int32/benchmark/benchmark.includes.js b/int32/benchmark/benchmark.includes.js new file mode 100644 index 00000000..144ca93d --- /dev/null +++ b/int32/benchmark/benchmark.includes.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':includes', function benchmark( b ) { + var bool; + var arr; + var v; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + bool = arr.includes( v ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/benchmark/benchmark.includes.length.js b/int32/benchmark/benchmark.includes.length.js new file mode 100644 index 00000000..d9a6c8d4 --- /dev/null +++ b/int32/benchmark/benchmark.includes.length.js @@ -0,0 +1,96 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + bool = arr.includes( v ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':includes:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.index_of.js b/int32/benchmark/benchmark.index_of.js new file mode 100644 index 00000000..45d65f02 --- /dev/null +++ b/int32/benchmark/benchmark.index_of.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':indexOf', function benchmark( b ) { + var out; + var arr; + var v; + var i; + + arr = new Int32Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.indexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/benchmark/benchmark.index_of.length.js b/int32/benchmark/benchmark.index_of.length.js new file mode 100644 index 00000000..cdf1ca43 --- /dev/null +++ b/int32/benchmark/benchmark.index_of.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.indexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':indexOf:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.join.js b/int32/benchmark/benchmark.join.js new file mode 100644 index 00000000..d4cbe407 --- /dev/null +++ b/int32/benchmark/benchmark.join.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':join', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i % 127; + out = arr.join(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/benchmark/benchmark.join.length.js b/int32/benchmark/benchmark.join.length.js new file mode 100644 index 00000000..24ef4d7b --- /dev/null +++ b/int32/benchmark/benchmark.join.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i % 127; + out = arr.join(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':join:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.js b/int32/benchmark/benchmark.js new file mode 100644 index 00000000..9def7bbf --- /dev/null +++ b/int32/benchmark/benchmark.js @@ -0,0 +1,47 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt32Array = require( '@stdlib/assert/is-int32array' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new ctor( 0 ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isInt32Array( arr ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/benchmark/benchmark.keys.js b/int32/benchmark/benchmark.keys.js new file mode 100644 index 00000000..1b086405 --- /dev/null +++ b/int32/benchmark/benchmark.keys.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':keys', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.keys(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/benchmark/benchmark.last_index_of.js b/int32/benchmark/benchmark.last_index_of.js new file mode 100644 index 00000000..77a474e3 --- /dev/null +++ b/int32/benchmark/benchmark.last_index_of.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':lastIndexOf', function benchmark( b ) { + var out; + var arr; + var v; + var i; + + arr = new Int32Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.lastIndexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/benchmark/benchmark.last_index_of.length.js b/int32/benchmark/benchmark.last_index_of.length.js new file mode 100644 index 00000000..1d5b5ae3 --- /dev/null +++ b/int32/benchmark/benchmark.last_index_of.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.lastIndexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':lastIndexOf:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.length.js b/int32/benchmark/benchmark.length.js new file mode 100644 index 00000000..4589cca8 --- /dev/null +++ b/int32/benchmark/benchmark.length.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isInt32Array = require( '@stdlib/assert/is-int32array' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new ctor( len ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isInt32Array( arr ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.map.js b/int32/benchmark/benchmark.map.js new file mode 100644 index 00000000..49b37a12 --- /dev/null +++ b/int32/benchmark/benchmark.map.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt32Array = require( '@stdlib/assert/is-int32array' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':map', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt32Array( out ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); + +bench( pkg+'::this_context:map', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn, {} ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt32Array( out ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/int32/benchmark/benchmark.map.length.js b/int32/benchmark/benchmark.map.length.js new file mode 100644 index 00000000..56053beb --- /dev/null +++ b/int32/benchmark/benchmark.map.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isInt32Array = require( '@stdlib/assert/is-int32array' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Maps an array element to a new value. +* +* @private +* @param {*} value - array element +* @returns {*} new value +*/ +function fcn( value ) { + return value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt32Array( out ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':map:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.of.js b/int32/benchmark/benchmark.of.js new file mode 100644 index 00000000..dce80d0f --- /dev/null +++ b/int32/benchmark/benchmark.of.js @@ -0,0 +1,48 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt32Array = require( '@stdlib/assert/is-int32array' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':of', function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int32Array.of( i, 2 ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt32Array( arr ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/benchmark/benchmark.properties.js b/int32/benchmark/benchmark.properties.js new file mode 100644 index 00000000..16ed2929 --- /dev/null +++ b/int32/benchmark/benchmark.properties.js @@ -0,0 +1,145 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isArrayBuffer = require( '@stdlib/assert/is-arraybuffer' ); +var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::get:buffer', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.buffer; + if ( typeof v !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isArrayBuffer( v ) ) { + b.fail( 'should return an ArrayBuffer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteLength', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteLength; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteOffset', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteOffset; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:BYTES_PER_ELEMENT', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.BYTES_PER_ELEMENT; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:length', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.length; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/benchmark/benchmark.reduce.js b/int32/benchmark/benchmark.reduce.js new file mode 100644 index 00000000..43b87c96 --- /dev/null +++ b/int32/benchmark/benchmark.reduce.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reduce', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( acc, v ) { + return acc + v + 1; + } +}); + +bench( pkg+'::initial_value:reduce', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn, 3 ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/int32/benchmark/benchmark.reduce.length.js b/int32/benchmark/benchmark.reduce.length.js new file mode 100644 index 00000000..cc066bfc --- /dev/null +++ b/int32/benchmark/benchmark.reduce.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Updates an accumulated value. +* +* @private +* @param {*} acc - accumulated value +* @param {*} value - array element +* @returns {*} accumulated value +*/ +function fcn( acc, value ) { + return acc + value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reduce:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.reduce_right.js b/int32/benchmark/benchmark.reduce_right.js new file mode 100644 index 00000000..381181cd --- /dev/null +++ b/int32/benchmark/benchmark.reduce_right.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reduceRight', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( acc, v ) { + return acc + v + 1; + } +}); + +bench( pkg+'::initial_value:reduceRight', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn, 3 ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/int32/benchmark/benchmark.reduce_right.length.js b/int32/benchmark/benchmark.reduce_right.length.js new file mode 100644 index 00000000..941a868c --- /dev/null +++ b/int32/benchmark/benchmark.reduce_right.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Updates an accumulated value. +* +* @private +* @param {*} acc - accumulated value +* @param {*} value - array element +* @returns {*} accumulated value +*/ +function fcn( acc, value ) { + return acc + value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reduceRight:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.reverse.js b/int32/benchmark/benchmark.reverse.js new file mode 100644 index 00000000..3f9cd876 --- /dev/null +++ b/int32/benchmark/benchmark.reverse.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt32Array = require( '@stdlib/assert/is-int32array' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reverse', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.reverse(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt32Array( out ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/benchmark/benchmark.reverse.length.js b/int32/benchmark/benchmark.reverse.length.js new file mode 100644 index 00000000..6c00fb15 --- /dev/null +++ b/int32/benchmark/benchmark.reverse.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isInt32Array = require( '@stdlib/assert/is-int32array' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.reverse(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt32Array( out ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reverse:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.set.js b/int32/benchmark/benchmark.set.js new file mode 100644 index 00000000..0f1b764f --- /dev/null +++ b/int32/benchmark/benchmark.set.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::array:set', function benchmark( b ) { + var values; + var buf; + var arr; + var N; + var v; + var i; + + values = []; + for ( i = 0; i < 10; i++ ) { + values.push( i ); + } + N = values.length; + + arr = new Int32Array( 2 ); + buf = [ 0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = values[ i%N ]; + v = arr.set( buf ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array:set', function benchmark( b ) { + var values; + var buf; + var arr; + var N; + var v; + var i; + + values = new Int32Array( 20 ); + N = values.length; + for ( i = 0; i < N; i++ ) { + values[ i ] = i; + } + + arr = new Int32Array( 2 ); + buf = new Int32Array( 1 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = values[ i%N ]; + v = arr.set( buf ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/benchmark/benchmark.set.length.js b/int32/benchmark/benchmark.set.length.js new file mode 100644 index 00000000..312069ba --- /dev/null +++ b/int32/benchmark/benchmark.set.length.js @@ -0,0 +1,114 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randi = require( '@stdlib/random/base/randi' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var values; + var arr1; + var arr2; + var arr; + var N; + var i; + + arr1 = []; + arr2 = []; + for ( i = 0; i < len; i++ ) { + arr1.push( randi() ); + arr2.push( randi() ); + } + arr = new Int32Array( len ); + + values = [ + arr1, + arr2 + ]; + N = values.length; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr.set( values[ i%N ] ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':set:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.slice.js b/int32/benchmark/benchmark.slice.js new file mode 100644 index 00000000..4d68a930 --- /dev/null +++ b/int32/benchmark/benchmark.slice.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt32Array = require( '@stdlib/assert/is-int32array' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':slice', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.slice(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt32Array( out ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/benchmark/benchmark.slice.length.js b/int32/benchmark/benchmark.slice.length.js new file mode 100644 index 00000000..8ef4b3ee --- /dev/null +++ b/int32/benchmark/benchmark.slice.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isInt32Array = require( '@stdlib/assert/is-int32array' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.slice(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt32Array( out ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':slice:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.some.js b/int32/benchmark/benchmark.some.js new file mode 100644 index 00000000..a4c82f14 --- /dev/null +++ b/int32/benchmark/benchmark.some.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':some', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:some', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate, {} ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/int32/benchmark/benchmark.some.length.js b/int32/benchmark/benchmark.some.length.js new file mode 100644 index 00000000..686b1612 --- /dev/null +++ b/int32/benchmark/benchmark.some.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':some:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.sort.js b/int32/benchmark/benchmark.sort.js new file mode 100644 index 00000000..976caea0 --- /dev/null +++ b/int32/benchmark/benchmark.sort.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var randi = require( '@stdlib/random/base/randi' ); +var isInt32Array = require( '@stdlib/assert/is-int32array' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':sort', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int32Array( [ randi(), randi() ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = randi(); + out = arr.sort(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt32Array( out ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/benchmark/benchmark.sort.length.js b/int32/benchmark/benchmark.sort.length.js new file mode 100644 index 00000000..3c70f9d1 --- /dev/null +++ b/int32/benchmark/benchmark.sort.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randi = require( '@stdlib/random/base/randi' ); +var isInt32Array = require( '@stdlib/assert/is-int32array' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var data; + var arr; + var i; + + data = []; + for ( i = 0; i < len; i++ ) { + data.push( randi() ); + } + arr = new Int32Array( data ); + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ i%len ] = randi(); + out = arr.sort(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt32Array( out ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':sort:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.subarray.js b/int32/benchmark/benchmark.subarray.js new file mode 100644 index 00000000..1dbc0104 --- /dev/null +++ b/int32/benchmark/benchmark.subarray.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt32Array = require( '@stdlib/assert/is-int32array' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':subarray', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.subarray(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt32Array( out ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/benchmark/benchmark.subarray.length.js b/int32/benchmark/benchmark.subarray.length.js new file mode 100644 index 00000000..0fc2921e --- /dev/null +++ b/int32/benchmark/benchmark.subarray.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isInt32Array = require( '@stdlib/assert/is-int32array' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.subarray(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt32Array( out ) ) { + b.fail( 'should return an Int32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':subarray:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.to_locale_string.js b/int32/benchmark/benchmark.to_locale_string.js new file mode 100644 index 00000000..32c7d394 --- /dev/null +++ b/int32/benchmark/benchmark.to_locale_string.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':toLocaleString', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toLocaleString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/benchmark/benchmark.to_locale_string.length.js b/int32/benchmark/benchmark.to_locale_string.length.js new file mode 100644 index 00000000..ec49e474 --- /dev/null +++ b/int32/benchmark/benchmark.to_locale_string.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toLocaleString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':toLocaleString:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.to_string.js b/int32/benchmark/benchmark.to_string.js new file mode 100644 index 00000000..f5fa1e9f --- /dev/null +++ b/int32/benchmark/benchmark.to_string.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':toString', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/benchmark/benchmark.to_string.length.js b/int32/benchmark/benchmark.to_string.length.js new file mode 100644 index 00000000..b679840b --- /dev/null +++ b/int32/benchmark/benchmark.to_string.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':toString:len='+len, f ); + } +} + +main(); diff --git a/int32/benchmark/benchmark.values.js b/int32/benchmark/benchmark.values.js new file mode 100644 index 00000000..8132a04c --- /dev/null +++ b/int32/benchmark/benchmark.values.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':values', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Int32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.values(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int32/docs/repl.txt b/int32/docs/repl.txt new file mode 100644 index 00000000..915c3e96 --- /dev/null +++ b/int32/docs/repl.txt @@ -0,0 +1,953 @@ + +{{alias}}() + A typed array constructor which returns a typed array representing an array + of twos-complement 32-bit signed integers in the platform byte order. + + Returns + ------- + out: Int32Array + A typed array. + + Examples + -------- + > var arr = new {{alias}}() + + + +{{alias}}( length ) + Returns a typed array having a specified length. + + Parameters + ---------- + length: integer + Typed array length. + + Returns + ------- + out: Int32Array + A typed array. + + Examples + -------- + > var arr = new {{alias}}( 5 ) + [ 0, 0, 0, 0, 0 ] + + +{{alias}}( typedarray ) + Creates a typed array from another typed array. + + Parameters + ---------- + typedarray: TypedArray + Typed array from which to generate another typed array. + + Returns + ------- + out: Int32Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias:@stdlib/array/int16}}( [ 5, 5, 5 ] ); + > var arr2 = new {{alias}}( arr1 ) + [ 5, 5, 5 ] + + +{{alias}}( obj ) + Creates a typed array from an array-like object or iterable. + + Parameters + ---------- + obj: Object + Array-like object or iterable from which to generate a typed array. + + Returns + ------- + out: Int32Array + A typed array. + + Examples + -------- + > var arr1 = [ 5.0, 5.0, 5.0 ]; + > var arr2 = new {{alias}}( arr1 ) + [ 5, 5, 5 ] + + +{{alias}}( buffer[, byteOffset[, length]] ) + Returns a typed array view of an ArrayBuffer. + + Parameters + ---------- + buffer: ArrayBuffer + Underlying ArrayBuffer. + + byteOffset: integer (optional) + Integer byte offset specifying the location of the first typed array + element. Default: 0. + + length: integer (optional) + View length. If not provided, the view spans from the byteOffset to + the end of the underlying ArrayBuffer. + + Returns + ------- + out: Int32Array + A typed array. + + Examples + -------- + > var buf = new {{alias:@stdlib/array/buffer}}( 16 ); + > var arr = new {{alias}}( buf, 0, 4 ) + [ 0, 0, 0, 0 ] + + +{{alias}}.from( src[, map[, thisArg]] ) + Creates a new typed array from an array-like object or an iterable. + + A callback is provided the following arguments: + + - value: source value. + - index: source index. + + Parameters + ---------- + src: ArrayLike|Iterable + Source of array elements. + + map: Function (optional) + Callback to invoke for each source element. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Int32Array + A typed array. + + Examples + -------- + > function mapFcn( v ) { return v * 2; }; + > var arr = {{alias}}.from( [ 1, 2 ], mapFcn ) + [ 2, 4 ] + + +{{alias}}.of( element0[, element1[, ...elementN]] ) + Creates a new typed array from a variable number of arguments. + + Parameters + ---------- + element0: number + Array element. + + element1: number (optional) + Array element. + + elementN: number (optional) + Array elements. + + Returns + ------- + out: Int32Array + A typed array. + + Examples + -------- + > var arr = {{alias}}.of( 1, 2 ) + [ 1, 2 ] + + +{{alias}}.BYTES_PER_ELEMENT + Number of bytes per view element. + + Examples + -------- + > {{alias}}.BYTES_PER_ELEMENT + 4 + + +{{alias}}.name + Typed array constructor name. + + Examples + -------- + > {{alias}}.name + 'Int32Array' + + +{{alias}}.prototype.buffer + Read-only property which returns the ArrayBuffer referenced by the typed + array. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.buffer + + + +{{alias}}.prototype.byteLength + Read-only property which returns the length (in bytes) of the typed array. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.byteLength + 20 + + +{{alias}}.prototype.byteOffset + Read-only property which returns the offset (in bytes) of the typed array + from the start of its ArrayBuffer. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.byteOffset + 0 + + +{{alias}}.prototype.BYTES_PER_ELEMENT + Number of bytes per view element. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.BYTES_PER_ELEMENT + 4 + + +{{alias}}.prototype.length + Read-only property which returns the number of view elements. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.length + 5 + + +{{alias}}.prototype.copyWithin( target, start[, end] ) + Copies a sequence of elements within the array starting at `start` and + ending at `end` (non-inclusive) to the position starting at `target`. + + Parameters + ---------- + target: integer + Target start index position. + + start: integer + Source start index position. + + end: integer (optional) + Source end index position. Default: out.length. + + Returns + ------- + out: Int32Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3, 4, 5 ] ); + > arr.copyWithin( 3, 0, 2 ); + > arr[ 3 ] + 1 + > arr[ 4 ] + 2 + + +{{alias}}.prototype.entries() + Returns an iterator for iterating over array key-value pairs. + + Returns + ------- + iter: Iterator + Iterator for iterating over array key-value pairs. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.entries(); + > it.next().value + [ 0, 1 ] + > it.next().value + [ 1, 2 ] + > it.next().done + true + + +{{alias}}.prototype.every( predicate[, thisArg] ) + Tests whether all array elements pass a test implemented by a predicate + function. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. If a predicate function + returns a truthy value, an array element passes; otherwise, an array + element fails. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + bool: boolean + Boolean indicating whether all array elements pass. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > function predicate( v ) { return ( v <= 1 ); }; + > arr.every( predicate ) + false + + +{{alias}}.prototype.fill( value[, start[, end]] ) + Fills an array from a start index to an end index (non-inclusive) with a + provided value. + + Parameters + ---------- + value: number + Fill value. + + start: integer (optional) + Start index. If less than zero, the start index is resolved relative to + the last array element. Default: 0. + + end: integer (optional) + End index (non-inclusive). If less than zero, the end index is resolved + relative to the last array element. Default: out.length. + + Returns + ------- + out: Int32Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > arr.fill( 3 ); + > arr[ 0 ] + 3 + > arr[ 1 ] + 3 + + +{{alias}}.prototype.filter( predicate[, thisArg] ) + Creates a new array which includes those elements for which a predicate + function returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + The returned array has the same data type as the host array. + + If a predicate function does not return a truthy value for any array + element, the method returns `null`. + + Parameters + ---------- + predicate: Function + Predicate function which filters array elements. If a predicate function + returns a truthy value, an array element is included in the output + array; otherwise, an array element is not included in the output array. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Int32Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 1 ); }; + > var arr2 = arr1.filter( predicate ); + > arr2.length + 2 + + +{{alias}}.prototype.find( predicate[, thisArg] ) + Returns the first array element for which a provided predicate function + returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + If a predicate function never returns a truthy value, the method returns + `undefined`. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + value: number|undefined + Array element. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 2 ); }; + > var v = arr.find( predicate ) + 3 + + +{{alias}}.prototype.findIndex( predicate[, thisArg] ) + Returns the index of the first array element for which a provided predicate + function returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + If a predicate function never returns a truthy value, the method returns + `-1`. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + idx: integer + Array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 2 ); }; + > var idx = arr.findIndex( predicate ) + 2 + + +{{alias}}.prototype.forEach( fcn[, thisArg] ) + Invokes a callback for each array element. + + A provided function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + fcn: Function + Function to invoke for each array element. + + thisArg: Any (optional) + Callback execution context. + + Examples + -------- + > var arr = new {{alias}}( [ 3, 2, 1 ] ); + > var str = ' '; + > function fcn( v, i ) { str += i + ':' + v + ' '; }; + > arr.forEach( fcn ); + > str + ' 0:3 1:2 2:1 ' + + +{{alias}}.prototype.includes( searchElement[, fromIndex] ) + Returns a boolean indicating whether an array includes a search element. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: 0. + + Returns + ------- + bool: boolean + Boolean indicating whether an array includes a search element. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > var bool = arr.includes( 4 ) + false + > bool = arr.includes( 3 ) + true + + +{{alias}}.prototype.indexOf( searchElement[, fromIndex] ) + Returns the index of the first array element strictly equal to a search + element. + + If unable to locate a search element, the method returns `-1`. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: 0. + + Returns + ------- + idx: integer + Array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > var idx = arr.indexOf( 4 ) + -1 + > idx = arr.indexOf( 3 ) + 2 + + +{{alias}}.prototype.join( [separator] ) + Serializes an array by joining all array elements as a string. + + Parameters + ---------- + separator: string (optional) + String delineating array elements. Default: ','. + + Returns + ------- + str: string + Array serialized as a string. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.join( '|' ) + '1|2|3' + + +{{alias}}.prototype.keys() + Returns an iterator for iterating over array keys. + + Returns + ------- + iter: Iterator + Iterator for iterating over array keys. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.keys(); + > it.next().value + 0 + > it.next().value + 1 + > it.next().done + true + + +{{alias}}.prototype.lastIndexOf( searchElement[, fromIndex] ) + Returns the index of the last array element strictly equal to a search + element. + + The method iterates from the last array element to the first array element. + + If unable to locate a search element, the method returns `-1`. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: -1. + + Returns + ------- + idx: integer + array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 0, 2, 0, 1 ] ); + > var idx = arr.lastIndexOf( 3 ) + -1 + > idx = arr.lastIndexOf( 0 ) + 3 + + +{{alias}}.prototype.map( fcn[, thisArg] ) + Maps each array element to an element in a new typed array. + + A provided function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + The returned array has the same data type as the host array. + + Parameters + ---------- + fcn: Function + Function which maps array elements to elements in the new array. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Int32Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( v ) { return v * 2; }; + > var arr2 = arr1.map( fcn ); + [ 2, 4, 6 ] + + +{{alias}}.prototype.reduce( fcn[, initialValue] ) + Applies a function against an accumulator and each element in an array and + returns the accumulated result. + + The provided function is provided the following arguments: + + - acc: accumulated result. + - value: current array element. + - index: index of the current array element. + - arr: array on which the method is invoked. + + If provided an initial value, the method invokes a provided function with + the initial value as the first argument and the first array element as the + second argument. + + If not provided an initial value, the method invokes a provided function + with the first array element as the first argument and the second array + element as the second argument. + + Parameters + ---------- + fcn: Function + Function to apply. + + initialValue: Any (optional) + Initial accumulation value. + + Returns + ------- + out: Any + Accumulated result. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( acc, v ) { return acc + (v*v); }; + > var v = arr.reduce( fcn, 0 ) + 14 + + +{{alias}}.prototype.reduceRight( fcn[, initialValue] ) + Applies a function against an accumulator and each element in an array and + returns the accumulated result, iterating from right to left. + + The provided function is provided the following arguments: + + - acc: accumulated result. + - value: current array element. + - index: index of the current array element. + - arr: array on which the method is invoked. + + If provided an initial value, the method invokes a provided function with + the initial value as the first argument and the last array element as the + second argument. + + If not provided an initial value, the method invokes a provided function + with the last array element as the first argument and the second-to-last + array element as the second argument. + + Parameters + ---------- + fcn: Function + Function to apply. + + initialValue: Any (optional) + Initial accumulation value. + + Returns + ------- + out: Any + Accumulated result. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( acc, v ) { return acc + (v*v); }; + > var v = arr.reduceRight( fcn, 0 ) + 14 + + +{{alias}}.prototype.reverse() + Reverses an array *in-place*. + + This method mutates the array on which the method is invoked. + + Returns + ------- + out: Int32Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ) + [ 1, 2, 3 ] + > arr.reverse() + [ 3, 2, 1 ] + + +{{alias}}.prototype.set( arr[, offset] ) + Sets array elements. + + Parameters + ---------- + arr: ArrayLike + Source array containing array values to set. + + offset: integer (optional) + Array index at which to start writing values. Default: 0. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.set( [ 4, 4 ], 1 ); + > arr[ 1 ] + 4 + > arr[ 2 ] + 4 + + +{{alias}}.prototype.slice( [begin[, end]] ) + Copies array elements to a new array with the same underlying data type as + the host array. + + If the method is unable to resolve indices to a non-empty array subsequence, + the method returns `null`. + + Parameters + ---------- + begin: integer (optional) + Start element index (inclusive). If less than zero, the start index is + resolved relative to the last array element. Default: 0. + + end: integer (optional) + End element index (exclusive). If less than zero, the end index is + resolved relative to the last array element. Default: arr.length. + + Returns + ------- + out: Int32Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > var arr2 = arr1.slice( 1 ); + > arr2.length + 2 + > arr2[ 0 ] + 1 + > arr2[ 1 ] + 2 + + +{{alias}}.prototype.some( predicate[, thisArg] ) + Tests whether at least one array element passes a test implemented by a + predicate function. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. If a predicate function + returns a truthy value, a array element passes; otherwise, an array + element fails. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + bool: boolean + Boolean indicating whether at least one array element passes. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > function predicate( v ) { return ( v > 1 ); }; + > arr.some( predicate ) + true + + +{{alias}}.prototype.sort( [compareFunction] ) + Sorts an array *in-place*. + + The comparison function is provided two array elements per invocation: `a` + and `b`. + + The comparison function return value determines the sort order as follows: + + - If the comparison function returns a value less than zero, then the method + sorts `a` to an index lower than `b` (i.e., `a` should come *before* `b`). + + - If the comparison function returns a value greater than zero, then the + method sorts `a` to an index higher than `b` (i.e., `b` should come *before* + `a`). + + - If the comparison function returns zero, then the relative order of `a` + and `b` should remain unchanged. + + This method mutates the array on which the method is invoked. + + Parameters + ---------- + compareFunction: Function (optional) + Function which specifies the sort order. The default sort order is + ascending order. + + Returns + ------- + out: Int32Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 0, 2, 1 ] ); + > arr.sort() + [ 0, 1, 1, 2, 2 ] + + +{{alias}}.prototype.subarray( [begin[, end]] ) + Creates a new typed array over the same underlying ArrayBuffer and with the + same underlying data type as the host array. + + If the method is unable to resolve indices to a non-empty array subsequence, + the method returns an empty typed array. + + Parameters + ---------- + begin: integer (optional) + Start element index (inclusive). If less than zero, the start index is + resolved relative to the last array element. Default: 0. + + end: integer (optional) + End element index (exclusive). If less than zero, the end index is + resolved relative to the last array element. Default: arr.length. + + Returns + ------- + out: Int32Array + A new typed array view. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3, 4, 5 ] ); + > var arr2 = arr1.subarray( 2 ) + [ 3, 4, 5 ] + + +{{alias}}.prototype.toLocaleString( [locales[, options]] ) + Serializes an array as a locale-specific string. + + Parameters + ---------- + locales: string|Array (optional) + A BCP 47 language tag, or an array of such tags. + + options: Object (optional) + Options. + + Returns + ------- + str: string + A typed array string representation. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.toLocaleString() + '1,2,3' + + +{{alias}}.prototype.toString() + Serializes an array as a string. + + Returns + ------- + str: string + A typed array string representation. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.toString() + '1,2,3' + + +{{alias}}.prototype.values() + Returns an iterator for iterating over array elements. + + Returns + ------- + iter: Iterator + Iterator for iterating over array elements. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.values(); + > it.next().value + 1 + > it.next().value + 2 + > it.next().done + true + + + See Also + -------- + diff --git a/int32/docs/types/index.d.ts b/int32/docs/types/index.d.ts new file mode 100644 index 00000000..71457b03 --- /dev/null +++ b/int32/docs/types/index.d.ts @@ -0,0 +1,26 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +// EXPORTS // + +/** +* Typed array constructor which returns a typed array representing an array of twos-complement 32-bit signed integers in the platform byte order. +*/ +export = Int32Array; diff --git a/int32/docs/types/test.ts b/int32/docs/types/test.ts new file mode 100644 index 00000000..1fef04d1 --- /dev/null +++ b/int32/docs/types/test.ts @@ -0,0 +1,37 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// tslint:disable: no-construct +// tslint:disable: no-unused-expression + +import Int32Array = require( './index' ); + + +// TESTS // + +// The function returns a typed array instance... +{ + new Int32Array( 10 ); // $ExpectType Int32Array + new Int32Array( [ 2, 5, 5, 7 ] ); // $ExpectType Int32Array +} + +// The constructor function has to be invoked with `new`... +{ + Int32Array( 10 ); // $ExpectError + Int32Array( [ 2, 5, 5, 7 ] ); // $ExpectError +} diff --git a/int32/examples/index.js b/int32/examples/index.js new file mode 100644 index 00000000..d0978bec --- /dev/null +++ b/int32/examples/index.js @@ -0,0 +1,32 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var randu = require( '@stdlib/random/base/randu' ); +var round = require( '@stdlib/math/base/special/round' ); +var ctor = require( './../lib' ); + +var arr; +var i; + +arr = new ctor( 10 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = round( randu()*100.0 ); +} +console.log( arr ); diff --git a/int32/lib/index.js b/int32/lib/index.js new file mode 100644 index 00000000..221c0507 --- /dev/null +++ b/int32/lib/index.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Typed array constructor which returns a typed array representing an array of twos-complement 32-bit signed integers in the platform byte order. +* +* @module @stdlib/array/int32 +* +* @example +* var ctor = require( '@stdlib/array/int32' ); +* +* var arr = new ctor( 10 ); +* // returns +*/ + +// MODULES // + +var hasInt32ArraySupport = require( '@stdlib/assert/has-int32array-support' ); +var builtin = require( './int32array.js' ); +var polyfill = require( './polyfill.js' ); + + +// MAIN // + +var ctor; +if ( hasInt32ArraySupport() ) { + ctor = builtin; +} else { + ctor = polyfill; +} + + +// EXPORTS // + +module.exports = ctor; diff --git a/int32/lib/int32array.js b/int32/lib/int32array.js new file mode 100644 index 00000000..4961b03e --- /dev/null +++ b/int32/lib/int32array.js @@ -0,0 +1,28 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MAIN // + +var ctor = ( typeof Int32Array === 'function' ) ? Int32Array : void 0; // eslint-disable-line stdlib/require-globals + + +// EXPORTS // + +module.exports = ctor; diff --git a/int32/lib/polyfill.js b/int32/lib/polyfill.js new file mode 100644 index 00000000..36b07a65 --- /dev/null +++ b/int32/lib/polyfill.js @@ -0,0 +1,37 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// TODO: write polyfill + +// MAIN // + +/** +* Typed array which represents an array of twos-complement 32-bit signed integers in the platform byte order. +* +* @throws {Error} not implemented +*/ +function polyfill() { + throw new Error( 'not implemented' ); +} + + +// EXPORTS // + +module.exports = polyfill; diff --git a/int32/package.json b/int32/package.json new file mode 100644 index 00000000..23dfacc1 --- /dev/null +++ b/int32/package.json @@ -0,0 +1,69 @@ +{ + "name": "@stdlib/array/int32", + "version": "0.0.0", + "description": "Int32Array.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structure", + "array", + "typed", + "typed array", + "typed-array", + "int32array", + "int32", + "int32_t", + "integer", + "int", + "signed", + "long" + ] +} diff --git a/int32/test/test.copy_within.js b/int32/test/test.copy_within.js new file mode 100644 index 00000000..4e137ffb --- /dev/null +++ b/int32/test/test.copy_within.js @@ -0,0 +1,320 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var hasProp = require( '@stdlib/assert/has-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var Int32Array = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof Int32Array, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'a typed array instance has a `copyWithin` method for copying a sequence of elements within a typed array', function test( t ) { + var arr = new Int32Array( 2 ); + t.strictEqual( hasProp( arr, 'copyWithin' ), true, 'has property' ); + t.strictEqual( isFunction( arr.copyWithin ), true, 'has method' ); + t.end(); +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a typed array instance', function test( t ) { + var values; + var arr; + var i; + + arr = new Int32Array( 2 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0 ); + }; + } +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a typed array instance (end)', function test( t ) { + var values; + var arr; + var i; + + arr = new Int32Array( 2 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0, 5 ); + }; + } +}); + +tape( 'the method copies a sequence of elements within a typed array', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int32Array( arr ); + p.copyWithin( 0, 3 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative target)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int32Array( arr ); + p.copyWithin( -p.length, 3 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative start)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int32Array( arr ); + p.copyWithin( 0, -2 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (end=length)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int32Array( arr ); + p.copyWithin( 0, 3, p.length ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (non-inclusive end)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int32Array( arr ); + p.copyWithin( 2, 0, 2 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative end)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int32Array( arr ); + p.copyWithin( 2, 0, -3 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (target >= length)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int32Array( arr ); + p.copyWithin( p.length, 3 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (target > start)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int32Array( arr ); + p.copyWithin( 2, 0 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + t.strictEqual( p[ 4 ], 2, 'returns expected value' ); + + t.end(); +}); diff --git a/int32/test/test.js b/int32/test/test.js new file mode 100644 index 00000000..2b225f2a --- /dev/null +++ b/int32/test/test.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var hasInt32ArraySupport = require( '@stdlib/assert/has-int32array-support' ); +var polyfill = require( './../lib/polyfill.js' ); +var ctor = require( './../lib' ); + + +// VARIABLES // + +var hasInt32Arrays = hasInt32ArraySupport(); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'if an environment supports `Int32Array`, the export is an alias for `Int32Array`', function test( t ) { + var Foo; + + Foo = proxyquire( './../lib', { + '@stdlib/assert/has-int32array-support': isTrue, + './int32array.js': Mock + }); + t.strictEqual( Foo, Mock, 'returns builtin' ); + + if ( hasInt32Arrays ) { + t.strictEqual( ctor, Int32Array, 'is alias' ); // eslint-disable-line stdlib/require-globals + } + + t.end(); + + function Mock() { + return this; + } + + function isTrue() { + return true; + } +}); + +tape( 'if an environment does not support `Int32Array`, the export is a polyfill', function test( t ) { + var Foo; + + Foo = proxyquire( './../lib', { + '@stdlib/assert/has-int32array-support': isFalse + }); + + t.strictEqual( Foo, polyfill, 'returns polyfill' ); + t.end(); + + function isFalse() { + return false; + } +}); diff --git a/int32/test/test.polyfill.js b/int32/test/test.polyfill.js new file mode 100644 index 00000000..9d6fcb19 --- /dev/null +++ b/int32/test/test.polyfill.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var ctor = require( './../lib/polyfill.js' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error when invoked', function test( t ) { + t.throws( foo, Error, 'throws an error' ); + t.end(); + + function foo() { + var f = new ctor(); // eslint-disable-line no-unused-vars + } +}); + +// TODO: tests diff --git a/int8/README.md b/int8/README.md new file mode 100644 index 00000000..066e2af5 --- /dev/null +++ b/int8/README.md @@ -0,0 +1,1431 @@ + + +# Int8Array + +> [Typed array][mdn-typed-array] constructor which returns a [typed array][mdn-typed-array] representing an array of twos-complement 8-bit signed integers in the platform byte order. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var Int8Array = require( '@stdlib/array/int8' ); +``` + +#### Int8Array() + +A [typed array][mdn-typed-array] constructor which returns a [typed array][mdn-typed-array] representing an array of twos-complement 8-bit signed integers in the platform byte order. + + + +```javascript +var arr = new Int8Array(); +// returns +``` + +#### Int8Array( length ) + +Returns a [typed array][mdn-typed-array] having a specified length. + + + +```javascript +var arr = new Int8Array( 5 ); +// returns [ 0, 0, 0, 0, 0 ] +``` + +#### Int8Array( typedarray ) + +Creates a [typed array][mdn-typed-array] from another [typed array][mdn-typed-array]. + + + +```javascript +var Float32Array = require( '@stdlib/array/float32' ); + +var arr1 = new Float32Array( [ 5.0, 5.0, 5.0 ] ); +var arr2 = new Int8Array( arr1 ); +// returns [ 5, 5, 5 ] +``` + +#### Int8Array( obj ) + +Creates a [typed array][mdn-typed-array] from an array-like `object` or iterable. + + + +```javascript +var arr = new Int8Array( [ 5.0, 5.0, 5.0 ] ); +// returns [ 5, 5, 5 ] +``` + +#### Int8Array( buffer\[, byteOffset\[, length]] ) + +Returns a [typed array][mdn-typed-array] view of an [`ArrayBuffer`][@stdlib/array/buffer]. + + + +```javascript +var ArrayBuffer = require( '@stdlib/array/buffer' ); + +var buf = new ArrayBuffer( 4 ); +var arr = new Int8Array( buf, 0, 4 ); +// returns [ 0, 0, 0, 0 ] +``` + +* * * + +### Properties + + + +#### Int8Array.BYTES_PER_ELEMENT + +Number of bytes per view element. + + + +```javascript +var nbytes = Int8Array.BYTES_PER_ELEMENT; +// returns 1 +``` + + + +#### Int8Array.name + +[Typed array][mdn-typed-array] constructor name. + + + +```javascript +var str = Int8Array.name; +// returns 'Int8Array' +``` + + + +#### Int8Array.prototype.buffer + +**Read-only** property which returns the [`ArrayBuffer`][@stdlib/array/buffer] referenced by the [typed array][mdn-typed-array]. + + + +```javascript +var arr = new Int8Array( 5 ); +var buf = arr.buffer; +// returns +``` + + + +#### Int8Array.prototype.byteLength + +**Read-only** property which returns the length (in bytes) of the [typed array][mdn-typed-array]. + + + +```javascript +var arr = new Int8Array( 5 ); +var byteLength = arr.byteLength; +// returns 5 +``` + + + +#### Int8Array.prototype.byteOffset + +**Read-only** property which returns the offset (in bytes) of the [typed array][mdn-typed-array] from the start of its [`ArrayBuffer`][@stdlib/array/buffer]. + + + +```javascript +var arr = new Int8Array( 5 ); +var byteOffset = arr.byteOffset; +// returns 0 +``` + + + +#### Int8Array.prototype.BYTES_PER_ELEMENT + +Number of bytes per view element. + + + +```javascript +var arr = new Int8Array( 5 ); +var nbytes = arr.BYTES_PER_ELEMENT; +// returns 1 +``` + + + +#### Int8Array.prototype.length + +**Read-only** property which returns the number of view elements. + + + +```javascript +var arr = new Int8Array( 5 ); +var len = arr.length; +// returns 5 +``` + +* * * + +### Methods + + + +#### Int8Array.from( src\[, map\[, thisArg]] ) + +Creates a new typed array from an array-like `object` or an iterable. + +```javascript +var arr = Int8Array.from( [ 1, 2 ] ); +// returns [ 1, 2 ] +``` + +To invoke a function for each `src` value, provide a callback function. + +```javascript +function mapFcn( v ) { + return v * 2; +} + +var arr = Int8Array.from( [ 1, 2 ], mapFcn ); +// returns [ 2, 4 ] +``` + +A callback function is provided two arguments: + +- `value`: source value +- `index`: source index + +To set the callback execution context, provide a `thisArg`. + +```javascript +function mapFcn( v ) { + this.count += 1; + return v * 2; +} + +var ctx = { + 'count': 0 +}; + +var arr = Int8Array.from( [ 1, 2 ], mapFcn, ctx ); +// returns [ 2, 4 ] + +var n = ctx.count; +// returns 2 +``` + + + +#### Int8Array.of( element0\[, element1\[, ...elementN]] ) + +Creates a new typed array from a variable number of arguments. + +```javascript +var arr = Int8Array.of( 1, 2 ); +// returns [ 1, 2 ] +``` + + + +#### Int8Array.prototype.copyWithin( target, start\[, end] ) + +Copies a sequence of elements within an array starting at `start` and ending at `end` (non-inclusive) to the position starting at `target`. + + + +```javascript +var arr = new Int8Array( [ 1, 2, 3, 4, 5 ] ); + +// Copy the last two elements to the first two elements: +arr.copyWithin( 0, 3 ); + +var v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 5 +``` + +By default, `end` equals the number of array elements (i.e., one more than the last array index). To limit the sequence length, provide an `end` argument. + + + +```javascript +var arr = new Int8Array( [ 1, 2, 3, 4, 5 ] ); + +// Copy the first two elements to the last two elements: +arr.copyWithin( 3, 0, 2 ); + +var v = arr[ 3 ]; +// returns 1 + +v = arr[ 4 ]; +// returns 2 +``` + +When a `target`, `start`, and/or `end` index is negative, the respective index is determined relative to the last array element. The following example achieves the same behavior as the previous example: + + + +```javascript +var arr = new Int8Array( [ 1, 2, 3, 4, 5 ] ); + +// Copy the first two elements to the last two elements: +arr.copyWithin( -2, -5, -3 ); + +var v = arr[ 3 ]; +// returns 1 + +v = arr[ 4 ]; +// returns 2 +``` + + + +#### Int8Array.prototype.entries() + +Returns an iterator for iterating over array key-value pairs. + + + +```javascript +var arr = new Int8Array( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.entries(); + +// Iterate over key-value pairs... +var v = it.next().value; +// returns [ 0, 1 ] + +v = it.next().value; +// returns [ 1, 2 ] + +var bool = it.next().done; +// returns true +``` + + + +#### Int8Array.prototype.every( predicate\[, thisArg] ) + +Tests whether all array elements pass a test implemented by a `predicate` function. + + + +```javascript +function predicate( v ) { + return ( v <= 1 ); +} + +var arr = new Int8Array( [ 1, 2 ] ); + +var bool = arr.every( predicate ); +// returns false +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 1 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Int8Array( [ 1, 2 ] ); + +var bool = arr.every( predicate, ctx ); +// returns true + +var n = ctx.count; +// returns 2 +``` + + + +#### Int8Array.prototype.fill( value\[, start\[, end]] ) + +Fills an array from a `start` index to an `end` index (non-inclusive) with a provided `value`. + + + +```javascript +var arr = new Int8Array( 2 ); + +// Set all array elements to the same value: +arr.fill( 2 ); + +var v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 2 + +// Set all array elements starting from the first index to the same value: +arr.fill( 3, 1 ); + +v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 3 + +// Set all array elements, except the last element, to the same value: +arr.fill( 4, 0, arr.length-1 ); + +v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 3 +``` + +When a `start` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr = new Int8Array( 2 ); + +// Set all array elements, except the last element, to the same value: +arr.fill( 2, -arr.length, -1 ); + +var v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 0 +``` + + + +#### Int8Array.prototype.filter( predicate\[, thisArg] ) + +Creates a new array (of the same data type as the host array) which includes those elements for which a `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v >= 2 ); +} + +var arr1 = new Int8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate ); +// returns [ 2, 3 ] +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns an empty array. + + + +```javascript +function predicate( v ) { + return ( v >= 10 ); +} + +var arr1 = new Int8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate ); +// returns [] +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr1 = new Int8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Int8Array.prototype.find( predicate\[, thisArg] ) + +Returns the first array element for which a provided `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v > 2 ); +} + +var arr = new Int8Array( [ 1, 2, 3 ] ); + +var v = arr.find( predicate ); +// returns 3 +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns `undefined`. + + + +```javascript +function predicate( v ) { + return ( v < 1 ); +} + +var arr = new Int8Array( [ 1, 2, 3 ] ); + +var v = arr.find( predicate ); +// returns undefined +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v > 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Int8Array( [ 1, 2, 3 ] ); + +var v = arr.find( predicate, ctx ); +// returns 3 + +var n = ctx.count; +// returns 3 +``` + + + +#### Int8Array.prototype.findIndex( predicate\[, thisArg] ) + +Returns the index of the first array element for which a provided `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v >= 3 ); +} + +var arr = new Int8Array( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate ); +// returns 2 +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns `-1`. + + + +```javascript +function predicate( v ) { + return ( v < 1 ); +} + +var arr = new Int8Array( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate ); +// returns -1 +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 3 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Int8Array( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate, ctx ); +// returns 2 + +var n = ctx.count; +// returns 3 +``` + + + +#### Int8Array.prototype.forEach( fcn\[, thisArg] ) + +Invokes a callback for each array element. + + + +```javascript +var arr = new Int8Array( [ 1, 2, 3 ] ); + +var str = ''; + +function fcn( v, i ) { + str += i + ':' + v; + if ( i < arr.length-1 ) { + str += ' '; + } +} + +arr.forEach( fcn ); + +console.log( str ); +// => '0:1 1:2 2:3' +``` + +The callback is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function fcn() { + this.count += 1; +} + +var ctx = { + 'count': 0 +}; + +var arr = new Int8Array( [ 1, 2, 3 ] ); + +arr.forEach( fcn, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Int8Array.prototype.includes( searchElement\[, fromIndex] ) + +Returns a `boolean` indicating whether an array includes a search element. + + + +```javascript +var arr = new Int8Array( [ 1, 2, 3 ] ); + +var bool = arr.includes( 3 ); +// returns true + +bool = arr.includes( 0 ); +// returns false +``` + +By default, the method searches the entire array (`fromIndex = 0`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Int8Array( [ 1, 2, 3 ] ); + +var bool = arr.includes( 1, 1 ); +// returns false +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Int8Array( [ 1, 2, 3 ] ); + +bool = arr.includes( 1, -2 ); +// returns false +``` + + + +#### Int8Array.prototype.indexOf( searchElement\[, fromIndex] ) + +Returns the index of the first array element strictly equal to a search element. + + + +```javascript +var arr = new Int8Array( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 3 ); +// returns 2 + +idx = arr.indexOf( 0 ); +// returns -1 +``` + +By default, the method searches the entire array (`fromIndex = 0`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Int8Array( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 1, 1 ); +// returns -1 +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Int8Array( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 1, -2 ); +// returns -1 +``` + + + +#### Int8Array.prototype.join( \[separator] ) + +Serializes an array by joining all array elements as a string. + + + +```javascript +var arr = new Int8Array( [ 1, 2, 3 ] ); + +var str = arr.join(); +// returns '1,2,3' +``` + +By default, the method delineates array elements using a comma `,`. To specify a custom separator, provide a `separator` string. + + + +```javascript +var arr = new Int8Array( [ 1, 2, 3 ] ); + +var str = arr.join( '|' ); +// returns '1|2|3' +``` + + + +#### Int8Array.prototype.keys() + +Returns an iterator for iterating over array keys. + + + +```javascript +var arr = new Int8Array( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.keys(); + +// Iterate over keys... +var v = it.next().value; +// returns 0 + +v = it.next().value; +// returns 1 + +var bool = it.next().done; +// returns true +``` + + + +#### Int8Array.prototype.lastIndexOf( searchElement\[, fromIndex] ) + +Returns the index of the last array element strictly equal to a search element, iterating from right to left. + + + +```javascript +var arr = new Int8Array( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0 ); +// returns 3 + +idx = arr.lastIndexOf( 3 ); +// returns -1 +``` + +By default, the method searches the entire array (`fromIndex = -1`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Int8Array( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0, 2 ); +// returns 1 +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Int8Array( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0, -3 ); +// returns 1 +``` + + + +#### Int8Array.prototype.map( fcn\[, thisArg] ) + +Maps each array element to an element in a new array having the same data type as the host array. + + + +```javascript +function fcn( v ) { + return v * 2; +} + +var arr1 = new Int8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.map( fcn ); +// returns [ 2, 4, 6 ] +``` + +A callback is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function fcn( v ) { + this.count += 1; + return v * 2; +} + +var ctx = { + 'count': 0 +}; + +var arr1 = new Int8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.map( fcn, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Int8Array.prototype.reduce( fcn\[, initialValue] ) + +Applies a function against an accumulator and each element in an array and returns the accumulated result. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Int8Array( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn ); +// returns 12 +``` + +If not provided an initial value, the method invokes a provided function with the first array element as the first argument and the second array element as the second argument. + +If provided an initial value, the method invokes a provided function with the initial value as the first argument and the first array element as the second argument. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Int8Array( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn, 0 ); +// returns 14 +``` + +A callback is provided four arguments: + +- `acc`: accumulated result +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + + + +#### Int8Array.prototype.reduceRight( fcn\[, initialValue] ) + +Applies a function against an accumulator and each element in an array and returns the accumulated result, iterating from right to left. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Int8Array( [ 2, 1, 3 ] ); + +var v = arr.reduceRight( fcn ); +// returns 8 +``` + +If not provided an initial value, the method invokes a provided function with the last array element as the first argument and the second-to-last array element as the second argument. + +If provided an initial value, the method invokes a provided function with the initial value as the first argument and the last array element as the second argument. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Int8Array( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn, 0 ); +// returns 14 +``` + +A callback is provided four arguments: + +- `acc`: accumulated result +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + + + +#### Int8Array.prototype.reverse() + +Reverses an array **in-place** (thus mutating the array on which the method is invoked). + + + +```javascript +var arr = new Int8Array( [ 2, 0, 3 ] ); + +// Reverse the array: +arr.reverse(); + +var v = arr[ 0 ]; +// returns 3 + +v = arr[ 1 ]; +// returns 0 + +v = arr[ 2 ]; +// returns 2 +``` + + + +#### Int8Array.prototype.set( arr\[, offset] ) + +Sets array elements. + + + +```javascript +var arr = new Int8Array( [ 1, 2, 3 ] ); +// returns [ 1, 2, 3 ] + +// Set the first two array elements: +arr.set( [ 4, 5 ] ); + +var v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 5 +``` + +By default, the method starts writing values at the first array index. To specify an alternative index, provide an index `offset`. + + + +```javascript +var arr = new Int8Array( [ 1, 2, 3 ] ); +// returns [ 1, 2, 3 ] + +// Set the last two array elements: +arr.set( [ 4, 5 ], 1 ); + +var v = arr[ 1 ]; +// returns 4 + +v = arr[ 2 ]; +// returns 5 +``` + + + +#### Int8Array.prototype.slice( \[begin\[, end]] ) + +Copies array elements to a new array with the same underlying data type as the host array. + + + +```javascript +var arr1 = new Int8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice(); + +var bool = ( arr1 === arr2 ); +// returns false + +bool = ( arr1.buffer === arr2.buffer ); +// returns false + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 + +v = arr2[ 2 ]; +// returns 3 +``` + +By default, the method copies elements beginning with the first array element. To specify an alternative array index at which to begin copying, provide a `begin` index (inclusive). + + + +```javascript +var arr1 = new Int8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( 1 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 2 + +v = arr2[ 1 ]; +// returns 3 +``` + +By default, the method copies all array elements after `begin`. To specify an alternative array index at which to end copying, provide an `end` index (exclusive). + + + +```javascript +var arr1 = new Int8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( 0, 2 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 +``` + +When a `begin` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr1 = new Int8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( -arr1.length, -1 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 +``` + + + +#### Int8Array.prototype.some( predicate\[, thisArg] ) + +Tests whether at least one array element passes a test implemented by a `predicate` function. + + + +```javascript +function predicate( v ) { + return ( v >= 2 ); +} + +var arr = new Int8Array( [ 1, 2 ] ); + +var bool = arr.some( predicate ); +// returns true +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Int8Array( [ 1, 1 ] ); + +var bool = arr.some( predicate, ctx ); +// returns false + +var n = ctx.count; +// returns 2 +``` + + + +#### Int8Array.prototype.sort( \[compareFunction] ) + +Sorts an array **in-place** (thus mutating the array on which the method is invoked). + + + +```javascript +var arr = new Int8Array( [ 2, 3, 0 ] ); + +// Sort the array (in ascending order): +arr.sort(); + +var v = arr[ 0 ]; +// returns 0 + +v = arr[ 1 ]; +// returns 2 + +v = arr[ 2 ]; +// returns 3 +``` + +By default, the method sorts array elements in ascending order. To impose a custom order, provide a `compareFunction`. + + + +```javascript +function descending( a, b ) { + return b - a; +} + +var arr = new Int8Array( [ 2, 3, 0 ] ); + +// Sort the array (in descending order): +arr.sort( descending ); + +var v = arr[ 0 ]; +// returns 3 + +v = arr[ 1 ]; +// returns 2 + +v = arr[ 2 ]; +// returns 0 +``` + +The comparison function is provided two array elements, `a` and `b`, per invocation, and its return value determines the sort order as follows: + +- If the comparison function returns a value **less** than zero, then the method sorts `a` to an index lower than `b` (i.e., `a` should come **before** `b`). +- If the comparison function returns a value **greater** than zero, then the method sorts `a` to an index higher than `b` (i.e., `b` should come **before** `a`). +- If the comparison function returns **zero**, then the relative order of `a` and `b` _should_ remain unchanged. + + + +#### Int8Array.prototype.subarray( \[begin\[, end]] ) + +Creates a new typed array view over the same underlying [`ArrayBuffer`][@stdlib/array/buffer] and with the same underlying data type as the host array. + + + +```javascript +var arr1 = new Int8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray(); +// returns [ 1, 2, 3 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +By default, the method creates a typed array view beginning with the first array element. To specify an alternative array index at which to begin, provide a `begin` index (inclusive). + + + +```javascript +var arr1 = new Int8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 1 ); +// returns [ 2, 3 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +By default, the method creates a typed array view which includes all array elements after `begin`. To limit the number of array elements after `begin`, provide an `end` index (exclusive). + + + +```javascript +var arr1 = new Int8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 0, 2 ); +// returns [ 1, 2 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +When a `begin` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr1 = new Int8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( -arr1.length, -1 ); +// returns [ 1, 2 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +If the method is unable to resolve indices to a non-empty array subsequence, the method returns an empty typed array. + + + +```javascript +var arr1 = new Int8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 10, -1 ); +// returns [] +``` + + + +#### Int8Array.prototype.toLocaleString( \[locales\[, options]] ) + +Serializes an array as a locale-specific `string`. + + + +```javascript +var arr = new Int8Array( [ 1, 2, 3 ] ); + +var str = arr.toLocaleString(); +// returns '1,2,3' +``` + + + +#### Int8Array.prototype.toString() + +Serializes an array as a `string`. + + + +```javascript +var arr = new Int8Array( [ 1, 2, 3 ] ); + +var str = arr.toString(); +// returns '1,2,3' +``` + + + +#### Int8Array.prototype.values() + +Returns an iterator for iterating over array elements. + + + +```javascript +var arr = new Int8Array( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.values(); + +// Iterate over array elements... +var v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 2 + +var bool = it.next().done; +// returns true +``` + +
+ + + +* * * + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var randu = require( '@stdlib/random/base/randu' ); +var round = require( '@stdlib/math/base/special/round' ); +var ctor = require( '@stdlib/array/int8' ); + +var arr; +var i; + +arr = new ctor( 10 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = round( randu()*100.0 ); +} +console.log( arr ); +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/int8/benchmark/benchmark.copy_within.js b/int8/benchmark/benchmark.copy_within.js new file mode 100644 index 00000000..60156d26 --- /dev/null +++ b/int8/benchmark/benchmark.copy_within.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':copyWithin', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr[ 0 ] = v; + arr = arr.copyWithin( 1, 0 ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/benchmark/benchmark.copy_within.length.js b/int8/benchmark/benchmark.copy_within.length.js new file mode 100644 index 00000000..1a00aacc --- /dev/null +++ b/int8/benchmark/benchmark.copy_within.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr[ 0 ] = v; + arr = arr.copyWithin( 1, 0 ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':copyWithin:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.data.js b/int8/benchmark/benchmark.data.js new file mode 100644 index 00000000..a4dda02b --- /dev/null +++ b/int8/benchmark/benchmark.data.js @@ -0,0 +1,75 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::get,index', function benchmark( b ) { + var arr; + var N; + var v; + var i; + + arr = new Int8Array( 2 ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr[ i%N ]; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::set,index', function benchmark( b ) { + var arr; + var N; + var i; + + arr = new Int8Array( 2 ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ i%N ] = i; + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] || arr[ 1 ] !== arr[ 1 ] ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/benchmark/benchmark.entries.js b/int8/benchmark/benchmark.entries.js new file mode 100644 index 00000000..b830a69e --- /dev/null +++ b/int8/benchmark/benchmark.entries.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':entries', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Int8Array( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.entries(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/benchmark/benchmark.every.js b/int8/benchmark/benchmark.every.js new file mode 100644 index 00000000..40a8642c --- /dev/null +++ b/int8/benchmark/benchmark.every.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':every', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); + +bench( pkg+'::this_context:every', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate, {} ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); diff --git a/int8/benchmark/benchmark.every.length.js b/int8/benchmark/benchmark.every.length.js new file mode 100644 index 00000000..a0229bdb --- /dev/null +++ b/int8/benchmark/benchmark.every.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value >= 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':every:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.fill.js b/int8/benchmark/benchmark.fill.js new file mode 100644 index 00000000..da6d595a --- /dev/null +++ b/int8/benchmark/benchmark.fill.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':fill', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr = arr.fill( v ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/benchmark/benchmark.fill.length.js b/int8/benchmark/benchmark.fill.length.js new file mode 100644 index 00000000..e81e99fb --- /dev/null +++ b/int8/benchmark/benchmark.fill.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr = arr.fill( v ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':fill:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.filter.js b/int8/benchmark/benchmark.filter.js new file mode 100644 index 00000000..3ea9329b --- /dev/null +++ b/int8/benchmark/benchmark.filter.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt8Array = require( '@stdlib/assert/is-int8array' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':filter', function benchmark( b ) { + var arr; + var out; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt8Array( out ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); + +bench( pkg+'::this_context:filter', function benchmark( b ) { + var arr; + var out; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate, {} ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt8Array( out ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); diff --git a/int8/benchmark/benchmark.filter.length.js b/int8/benchmark/benchmark.filter.length.js new file mode 100644 index 00000000..bfabe84c --- /dev/null +++ b/int8/benchmark/benchmark.filter.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isInt8Array = require( '@stdlib/assert/is-int8array' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value >= 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt8Array( out ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':filter:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.find.js b/int8/benchmark/benchmark.find.js new file mode 100644 index 00000000..470dd8da --- /dev/null +++ b/int8/benchmark/benchmark.find.js @@ -0,0 +1,82 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':find', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int8Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:find', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int8Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate, {} ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/int8/benchmark/benchmark.find.length.js b/int8/benchmark/benchmark.find.length.js new file mode 100644 index 00000000..5abbeee8 --- /dev/null +++ b/int8/benchmark/benchmark.find.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - tuple length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int8Array( len ); + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':find:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.find_index.js b/int8/benchmark/benchmark.find_index.js new file mode 100644 index 00000000..7b6e0329 --- /dev/null +++ b/int8/benchmark/benchmark.find_index.js @@ -0,0 +1,82 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':findIndex', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int8Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:findIndex', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int8Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate, {} ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/int8/benchmark/benchmark.find_index.length.js b/int8/benchmark/benchmark.find_index.length.js new file mode 100644 index 00000000..05cfd05e --- /dev/null +++ b/int8/benchmark/benchmark.find_index.length.js @@ -0,0 +1,104 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Float32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0.0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Float32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':findIndex:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.for_each.js b/int8/benchmark/benchmark.for_each.js new file mode 100644 index 00000000..c88177ea --- /dev/null +++ b/int8/benchmark/benchmark.for_each.js @@ -0,0 +1,88 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':forEach', function benchmark( b ) { + var count; + var arr; + var N; + var i; + + arr = new Int8Array( 2 ); + N = arr.length; + + count = 0; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn ); + if ( count !== N*(i+1) ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( count !== N*i ) { + b.fail( 'unexpected result' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn() { + count += 1; + } +}); + +bench( pkg+'::this_context:forEach', function benchmark( b ) { + var count; + var arr; + var N; + var i; + + arr = new Int8Array( 2 ); + N = arr.length; + + count = 0; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn, {} ); + if ( count !== N*(i+1) ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( count !== N*i ) { + b.fail( 'unexpected result' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn() { + count += 1; + } +}); diff --git a/int8/benchmark/benchmark.for_each.length.js b/int8/benchmark/benchmark.for_each.length.js new file mode 100644 index 00000000..09f03918 --- /dev/null +++ b/int8/benchmark/benchmark.for_each.length.js @@ -0,0 +1,106 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var count; + var arr; + + arr = new Int8Array( len ); + count = 0; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn ); + if ( count !== count ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( count !== count ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } + + /** + * Callback invoked for each tuple element. + * + * @private + */ + function fcn() { + count += 1; + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':forEach:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.from.js b/int8/benchmark/benchmark.from.js new file mode 100644 index 00000000..0708827b --- /dev/null +++ b/int8/benchmark/benchmark.from.js @@ -0,0 +1,237 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var ITERATOR_SYMBOL = require( '@stdlib/symbol/iterator' ); +var isInt8Array = require( '@stdlib/assert/is-int8array' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// VARIABLES // + +var opts = { + 'skip': ( ITERATOR_SYMBOL === null ) +}; + + +// MAIN // + +bench( pkg+'::typed_array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Int8Array( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int8Array.from( buf ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt8Array( arr ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array,clbk:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Int8Array( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int8Array.from( buf, clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt8Array( arr ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1; + } +}); + +bench( pkg+'::array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1, 2 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int8Array.from( buf ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt8Array( arr ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::array,clbk:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1, 2 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int8Array.from( buf, clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt8Array( arr ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1; + } +}); + +bench( pkg+'::iterable:from', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int8Array.from( createIterable() ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt8Array( arr ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out; + var i; + + out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + + i = 0; + + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + i += 1; + if ( i <= 2 ) { + return { + 'value': 0, + 'done': false + }; + } + return { + 'done': true + }; + } + } +}); + +bench( pkg+'::iterable,clbk:from:', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int8Array.from( createIterable(), clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt8Array( arr ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out; + var i; + + out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + + i = 0; + + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + i += 1; + if ( i <= 2 ) { + return { + 'value': 1, + 'done': false + }; + } + return { + 'done': true + }; + } + } + + function clbk( v ) { + return v + 1; + } +}); diff --git a/int8/benchmark/benchmark.includes.js b/int8/benchmark/benchmark.includes.js new file mode 100644 index 00000000..78e6a65f --- /dev/null +++ b/int8/benchmark/benchmark.includes.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':includes', function benchmark( b ) { + var bool; + var arr; + var v; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + bool = arr.includes( v ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/benchmark/benchmark.includes.length.js b/int8/benchmark/benchmark.includes.length.js new file mode 100644 index 00000000..3aa2aaa7 --- /dev/null +++ b/int8/benchmark/benchmark.includes.length.js @@ -0,0 +1,96 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + bool = arr.includes( v ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':includes:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.index_of.js b/int8/benchmark/benchmark.index_of.js new file mode 100644 index 00000000..d638435a --- /dev/null +++ b/int8/benchmark/benchmark.index_of.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':indexOf', function benchmark( b ) { + var out; + var arr; + var v; + var i; + + arr = new Int8Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.indexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/benchmark/benchmark.index_of.length.js b/int8/benchmark/benchmark.index_of.length.js new file mode 100644 index 00000000..6cf9936b --- /dev/null +++ b/int8/benchmark/benchmark.index_of.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.indexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':indexOf:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.join.js b/int8/benchmark/benchmark.join.js new file mode 100644 index 00000000..2f0ddb4f --- /dev/null +++ b/int8/benchmark/benchmark.join.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':join', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i % 127; + out = arr.join(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/benchmark/benchmark.join.length.js b/int8/benchmark/benchmark.join.length.js new file mode 100644 index 00000000..93d779a5 --- /dev/null +++ b/int8/benchmark/benchmark.join.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i % 127; + out = arr.join(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':join:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.js b/int8/benchmark/benchmark.js new file mode 100644 index 00000000..74ef7986 --- /dev/null +++ b/int8/benchmark/benchmark.js @@ -0,0 +1,47 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt8Array = require( '@stdlib/assert/is-int8array' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new ctor( 0 ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isInt8Array( arr ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/benchmark/benchmark.keys.js b/int8/benchmark/benchmark.keys.js new file mode 100644 index 00000000..dfdeb1dc --- /dev/null +++ b/int8/benchmark/benchmark.keys.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':keys', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.keys(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/benchmark/benchmark.last_index_of.js b/int8/benchmark/benchmark.last_index_of.js new file mode 100644 index 00000000..00b9448c --- /dev/null +++ b/int8/benchmark/benchmark.last_index_of.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':lastIndexOf', function benchmark( b ) { + var out; + var arr; + var v; + var i; + + arr = new Int8Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.lastIndexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/benchmark/benchmark.last_index_of.length.js b/int8/benchmark/benchmark.last_index_of.length.js new file mode 100644 index 00000000..12efaf1a --- /dev/null +++ b/int8/benchmark/benchmark.last_index_of.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.lastIndexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':lastIndexOf:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.length.js b/int8/benchmark/benchmark.length.js new file mode 100644 index 00000000..f3fb4145 --- /dev/null +++ b/int8/benchmark/benchmark.length.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isInt8Array = require( '@stdlib/assert/is-int8array' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new ctor( len ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isInt8Array( arr ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.map.js b/int8/benchmark/benchmark.map.js new file mode 100644 index 00000000..ff3dfb1b --- /dev/null +++ b/int8/benchmark/benchmark.map.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt8Array = require( '@stdlib/assert/is-int8array' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':map', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt8Array( out ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); + +bench( pkg+'::this_context:map', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn, {} ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt8Array( out ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/int8/benchmark/benchmark.map.length.js b/int8/benchmark/benchmark.map.length.js new file mode 100644 index 00000000..e44b7212 --- /dev/null +++ b/int8/benchmark/benchmark.map.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isInt8Array = require( '@stdlib/assert/is-int8array' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Maps an array element to a new value. +* +* @private +* @param {*} value - array element +* @returns {*} new value +*/ +function fcn( value ) { + return value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt8Array( out ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':map:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.of.js b/int8/benchmark/benchmark.of.js new file mode 100644 index 00000000..53a47940 --- /dev/null +++ b/int8/benchmark/benchmark.of.js @@ -0,0 +1,48 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt8Array = require( '@stdlib/assert/is-int8array' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':of', function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Int8Array.of( i, 2 ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isInt8Array( arr ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/benchmark/benchmark.properties.js b/int8/benchmark/benchmark.properties.js new file mode 100644 index 00000000..95ef3416 --- /dev/null +++ b/int8/benchmark/benchmark.properties.js @@ -0,0 +1,145 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isArrayBuffer = require( '@stdlib/assert/is-arraybuffer' ); +var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::get:buffer', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.buffer; + if ( typeof v !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isArrayBuffer( v ) ) { + b.fail( 'should return an ArrayBuffer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteLength', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteLength; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteOffset', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteOffset; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:BYTES_PER_ELEMENT', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.BYTES_PER_ELEMENT; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:length', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.length; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/benchmark/benchmark.reduce.js b/int8/benchmark/benchmark.reduce.js new file mode 100644 index 00000000..6dc489b5 --- /dev/null +++ b/int8/benchmark/benchmark.reduce.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reduce', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( acc, v ) { + return acc + v + 1; + } +}); + +bench( pkg+'::initial_value:reduce', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn, 3 ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/int8/benchmark/benchmark.reduce.length.js b/int8/benchmark/benchmark.reduce.length.js new file mode 100644 index 00000000..ed2dff61 --- /dev/null +++ b/int8/benchmark/benchmark.reduce.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Updates an accumulated value. +* +* @private +* @param {*} acc - accumulated value +* @param {*} value - array element +* @returns {*} accumulated value +*/ +function fcn( acc, value ) { + return acc + value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reduce:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.reduce_right.js b/int8/benchmark/benchmark.reduce_right.js new file mode 100644 index 00000000..5c5d499d --- /dev/null +++ b/int8/benchmark/benchmark.reduce_right.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reduceRight', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( acc, v ) { + return acc + v + 1; + } +}); + +bench( pkg+'::initial_value:reduceRight', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn, 3 ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/int8/benchmark/benchmark.reduce_right.length.js b/int8/benchmark/benchmark.reduce_right.length.js new file mode 100644 index 00000000..ec8826e4 --- /dev/null +++ b/int8/benchmark/benchmark.reduce_right.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Updates an accumulated value. +* +* @private +* @param {*} acc - accumulated value +* @param {*} value - array element +* @returns {*} accumulated value +*/ +function fcn( acc, value ) { + return acc + value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reduceRight:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.reverse.js b/int8/benchmark/benchmark.reverse.js new file mode 100644 index 00000000..51340179 --- /dev/null +++ b/int8/benchmark/benchmark.reverse.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt8Array = require( '@stdlib/assert/is-int8array' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reverse', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.reverse(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt8Array( out ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/benchmark/benchmark.reverse.length.js b/int8/benchmark/benchmark.reverse.length.js new file mode 100644 index 00000000..01d44fd3 --- /dev/null +++ b/int8/benchmark/benchmark.reverse.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isInt8Array = require( '@stdlib/assert/is-int8array' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.reverse(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt8Array( out ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reverse:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.set.js b/int8/benchmark/benchmark.set.js new file mode 100644 index 00000000..0072330a --- /dev/null +++ b/int8/benchmark/benchmark.set.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::array:set', function benchmark( b ) { + var values; + var buf; + var arr; + var N; + var v; + var i; + + values = []; + for ( i = 0; i < 10; i++ ) { + values.push( i ); + } + N = values.length; + + arr = new Int8Array( 2 ); + buf = [ 0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = values[ i%N ]; + v = arr.set( buf ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array:set', function benchmark( b ) { + var values; + var buf; + var arr; + var N; + var v; + var i; + + values = new Int8Array( 20 ); + N = values.length; + for ( i = 0; i < N; i++ ) { + values[ i ] = i; + } + + arr = new Int8Array( 2 ); + buf = new Int8Array( 1 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = values[ i%N ]; + v = arr.set( buf ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/benchmark/benchmark.set.length.js b/int8/benchmark/benchmark.set.length.js new file mode 100644 index 00000000..bce7b915 --- /dev/null +++ b/int8/benchmark/benchmark.set.length.js @@ -0,0 +1,114 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randi = require( '@stdlib/random/base/randi' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var values; + var arr1; + var arr2; + var arr; + var N; + var i; + + arr1 = []; + arr2 = []; + for ( i = 0; i < len; i++ ) { + arr1.push( randi() ); + arr2.push( randi() ); + } + arr = new Int8Array( len ); + + values = [ + arr1, + arr2 + ]; + N = values.length; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr.set( values[ i%N ] ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':set:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.slice.js b/int8/benchmark/benchmark.slice.js new file mode 100644 index 00000000..3fa057a3 --- /dev/null +++ b/int8/benchmark/benchmark.slice.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt8Array = require( '@stdlib/assert/is-int8array' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':slice', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.slice(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt8Array( out ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/benchmark/benchmark.slice.length.js b/int8/benchmark/benchmark.slice.length.js new file mode 100644 index 00000000..c28a6871 --- /dev/null +++ b/int8/benchmark/benchmark.slice.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isInt8Array = require( '@stdlib/assert/is-int8array' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.slice(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt8Array( out ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':slice:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.some.js b/int8/benchmark/benchmark.some.js new file mode 100644 index 00000000..40ca80b8 --- /dev/null +++ b/int8/benchmark/benchmark.some.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':some', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:some', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate, {} ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/int8/benchmark/benchmark.some.length.js b/int8/benchmark/benchmark.some.length.js new file mode 100644 index 00000000..6805fd54 --- /dev/null +++ b/int8/benchmark/benchmark.some.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':some:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.sort.js b/int8/benchmark/benchmark.sort.js new file mode 100644 index 00000000..ea9a380e --- /dev/null +++ b/int8/benchmark/benchmark.sort.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var randi = require( '@stdlib/random/base/randi' ); +var isInt8Array = require( '@stdlib/assert/is-int8array' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':sort', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int8Array( [ randi(), randi() ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = randi(); + out = arr.sort(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt8Array( out ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/benchmark/benchmark.sort.length.js b/int8/benchmark/benchmark.sort.length.js new file mode 100644 index 00000000..e58533fa --- /dev/null +++ b/int8/benchmark/benchmark.sort.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randi = require( '@stdlib/random/base/randi' ); +var isInt8Array = require( '@stdlib/assert/is-int8array' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var data; + var arr; + var i; + + data = []; + for ( i = 0; i < len; i++ ) { + data.push( randi() ); + } + arr = new Int8Array( data ); + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ i%len ] = randi(); + out = arr.sort(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt8Array( out ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':sort:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.subarray.js b/int8/benchmark/benchmark.subarray.js new file mode 100644 index 00000000..8ee2e153 --- /dev/null +++ b/int8/benchmark/benchmark.subarray.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isInt8Array = require( '@stdlib/assert/is-int8array' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':subarray', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.subarray(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt8Array( out ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/benchmark/benchmark.subarray.length.js b/int8/benchmark/benchmark.subarray.length.js new file mode 100644 index 00000000..86eda65e --- /dev/null +++ b/int8/benchmark/benchmark.subarray.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isInt8Array = require( '@stdlib/assert/is-int8array' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.subarray(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isInt8Array( out ) ) { + b.fail( 'should return an Int8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':subarray:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.to_locale_string.js b/int8/benchmark/benchmark.to_locale_string.js new file mode 100644 index 00000000..510a3693 --- /dev/null +++ b/int8/benchmark/benchmark.to_locale_string.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':toLocaleString', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toLocaleString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/benchmark/benchmark.to_locale_string.length.js b/int8/benchmark/benchmark.to_locale_string.length.js new file mode 100644 index 00000000..4c75af03 --- /dev/null +++ b/int8/benchmark/benchmark.to_locale_string.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toLocaleString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':toLocaleString:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.to_string.js b/int8/benchmark/benchmark.to_string.js new file mode 100644 index 00000000..ab4aebc3 --- /dev/null +++ b/int8/benchmark/benchmark.to_string.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':toString', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/benchmark/benchmark.to_string.length.js b/int8/benchmark/benchmark.to_string.length.js new file mode 100644 index 00000000..f63ab08d --- /dev/null +++ b/int8/benchmark/benchmark.to_string.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Int8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':toString:len='+len, f ); + } +} + +main(); diff --git a/int8/benchmark/benchmark.values.js b/int8/benchmark/benchmark.values.js new file mode 100644 index 00000000..1849e01d --- /dev/null +++ b/int8/benchmark/benchmark.values.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Int8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':values', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Int8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.values(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/int8/docs/repl.txt b/int8/docs/repl.txt new file mode 100644 index 00000000..a71d10ad --- /dev/null +++ b/int8/docs/repl.txt @@ -0,0 +1,953 @@ + +{{alias}}() + A typed array constructor which returns a typed array representing an array + of twos-complement 8-bit signed integers in the platform byte order. + + Returns + ------- + out: Int8Array + A typed array. + + Examples + -------- + > var arr = new {{alias}}() + + + +{{alias}}( length ) + Returns a typed array having a specified length. + + Parameters + ---------- + length: integer + Typed array length. + + Returns + ------- + out: Int8Array + A typed array. + + Examples + -------- + > var arr = new {{alias}}( 5 ) + [ 0, 0, 0, 0, 0 ] + + +{{alias}}( typedarray ) + Creates a typed array from another typed array. + + Parameters + ---------- + typedarray: TypedArray + Typed array from which to generate another typed array. + + Returns + ------- + out: Int8Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias:@stdlib/array/int32}}( [ 5, 5, 5 ] ); + > var arr2 = new {{alias}}( arr1 ) + [ 5, 5, 5 ] + + +{{alias}}( obj ) + Creates a typed array from an array-like object or iterable. + + Parameters + ---------- + obj: Object + Array-like object or iterable from which to generate a typed array. + + Returns + ------- + out: Int8Array + A typed array. + + Examples + -------- + > var arr1 = [ 5.0, 5.0, 5.0 ]; + > var arr2 = new {{alias}}( arr1 ) + [ 5, 5, 5 ] + + +{{alias}}( buffer[, byteOffset[, length]] ) + Returns a typed array view of an ArrayBuffer. + + Parameters + ---------- + buffer: ArrayBuffer + Underlying ArrayBuffer. + + byteOffset: integer (optional) + Integer byte offset specifying the location of the first typed array + element. Default: 0. + + length: integer (optional) + View length. If not provided, the view spans from the byteOffset to + the end of the underlying ArrayBuffer. + + Returns + ------- + out: Int8Array + A typed array. + + Examples + -------- + > var buf = new {{alias:@stdlib/array/buffer}}( 4 ); + > var arr = new {{alias}}( buf, 0, 4 ) + [ 0, 0, 0, 0 ] + + +{{alias}}.from( src[, map[, thisArg]] ) + Creates a new typed array from an array-like object or an iterable. + + A callback is provided the following arguments: + + - value: source value. + - index: source index. + + Parameters + ---------- + src: ArrayLike|Iterable + Source of array elements. + + map: Function (optional) + Callback to invoke for each source element. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Int8Array + A typed array. + + Examples + -------- + > function mapFcn( v ) { return v * 2; }; + > var arr = {{alias}}.from( [ 1, 2 ], mapFcn ) + [ 2, 4 ] + + +{{alias}}.of( element0[, element1[, ...elementN]] ) + Creates a new typed array from a variable number of arguments. + + Parameters + ---------- + element0: number + Array element. + + element1: number (optional) + Array element. + + elementN: number (optional) + Array elements. + + Returns + ------- + out: Int8Array + A typed array. + + Examples + -------- + > var arr = {{alias}}.of( 1, 2 ) + [ 1, 2 ] + + +{{alias}}.BYTES_PER_ELEMENT + Number of bytes per view element. + + Examples + -------- + > {{alias}}.BYTES_PER_ELEMENT + 1 + + +{{alias}}.name + Typed array constructor name. + + Examples + -------- + > {{alias}}.name + 'Int8Array' + + +{{alias}}.prototype.buffer + Read-only property which returns the ArrayBuffer referenced by the typed + array. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.buffer + + + +{{alias}}.prototype.byteLength + Read-only property which returns the length (in bytes) of the typed array. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.byteLength + 5 + + +{{alias}}.prototype.byteOffset + Read-only property which returns the offset (in bytes) of the typed array + from the start of its ArrayBuffer. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.byteOffset + 0 + + +{{alias}}.prototype.BYTES_PER_ELEMENT + Number of bytes per view element. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.BYTES_PER_ELEMENT + 1 + + +{{alias}}.prototype.length + Read-only property which returns the number of view elements. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.length + 5 + + +{{alias}}.prototype.copyWithin( target, start[, end] ) + Copies a sequence of elements within the array starting at `start` and + ending at `end` (non-inclusive) to the position starting at `target`. + + Parameters + ---------- + target: integer + Target start index position. + + start: integer + Source start index position. + + end: integer (optional) + Source end index position. Default: out.length. + + Returns + ------- + out: Int8Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3, 4, 5 ] ); + > arr.copyWithin( 3, 0, 2 ); + > arr[ 3 ] + 1 + > arr[ 4 ] + 2 + + +{{alias}}.prototype.entries() + Returns an iterator for iterating over array key-value pairs. + + Returns + ------- + iter: Iterator + Iterator for iterating over array key-value pairs. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.entries(); + > it.next().value + [ 0, 1 ] + > it.next().value + [ 1, 2 ] + > it.next().done + true + + +{{alias}}.prototype.every( predicate[, thisArg] ) + Tests whether all array elements pass a test implemented by a predicate + function. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. If a predicate function + returns a truthy value, an array element passes; otherwise, an array + element fails. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + bool: boolean + Boolean indicating whether all array elements pass. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > function predicate( v ) { return ( v <= 1 ); }; + > arr.every( predicate ) + false + + +{{alias}}.prototype.fill( value[, start[, end]] ) + Fills an array from a start index to an end index (non-inclusive) with a + provided value. + + Parameters + ---------- + value: number + Fill value. + + start: integer (optional) + Start index. If less than zero, the start index is resolved relative to + the last array element. Default: 0. + + end: integer (optional) + End index (non-inclusive). If less than zero, the end index is resolved + relative to the last array element. Default: out.length. + + Returns + ------- + out: Int8Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > arr.fill( 3 ); + > arr[ 0 ] + 3 + > arr[ 1 ] + 3 + + +{{alias}}.prototype.filter( predicate[, thisArg] ) + Creates a new array which includes those elements for which a predicate + function returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + The returned array has the same data type as the host array. + + If a predicate function does not return a truthy value for any array + element, the method returns `null`. + + Parameters + ---------- + predicate: Function + Predicate function which filters array elements. If a predicate function + returns a truthy value, an array element is included in the output + array; otherwise, an array element is not included in the output array. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Int8Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 1 ); }; + > var arr2 = arr1.filter( predicate ); + > arr2.length + 2 + + +{{alias}}.prototype.find( predicate[, thisArg] ) + Returns the first array element for which a provided predicate function + returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + If a predicate function never returns a truthy value, the method returns + `undefined`. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + value: number|undefined + Array element. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 2 ); }; + > var v = arr.find( predicate ) + 3 + + +{{alias}}.prototype.findIndex( predicate[, thisArg] ) + Returns the index of the first array element for which a provided predicate + function returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + If a predicate function never returns a truthy value, the method returns + `-1`. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + idx: integer + Array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 2 ); }; + > var idx = arr.findIndex( predicate ) + 2 + + +{{alias}}.prototype.forEach( fcn[, thisArg] ) + Invokes a callback for each array element. + + A provided function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + fcn: Function + Function to invoke for each array element. + + thisArg: Any (optional) + Callback execution context. + + Examples + -------- + > var arr = new {{alias}}( [ 3, 2, 1 ] ); + > var str = ' '; + > function fcn( v, i ) { str += i + ':' + v + ' '; }; + > arr.forEach( fcn ); + > str + ' 0:3 1:2 2:1 ' + + +{{alias}}.prototype.includes( searchElement[, fromIndex] ) + Returns a boolean indicating whether an array includes a search element. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: 0. + + Returns + ------- + bool: boolean + Boolean indicating whether an array includes a search element. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > var bool = arr.includes( 4 ) + false + > bool = arr.includes( 3 ) + true + + +{{alias}}.prototype.indexOf( searchElement[, fromIndex] ) + Returns the index of the first array element strictly equal to a search + element. + + If unable to locate a search element, the method returns `-1`. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: 0. + + Returns + ------- + idx: integer + Array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > var idx = arr.indexOf( 4 ) + -1 + > idx = arr.indexOf( 3 ) + 2 + + +{{alias}}.prototype.join( [separator] ) + Serializes an array by joining all array elements as a string. + + Parameters + ---------- + separator: string (optional) + String delineating array elements. Default: ','. + + Returns + ------- + str: string + Array serialized as a string. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.join( '|' ) + '1|2|3' + + +{{alias}}.prototype.keys() + Returns an iterator for iterating over array keys. + + Returns + ------- + iter: Iterator + Iterator for iterating over array keys. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.keys(); + > it.next().value + 0 + > it.next().value + 1 + > it.next().done + true + + +{{alias}}.prototype.lastIndexOf( searchElement[, fromIndex] ) + Returns the index of the last array element strictly equal to a search + element. + + The method iterates from the last array element to the first array element. + + If unable to locate a search element, the method returns `-1`. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: -1. + + Returns + ------- + idx: integer + array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 0, 2, 0, 1 ] ); + > var idx = arr.lastIndexOf( 3 ) + -1 + > idx = arr.lastIndexOf( 0 ) + 3 + + +{{alias}}.prototype.map( fcn[, thisArg] ) + Maps each array element to an element in a new typed array. + + A provided function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + The returned array has the same data type as the host array. + + Parameters + ---------- + fcn: Function + Function which maps array elements to elements in the new array. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Int8Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( v ) { return v * 2; }; + > var arr2 = arr1.map( fcn ); + [ 2, 4, 6 ] + + +{{alias}}.prototype.reduce( fcn[, initialValue] ) + Applies a function against an accumulator and each element in an array and + returns the accumulated result. + + The provided function is provided the following arguments: + + - acc: accumulated result. + - value: current array element. + - index: index of the current array element. + - arr: array on which the method is invoked. + + If provided an initial value, the method invokes a provided function with + the initial value as the first argument and the first array element as the + second argument. + + If not provided an initial value, the method invokes a provided function + with the first array element as the first argument and the second array + element as the second argument. + + Parameters + ---------- + fcn: Function + Function to apply. + + initialValue: Any (optional) + Initial accumulation value. + + Returns + ------- + out: Any + Accumulated result. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( acc, v ) { return acc + (v*v); }; + > var v = arr.reduce( fcn, 0 ) + 14 + + +{{alias}}.prototype.reduceRight( fcn[, initialValue] ) + Applies a function against an accumulator and each element in an array and + returns the accumulated result, iterating from right to left. + + The provided function is provided the following arguments: + + - acc: accumulated result. + - value: current array element. + - index: index of the current array element. + - arr: array on which the method is invoked. + + If provided an initial value, the method invokes a provided function with + the initial value as the first argument and the last array element as the + second argument. + + If not provided an initial value, the method invokes a provided function + with the last array element as the first argument and the second-to-last + array element as the second argument. + + Parameters + ---------- + fcn: Function + Function to apply. + + initialValue: Any (optional) + Initial accumulation value. + + Returns + ------- + out: Any + Accumulated result. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( acc, v ) { return acc + (v*v); }; + > var v = arr.reduceRight( fcn, 0 ) + 14 + + +{{alias}}.prototype.reverse() + Reverses an array *in-place*. + + This method mutates the array on which the method is invoked. + + Returns + ------- + out: Int8Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ) + [ 1, 2, 3 ] + > arr.reverse() + [ 3, 2, 1 ] + + +{{alias}}.prototype.set( arr[, offset] ) + Sets array elements. + + Parameters + ---------- + arr: ArrayLike + Source array containing array values to set. + + offset: integer (optional) + Array index at which to start writing values. Default: 0. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.set( [ 4, 4 ], 1 ); + > arr[ 1 ] + 4 + > arr[ 2 ] + 4 + + +{{alias}}.prototype.slice( [begin[, end]] ) + Copies array elements to a new array with the same underlying data type as + the host array. + + If the method is unable to resolve indices to a non-empty array subsequence, + the method returns `null`. + + Parameters + ---------- + begin: integer (optional) + Start element index (inclusive). If less than zero, the start index is + resolved relative to the last array element. Default: 0. + + end: integer (optional) + End element index (exclusive). If less than zero, the end index is + resolved relative to the last array element. Default: arr.length. + + Returns + ------- + out: Int8Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > var arr2 = arr1.slice( 1 ); + > arr2.length + 2 + > arr2[ 0 ] + 1 + > arr2[ 1 ] + 2 + + +{{alias}}.prototype.some( predicate[, thisArg] ) + Tests whether at least one array element passes a test implemented by a + predicate function. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. If a predicate function + returns a truthy value, a array element passes; otherwise, an array + element fails. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + bool: boolean + Boolean indicating whether at least one array element passes. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > function predicate( v ) { return ( v > 1 ); }; + > arr.some( predicate ) + true + + +{{alias}}.prototype.sort( [compareFunction] ) + Sorts an array *in-place*. + + The comparison function is provided two array elements per invocation: `a` + and `b`. + + The comparison function return value determines the sort order as follows: + + - If the comparison function returns a value less than zero, then the method + sorts `a` to an index lower than `b` (i.e., `a` should come *before* `b`). + + - If the comparison function returns a value greater than zero, then the + method sorts `a` to an index higher than `b` (i.e., `b` should come *before* + `a`). + + - If the comparison function returns zero, then the relative order of `a` + and `b` should remain unchanged. + + This method mutates the array on which the method is invoked. + + Parameters + ---------- + compareFunction: Function (optional) + Function which specifies the sort order. The default sort order is + ascending order. + + Returns + ------- + out: Int8Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 0, 2, 1 ] ); + > arr.sort() + [ 0, 1, 1, 2, 2 ] + + +{{alias}}.prototype.subarray( [begin[, end]] ) + Creates a new typed array over the same underlying ArrayBuffer and with the + same underlying data type as the host array. + + If the method is unable to resolve indices to a non-empty array subsequence, + the method returns an empty typed array. + + Parameters + ---------- + begin: integer (optional) + Start element index (inclusive). If less than zero, the start index is + resolved relative to the last array element. Default: 0. + + end: integer (optional) + End element index (exclusive). If less than zero, the end index is + resolved relative to the last array element. Default: arr.length. + + Returns + ------- + out: Int8Array + A new typed array view. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3, 4, 5 ] ); + > var arr2 = arr1.subarray( 2 ) + [ 3, 4, 5 ] + + +{{alias}}.prototype.toLocaleString( [locales[, options]] ) + Serializes an array as a locale-specific string. + + Parameters + ---------- + locales: string|Array (optional) + A BCP 47 language tag, or an array of such tags. + + options: Object (optional) + Options. + + Returns + ------- + str: string + A typed array string representation. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.toLocaleString() + '1,2,3' + + +{{alias}}.prototype.toString() + Serializes an array as a string. + + Returns + ------- + str: string + A typed array string representation. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.toString() + '1,2,3' + + +{{alias}}.prototype.values() + Returns an iterator for iterating over array elements. + + Returns + ------- + iter: Iterator + Iterator for iterating over array elements. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.values(); + > it.next().value + 1 + > it.next().value + 2 + > it.next().done + true + + + See Also + -------- + diff --git a/int8/docs/types/index.d.ts b/int8/docs/types/index.d.ts new file mode 100644 index 00000000..c4f785b4 --- /dev/null +++ b/int8/docs/types/index.d.ts @@ -0,0 +1,26 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +// EXPORTS // + +/** +* Typed array constructor which returns a typed array representing an array of twos-complement 8-bit signed integers in the platform byte order. +*/ +export = Int8Array; diff --git a/int8/docs/types/test.ts b/int8/docs/types/test.ts new file mode 100644 index 00000000..000d037f --- /dev/null +++ b/int8/docs/types/test.ts @@ -0,0 +1,37 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// tslint:disable: no-construct +// tslint:disable: no-unused-expression + +import Int8Array = require( './index' ); + + +// TESTS // + +// The function returns a typed array instance... +{ + new Int8Array( 10 ); // $ExpectType Int8Array + new Int8Array( [ 2, 5, 5, 7 ] ); // $ExpectType Int8Array +} + +// The constructor function has to be invoked with `new`... +{ + Int8Array( 10 ); // $ExpectError + Int8Array( [ 2, 5, 5, 7 ] ); // $ExpectError +} diff --git a/int8/examples/index.js b/int8/examples/index.js new file mode 100644 index 00000000..d0978bec --- /dev/null +++ b/int8/examples/index.js @@ -0,0 +1,32 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var randu = require( '@stdlib/random/base/randu' ); +var round = require( '@stdlib/math/base/special/round' ); +var ctor = require( './../lib' ); + +var arr; +var i; + +arr = new ctor( 10 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = round( randu()*100.0 ); +} +console.log( arr ); diff --git a/int8/lib/index.js b/int8/lib/index.js new file mode 100644 index 00000000..b595450f --- /dev/null +++ b/int8/lib/index.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Typed array constructor which returns a typed array representing an array of twos-complement 8-bit signed integers in the platform byte order. +* +* @module @stdlib/array/int8 +* +* @example +* var ctor = require( '@stdlib/array/int8' ); +* +* var arr = new ctor( 10 ); +* // returns +*/ + +// MODULES // + +var hasInt8ArraySupport = require( '@stdlib/assert/has-int8array-support' ); +var builtin = require( './int8array.js' ); +var polyfill = require( './polyfill.js' ); + + +// MAIN // + +var ctor; +if ( hasInt8ArraySupport() ) { + ctor = builtin; +} else { + ctor = polyfill; +} + + +// EXPORTS // + +module.exports = ctor; diff --git a/int8/lib/int8array.js b/int8/lib/int8array.js new file mode 100644 index 00000000..667410e0 --- /dev/null +++ b/int8/lib/int8array.js @@ -0,0 +1,28 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MAIN // + +var ctor = ( typeof Int8Array === 'function' ) ? Int8Array : void 0; // eslint-disable-line stdlib/require-globals + + +// EXPORTS // + +module.exports = ctor; diff --git a/int8/lib/polyfill.js b/int8/lib/polyfill.js new file mode 100644 index 00000000..cd3f2fb0 --- /dev/null +++ b/int8/lib/polyfill.js @@ -0,0 +1,37 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// TODO: write polyfill + +// MAIN // + +/** +* Typed array which represents an array of twos-complement 8-bit signed integers in the platform byte order. +* +* @throws {Error} not implemented +*/ +function polyfill() { + throw new Error( 'not implemented' ); +} + + +// EXPORTS // + +module.exports = polyfill; diff --git a/int8/package.json b/int8/package.json new file mode 100644 index 00000000..8202e1db --- /dev/null +++ b/int8/package.json @@ -0,0 +1,69 @@ +{ + "name": "@stdlib/array/int8", + "version": "0.0.0", + "description": "Int8Array.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structure", + "array", + "typed", + "typed array", + "typed-array", + "int8array", + "int8", + "int8_t", + "integer", + "int", + "signed", + "byte" + ] +} diff --git a/int8/test/test.copy_within.js b/int8/test/test.copy_within.js new file mode 100644 index 00000000..dda6a676 --- /dev/null +++ b/int8/test/test.copy_within.js @@ -0,0 +1,320 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var hasProp = require( '@stdlib/assert/has-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var Int8Array = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof Int8Array, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'a typed array instance has a `copyWithin` method for copying a sequence of elements within a typed array', function test( t ) { + var arr = new Int8Array( 2 ); + t.strictEqual( hasProp( arr, 'copyWithin' ), true, 'has property' ); + t.strictEqual( isFunction( arr.copyWithin ), true, 'has method' ); + t.end(); +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a typed array instance', function test( t ) { + var values; + var arr; + var i; + + arr = new Int8Array( 2 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0 ); + }; + } +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a typed array instance (end)', function test( t ) { + var values; + var arr; + var i; + + arr = new Int8Array( 2 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0, 5 ); + }; + } +}); + +tape( 'the method copies a sequence of elements within a typed array', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int8Array( arr ); + p.copyWithin( 0, 3 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative target)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int8Array( arr ); + p.copyWithin( -p.length, 3 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative start)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int8Array( arr ); + p.copyWithin( 0, -2 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (end=length)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int8Array( arr ); + p.copyWithin( 0, 3, p.length ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (non-inclusive end)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int8Array( arr ); + p.copyWithin( 2, 0, 2 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative end)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int8Array( arr ); + p.copyWithin( 2, 0, -3 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (target >= length)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int8Array( arr ); + p.copyWithin( p.length, 3 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (target > start)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Int8Array( arr ); + p.copyWithin( 2, 0 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + t.strictEqual( p[ 4 ], 2, 'returns expected value' ); + + t.end(); +}); diff --git a/int8/test/test.js b/int8/test/test.js new file mode 100644 index 00000000..d45a7587 --- /dev/null +++ b/int8/test/test.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var hasInt8ArraySupport = require( '@stdlib/assert/has-int8array-support' ); +var polyfill = require( './../lib/polyfill.js' ); +var ctor = require( './../lib' ); + + +// VARIABLES // + +var hasInt8Arrays = hasInt8ArraySupport(); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'if an environment supports `Int8Array`, the export is an alias for `Int8Array`', function test( t ) { + var Foo; + + Foo = proxyquire( './../lib', { + '@stdlib/assert/has-int8array-support': isTrue, + './int8array.js': Mock + }); + t.strictEqual( Foo, Mock, 'returns builtin' ); + + if ( hasInt8Arrays ) { + t.strictEqual( ctor, Int8Array, 'is alias' ); // eslint-disable-line stdlib/require-globals + } + + t.end(); + + function Mock() { + return this; + } + + function isTrue() { + return true; + } +}); + +tape( 'if an environment does not support `Int8Array`, the export is a polyfill', function test( t ) { + var Foo; + + Foo = proxyquire( './../lib', { + '@stdlib/assert/has-int8array-support': isFalse + }); + + t.strictEqual( Foo, polyfill, 'returns polyfill' ); + t.end(); + + function isFalse() { + return false; + } +}); diff --git a/int8/test/test.polyfill.js b/int8/test/test.polyfill.js new file mode 100644 index 00000000..9d6fcb19 --- /dev/null +++ b/int8/test/test.polyfill.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var ctor = require( './../lib/polyfill.js' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error when invoked', function test( t ) { + t.throws( foo, Error, 'throws an error' ); + t.end(); + + function foo() { + var f = new ctor(); // eslint-disable-line no-unused-vars + } +}); + +// TODO: tests diff --git a/lib/index.js b/lib/index.js new file mode 100644 index 00000000..9aab29a7 --- /dev/null +++ b/lib/index.js @@ -0,0 +1,474 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/* +* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name. +*/ + +// MODULES // + +var setReadOnly = require( '@stdlib/utils/define-read-only-property' ); + + +// MAIN // + +/** +* Top-level namespace. +* +* @namespace ns +*/ +var ns = {}; + +/** +* @name ArrayBuffer +* @memberof ns +* @readonly +* @constructor +* @see {@link module:@stdlib/array/buffer} +*/ +setReadOnly( ns, 'ArrayBuffer', require( '@stdlib/array/buffer' ) ); + +/** +* @name Complex64Array +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/complex64} +*/ +setReadOnly( ns, 'Complex64Array', require( '@stdlib/array/complex64' ) ); + +/** +* @name Complex128Array +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/complex128} +*/ +setReadOnly( ns, 'Complex128Array', require( '@stdlib/array/complex128' ) ); + +/** +* @name convertArray +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/convert} +*/ +setReadOnly( ns, 'convertArray', require( '@stdlib/array/convert' ) ); + +/** +* @name convertArraySame +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/convert-same} +*/ +setReadOnly( ns, 'convertArraySame', require( '@stdlib/array/convert-same' ) ); + +/** +* @name arrayCtors +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/ctors} +*/ +setReadOnly( ns, 'arrayCtors', require( '@stdlib/array/ctors' ) ); + +/** +* @name DataView +* @memberof ns +* @readonly +* @constructor +* @see {@link module:@stdlib/array/dataview} +*/ +setReadOnly( ns, 'DataView', require( '@stdlib/array/dataview' ) ); + +/** +* @name datespace +* @memberof ns +* @readonly +* @constructor +* @see {@link module:@stdlib/array/datespace} +*/ +setReadOnly( ns, 'datespace', require( '@stdlib/array/datespace' ) ); + +/** +* @name arrayDataType +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/dtype} +*/ +setReadOnly( ns, 'arrayDataType', require( '@stdlib/array/dtype' ) ); + +/** +* @name arrayDataTypes +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/dtypes} +*/ +setReadOnly( ns, 'arrayDataTypes', require( '@stdlib/array/dtypes' ) ); + +/** +* @name filledarray +* @memberof ns +* @readonly +* @constructor +* @see {@link module:@stdlib/array/filled} +*/ +setReadOnly( ns, 'filledarray', require( '@stdlib/array/filled' ) ); + +/** +* @name Float32Array +* @memberof ns +* @readonly +* @constructor +* @see {@link module:@stdlib/array/float32} +*/ +setReadOnly( ns, 'Float32Array', require( '@stdlib/array/float32' ) ); + +/** +* @name Float64Array +* @memberof ns +* @readonly +* @constructor +* @see {@link module:@stdlib/array/float64} +*/ +setReadOnly( ns, 'Float64Array', require( '@stdlib/array/float64' ) ); + +/** +* @name iterator2array +* @memberof ns +* @readonly +* @constructor +* @see {@link module:@stdlib/array/from-iterator} +*/ +setReadOnly( ns, 'iterator2array', require( '@stdlib/array/from-iterator' ) ); + +/** +* @name incrspace +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/incrspace} +*/ +setReadOnly( ns, 'incrspace', require( '@stdlib/array/incrspace' ) ); + +/** +* @name Int8Array +* @memberof ns +* @readonly +* @constructor +* @see {@link module:@stdlib/array/int8} +*/ +setReadOnly( ns, 'Int8Array', require( '@stdlib/array/int8' ) ); + +/** +* @name Int16Array +* @memberof ns +* @readonly +* @constructor +* @see {@link module:@stdlib/array/int16} +*/ +setReadOnly( ns, 'Int16Array', require( '@stdlib/array/int16' ) ); + +/** +* @name Int32Array +* @memberof ns +* @readonly +* @constructor +* @see {@link module:@stdlib/array/int32} +*/ +setReadOnly( ns, 'Int32Array', require( '@stdlib/array/int32' ) ); + +/** +* @name linspace +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/linspace} +*/ +setReadOnly( ns, 'linspace', require( '@stdlib/array/linspace' ) ); + +/** +* @name logspace +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/logspace} +*/ +setReadOnly( ns, 'logspace', require( '@stdlib/array/logspace' ) ); + +/** +* @name arrayMinDataType +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/min-dtype} +*/ +setReadOnly( ns, 'arrayMinDataType', require( '@stdlib/array/min-dtype' ) ); + +/** +* @name arrayNextDataType +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/next-dtype} +*/ +setReadOnly( ns, 'arrayNextDataType', require( '@stdlib/array/next-dtype' ) ); + +/** +* @name typedarraypool +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/pool} +*/ +setReadOnly( ns, 'typedarraypool', require( '@stdlib/array/pool' ) ); + +/** +* @name arrayPromotionRules +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/promotion-rules} +*/ +setReadOnly( ns, 'arrayPromotionRules', require( '@stdlib/array/promotion-rules' ) ); + +/** +* @name reviveTypedArray +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/reviver} +*/ +setReadOnly( ns, 'reviveTypedArray', require( '@stdlib/array/reviver' ) ); + +/** +* @name arraySafeCasts +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/safe-casts} +*/ +setReadOnly( ns, 'arraySafeCasts', require( '@stdlib/array/safe-casts' ) ); + +/** +* @name arraySameKindCasts +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/same-kind-casts} +*/ +setReadOnly( ns, 'arraySameKindCasts', require( '@stdlib/array/same-kind-casts' ) ); + +/** +* @name arrayShape +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/shape} +*/ +setReadOnly( ns, 'arrayShape', require( '@stdlib/array/shape' ) ); + +/** +* @name SharedArrayBuffer +* @memberof ns +* @readonly +* @constructor +* @see {@link module:@stdlib/array/shared-buffer} +*/ +setReadOnly( ns, 'SharedArrayBuffer', require( '@stdlib/array/shared-buffer' ) ); + +/** +* @name circarray2iterator +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/to-circular-iterator} +*/ +setReadOnly( ns, 'circarray2iterator', require( '@stdlib/array/to-circular-iterator' ) ); + +/** +* @name array2iterator +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/to-iterator} +*/ +setReadOnly( ns, 'array2iterator', require( '@stdlib/array/to-iterator' ) ); + +/** +* @name array2iteratorRight +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/to-iterator-right} +*/ +setReadOnly( ns, 'array2iteratorRight', require( '@stdlib/array/to-iterator-right' ) ); + +/** +* @name typedarray2json +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/to-json} +*/ +setReadOnly( ns, 'typedarray2json', require( '@stdlib/array/to-json' ) ); + +/** +* @name sparsearray2iterator +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/to-sparse-iterator} +*/ +setReadOnly( ns, 'sparsearray2iterator', require( '@stdlib/array/to-sparse-iterator' ) ); + +/** +* @name sparsearray2iteratorRight +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/to-sparse-iterator-right} +*/ +setReadOnly( ns, 'sparsearray2iteratorRight', require( '@stdlib/array/to-sparse-iterator-right' ) ); + +/** +* @name stridedarray2iterator +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/to-strided-iterator} +*/ +setReadOnly( ns, 'stridedarray2iterator', require( '@stdlib/array/to-strided-iterator' ) ); + +/** +* @name arrayview2iterator +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/to-view-iterator} +*/ +setReadOnly( ns, 'arrayview2iterator', require( '@stdlib/array/to-view-iterator' ) ); + +/** +* @name arrayview2iteratorRight +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/to-view-iterator-right} +*/ +setReadOnly( ns, 'arrayview2iteratorRight', require( '@stdlib/array/to-view-iterator-right' ) ); + +/** +* @name typedarray +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/typed} +*/ +setReadOnly( ns, 'typedarray', require( '@stdlib/array/typed' ) ); + +/** +* @name typedarrayComplexCtors +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/typed-complex-ctors} +*/ +setReadOnly( ns, 'typedarrayComplexCtors', require( '@stdlib/array/typed-complex-ctors' ) ); + +/** +* @name typedarrayComplexDataTypes +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/typed-complex-dtypes} +*/ +setReadOnly( ns, 'typedarrayComplexDataTypes', require( '@stdlib/array/typed-complex-dtypes' ) ); + +/** +* @name typedarrayCtors +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/typed-ctors} +*/ +setReadOnly( ns, 'typedarrayCtors', require( '@stdlib/array/typed-ctors' ) ); + +/** +* @name typedarrayDataTypes +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/array/typed-dtypes} +*/ +setReadOnly( ns, 'typedarrayDataTypes', require( '@stdlib/array/typed-dtypes' ) ); + +/** +* @name Uint8Array +* @memberof ns +* @readonly +* @constructor +* @see {@link module:@stdlib/array/uint8} +*/ +setReadOnly( ns, 'Uint8Array', require( '@stdlib/array/uint8' ) ); + +/** +* @name Uint8ClampedArray +* @memberof ns +* @readonly +* @constructor +* @see {@link module:@stdlib/array/uint8c} +*/ +setReadOnly( ns, 'Uint8ClampedArray', require( '@stdlib/array/uint8c' ) ); + +/** +* @name Uint16Array +* @memberof ns +* @readonly +* @constructor +* @see {@link module:@stdlib/array/uint16} +*/ +setReadOnly( ns, 'Uint16Array', require( '@stdlib/array/uint16' ) ); + +/** +* @name Uint32Array +* @memberof ns +* @readonly +* @constructor +* @see {@link module:@stdlib/array/uint32} +*/ +setReadOnly( ns, 'Uint32Array', require( '@stdlib/array/uint32' ) ); + +/** +* @name constants +* @memberof ns +* @readonly +* @type {Namespace} +* @see {@link module:@stdlib/constants/array} +*/ +setReadOnly( ns, 'constants', require( '@stdlib/constants/array' ) ); + + +// EXPORTS // + +module.exports = ns; diff --git a/linspace/README.md b/linspace/README.md new file mode 100644 index 00000000..bf7cf39b --- /dev/null +++ b/linspace/README.md @@ -0,0 +1,115 @@ + + +# Linspace + +> Generate a linearly spaced numeric array. + +
+ +## Usage + +```javascript +var linspace = require( '@stdlib/array/linspace' ); +``` + +#### linspace( start, stop\[, length] ) + +Generates a linearly spaced numeric `array`. If a `length` is not provided, the default output `array` length is `100`. + +```javascript +var arr = linspace( 0, 100, 6 ); +// returns [ 0, 20, 40, 60, 80, 100 ] +``` + +
+ + + +
+ +## Notes + +- The output `array` is guaranteed to include the `start` and `stop` values. Beware, however, that values between the `start` and `stop` are subject to floating-point errors. Hence, + + ```javascript + var arr = linspace( 0, 1, 3 ); + // returns [ 0, ~0.5, 1 ] + ``` + + where `arr[1]` is only guaranteed to be approximately equal to `0.5`. If you desire more control over element precision, consider using [roundn][@stdlib/math/base/special/roundn]: + + ```javascript + var roundn = require( '@stdlib/math/base/special/roundn' ); + + // Create an array subject to floating-point errors: + var arr = linspace( 0, 1, 21 ); + + // Round each value to the nearest hundredth: + var out = []; + var i; + for ( i = 0; i < arr.length; i++ ) { + out.push( roundn( arr[ i ], -2 ) ); + } + + console.log( out.join( '\n' ) ); + ``` + +
+ + + +
+ +## Examples + + + +```javascript +var linspace = require( '@stdlib/array/linspace' ); +var out; + +// Default behavior: +out = linspace( 0, 10 ); +console.log( out.join( '\n' ) ); + +// Specify length: +out = linspace( 0, 10, 10 ); +console.log( out.join( '\n' ) ); + +out = linspace( 0, 10, 11 ); +console.log( out.join( '\n' ) ); + +// Create an array with decremented values: +out = linspace( 10, 0, 11 ); +console.log( out.join( '\n' ) ); +``` + +
+ + + + + + diff --git a/linspace/benchmark/benchmark.js b/linspace/benchmark/benchmark.js new file mode 100644 index 00000000..86a69eb5 --- /dev/null +++ b/linspace/benchmark/benchmark.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var randu = require( '@stdlib/random/base/randu' ); +var isArray = require( '@stdlib/assert/is-array' ); +var pkg = require( './../package.json' ).name; +var linspace = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var x2; + var i; + var v; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + x2 = randu()*100.0; + v = linspace( 0.0, x2 ); + if ( typeof v !== 'object' ) { + b.fail( 'should return an array' ); + } + } + b.toc(); + if ( !isArray( v ) ) { + b.fail( 'should return an array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/linspace/benchmark/benchmark.length.js b/linspace/benchmark/benchmark.length.js new file mode 100644 index 00000000..7bf79fe0 --- /dev/null +++ b/linspace/benchmark/benchmark.length.js @@ -0,0 +1,96 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randu = require( '@stdlib/random/base/randu' ); +var isArray = require( '@stdlib/assert/is-array' ); +var pkg = require( './../package.json' ).name; +var linspace = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var x2; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + x2 = randu() * 10.0; + v = linspace( 0.0, x2, len ); + if ( typeof v !== 'object' ) { + b.fail( 'should return an array' ); + } + } + b.toc(); + if ( !isArray( v ) ) { + b.fail( 'should return an array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':len='+len, f ); + } +} + +main(); diff --git a/linspace/docs/repl.txt b/linspace/docs/repl.txt new file mode 100644 index 00000000..5bceb8c7 --- /dev/null +++ b/linspace/docs/repl.txt @@ -0,0 +1,32 @@ + +{{alias}}( start, stop[, length] ) + Generates a linearly spaced numeric array. + + If a `length` is not provided, the default output array length is `100`. + + The output array is guaranteed to include the `start` and `stop` values. + + Parameters + ---------- + start: number + First array value. + + stop: number + Last array value. + + length: integer (optional) + Length of output array. Default: `100`. + + Returns + ------- + arr: Array + Linearly spaced numeric array. + + Examples + -------- + > var arr = {{alias}}( 0, 100, 6 ) + [ 0, 20, 40, 60, 80, 100 ] + + See Also + -------- + diff --git a/linspace/docs/types/index.d.ts b/linspace/docs/types/index.d.ts new file mode 100644 index 00000000..cf00ef3c --- /dev/null +++ b/linspace/docs/types/index.d.ts @@ -0,0 +1,39 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/** +* Generates a linearly spaced numeric array. +* +* @param x1 - first array value +* @param x2 - last array value +* @param len - length of output array (default: 100) +* @throws third argument must be a nonnegative integer +* @returns linearly spaced numeric array +* +* @example +* var arr = linspace( 0, 100, 6 ); +* // returns [ 0, 20, 40, 60, 80, 100 ] +*/ +declare function linspace( x1: number, x2: number, len?: number ): Array; // tslint-disable-line max-line-length + + +// EXPORTS // + +export = linspace; diff --git a/linspace/docs/types/test.ts b/linspace/docs/types/test.ts new file mode 100644 index 00000000..3789fe23 --- /dev/null +++ b/linspace/docs/types/test.ts @@ -0,0 +1,60 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import linspace = require( './index' ); + + +// TESTS // + +// The function returns an array of numbers... +{ + linspace( 0, 11, 20 ); // $ExpectType number[] + linspace( 0, 10 ); // $ExpectType number[] +} + +// The function does not compile if provided values other than two numbers for the first two parameters... +{ + linspace( true, 10 ); // $ExpectError + linspace( false, 10 ); // $ExpectError + linspace( '5', 10 ); // $ExpectError + linspace( [], 10 ); // $ExpectError + linspace( {}, 10 ); // $ExpectError + linspace( ( x: number ): number => x, 10 ); // $ExpectError + + linspace( 9, true ); // $ExpectError + linspace( 9, false ); // $ExpectError + linspace( 5, '5' ); // $ExpectError + linspace( 8, [] ); // $ExpectError + linspace( 9, {} ); // $ExpectError + linspace( 8, ( x: number ): number => x ); // $ExpectError +} + +// The function does not compile if provided a value other than a number for the third parameter... +{ + linspace( 3, 20, true ); // $ExpectError + linspace( 4, 20, false ); // $ExpectError + linspace( 2, 20, '5' ); // $ExpectError + linspace( 2, 20, [] ); // $ExpectError + linspace( 9, 20, ( x: number ): number => x ); // $ExpectError +} + +// The function does not compile if provided insufficient arguments... +{ + linspace(); // $ExpectError + linspace( 3 ); // $ExpectError +} diff --git a/linspace/examples/index.js b/linspace/examples/index.js new file mode 100644 index 00000000..eacdef56 --- /dev/null +++ b/linspace/examples/index.js @@ -0,0 +1,45 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var linspace = require( './../lib' ); +var out; + +// Default behavior: +console.log( '\nDefault:' ); +out = linspace( 0, 10 ); +console.log( out.join( '\n' ) ); + +// Specify length: +console.log( '\nLength 10:' ); +out = linspace( 0, 10, 10 ); +console.log( out.join( '\n' ) ); + +console.log( '\nLength 11:' ); +out = linspace( 0, 10, 11 ); +console.log( out.join( '\n' ) ); + +console.log( '\nLength 21:' ); +out = linspace( 0, 1, 21 ); +console.log( out.join( '\n' ) ); + +// Create an array with decremented values: +console.log( '\nDecremented values:' ); +out = linspace( 10, 0, 11 ); +console.log( out.join( '\n' ) ); diff --git a/linspace/lib/index.js b/linspace/lib/index.js new file mode 100644 index 00000000..a96f3659 --- /dev/null +++ b/linspace/lib/index.js @@ -0,0 +1,40 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Generate a linearly spaced numeric array. +* +* @module @stdlib/array/linspace +* +* @example +* var linspace = require( '@stdlib/array/linspace' ); +* +* var arr = linspace( 0, 100, 6 ); +* // returns [ 0, 20, 40, 60, 80, 100 ] +*/ + +// MODULES // + +var linspace = require( './linspace.js' ); + + +// EXPORTS // + +module.exports = linspace; diff --git a/linspace/lib/linspace.js b/linspace/lib/linspace.js new file mode 100644 index 00000000..da9c3c21 --- /dev/null +++ b/linspace/lib/linspace.js @@ -0,0 +1,86 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive; +var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; +var isnan = require( '@stdlib/math/base/assert/is-nan' ); + + +// MAIN // + +/** +* Generates a linearly spaced numeric array. +* +* @param {number} x1 - first array value +* @param {number} x2 - last array value +* @param {NonNegativeInteger} [len=100] - length of output array +* @throws {TypeError} first argument must be numeric +* @throws {TypeError} second argument must be numeric +* @throws {TypeError} third argument must be a nonnegative integer +* @returns {Array} linearly spaced numeric array +* +* @example +* var arr = linspace( 0, 100, 6 ); +* // returns [ 0, 20, 40, 60, 80, 100 ] +*/ +function linspace( x1, x2, len ) { + var arr; + var end; + var tmp; + var d; + var i; + if ( !isNumber( x1 ) || isnan( x1 ) ) { + throw new TypeError( 'invalid argument. Start must be numeric. Value: `' + x1 + '`.' ); + } + if ( !isNumber( x2 ) || isnan( x2 ) ) { + throw new TypeError( 'invalid argument. Stop must be numeric. Value: `' + x2 + '`.' ); + } + if ( arguments.length < 3 ) { + len = 100; + } else { + if ( !isNonNegativeInteger( len ) ) { + throw new TypeError( 'invalid argument. Length must be a nonnegative integer. Value: `' + len + '`.' ); + } + if ( len === 0 ) { + return []; + } + } + // Calculate the increment: + end = len - 1; + d = ( x2-x1 ) / end; + + // Build the output array... + arr = []; + tmp = x1; + arr.push( tmp ); + for ( i = 1; i < end; i++ ) { + tmp += d; + arr.push( tmp ); + } + arr.push( x2 ); + return arr; +} + + +// EXPORTS // + +module.exports = linspace; diff --git a/linspace/package.json b/linspace/package.json new file mode 100644 index 00000000..123c9032 --- /dev/null +++ b/linspace/package.json @@ -0,0 +1,63 @@ +{ + "name": "@stdlib/array/linspace", + "version": "0.0.0", + "description": "Generate a linearly spaced numeric array.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdmath", + "utilities", + "utils", + "mathematics", + "math", + "generic", + "array", + "matlab", + "linear", + "linspace" + ] +} diff --git a/linspace/test/test.js b/linspace/test/test.js new file mode 100644 index 00000000..d8006ce9 --- /dev/null +++ b/linspace/test/test.js @@ -0,0 +1,154 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var linspace = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.equal( typeof linspace, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error if the `start` value is not a numeric value', function test( t ) { + var values; + var i; + + values = [ + '5', + null, + true, + undefined, + NaN, + [], + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + linspace( value, 10 ); + }; + } +}); + +tape( 'the function throws an error if the `stop` value is not a numeric value', function test( t ) { + var values; + var i; + + values = [ + '5', + null, + true, + undefined, + NaN, + [], + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + linspace( 0, value ); + }; + } +}); + +tape( 'the function throws an error if the `length` value is not a numeric value', function test( t ) { + var values; + var i; + + values = [ + '5', + null, + true, + undefined, + NaN, + [], + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + linspace( 0, 10, value ); + }; + } +}); + +tape( 'the function returns a linearly spaced array', function test( t ) { + var expected; + var actual; + var start; + var stop; + + start = 0; + stop = 10; + + // Default behavior: + actual = linspace( start, stop ); + t.strictEqual( actual.length, 100 ); + t.strictEqual( actual[0], start ); + t.strictEqual( actual[actual.length-1], 10 ); + + // Specify the length: + actual = linspace( start, stop, 10 ); + t.strictEqual( actual.length, 10 ); + t.strictEqual( actual[0], start ); + t.strictEqual( actual[actual.length-1], 10 ); + + // Verify correct values: + actual = linspace( start, stop, 11 ); + expected = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; + + t.deepEqual( actual, expected ); + + // Decrement: + actual = linspace( stop, start, 11 ); + expected = [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ]; + + t.deepEqual( actual, expected ); + t.end(); +}); + +tape( 'if the length is set to `0`, the function returns an empty array', function test( t ) { + t.deepEqual( linspace(0, 10, 0), [] ); + t.end(); +}); diff --git a/logspace/README.md b/logspace/README.md new file mode 100644 index 00000000..84c7e702 --- /dev/null +++ b/logspace/README.md @@ -0,0 +1,87 @@ + + +# Logspace + +> Generate a logarithmically spaced numeric array. + +
+ +## Usage + +```javascript +var logspace = require( '@stdlib/array/logspace' ); +``` + +#### logspace( a, b\[, length] ) + +Generates a logarithmically spaced numeric `array` between `10^a` and `10^b`. If a `length` is not provided, the default output `array` length is `10`. + +```javascript +var arr = logspace( 0, 2, 6 ); +// returns [ 1, ~2.5, ~6.31, ~15.85, ~39.81, 100 ] +``` + +
+ + + +
+ +## Notes + +- The output `array` includes the values `10^a` and `10^b`. **Beware** of floating point errors, including for the first and last `array` elements. + +
+ + + +
+ +## Examples + + + +```javascript +var logspace = require( '@stdlib/array/logspace' ); +var out; + +// Default behavior: +out = logspace( 0, 3 ); +console.log( out.join( '\n' ) ); + +// Specify length: +out = logspace( 0, 3, 100 ); +console.log( out.join( '\n' ) ); + +// Create an array with decremented values: +out = logspace( 3, 0, 10 ); +console.log( out.join( '\n' ) ); +``` + +
+ + + + + + diff --git a/logspace/benchmark/benchmark.js b/logspace/benchmark/benchmark.js new file mode 100644 index 00000000..3eebc43f --- /dev/null +++ b/logspace/benchmark/benchmark.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var randu = require( '@stdlib/random/base/randu' ); +var isArray = require( '@stdlib/assert/is-array' ); +var pkg = require( './../package.json' ).name; +var logspace = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var x2; + var i; + var v; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + x2 = randu()*100.0; + v = logspace( 0.0, x2 ); + if ( typeof v !== 'object' ) { + b.fail( 'should return an array' ); + } + } + b.toc(); + if ( !isArray( v ) ) { + b.fail( 'should return an array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/logspace/benchmark/benchmark.length.js b/logspace/benchmark/benchmark.length.js new file mode 100644 index 00000000..caff56d5 --- /dev/null +++ b/logspace/benchmark/benchmark.length.js @@ -0,0 +1,96 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randu = require( '@stdlib/random/base/randu' ); +var isArray = require( '@stdlib/assert/is-array' ); +var pkg = require( './../package.json' ).name; +var logspace = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var x2; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + x2 = randu() * 10.0; + v = logspace( 0.0, x2, len ); + if ( typeof v !== 'object' ) { + b.fail( 'should return an array' ); + } + } + b.toc(); + if ( !isArray( v ) ) { + b.fail( 'should return an array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':len='+len, f ); + } +} + +main(); diff --git a/logspace/docs/repl.txt b/logspace/docs/repl.txt new file mode 100644 index 00000000..998aaba1 --- /dev/null +++ b/logspace/docs/repl.txt @@ -0,0 +1,32 @@ + +{{alias}}( a, b[, length] ) + Generates a logarithmically spaced numeric array between `10^a` and `10^b`. + + If a `length` is not provided, the default output array length is `10`. + + The output array includes the values `10^a` and `10^b`. + + Parameters + ---------- + a: number + Exponent of start value. + + b: number + Exponent of end value. + + length: integer (optional) + Length of output array. Default: `10`. + + Returns + ------- + arr: Array + Logarithmically spaced numeric array. + + Examples + -------- + > var arr = {{alias}}( 0, 2, 6 ) + [ 1, ~2.5, ~6.31, ~15.85, ~39.81, 100 ] + + See Also + -------- + diff --git a/logspace/docs/types/index.d.ts b/logspace/docs/types/index.d.ts new file mode 100644 index 00000000..8ef2deb9 --- /dev/null +++ b/logspace/docs/types/index.d.ts @@ -0,0 +1,39 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/** +* Generates a logarithmically spaced numeric array. +* +* @param a - exponent of start value +* @param b - exponent of end value +* @param len - length of output array (default: 10) +* @throws third argument must be a nonnegative integer +* @returns logarithmically spaced numeric array +* +* @example +* var arr = logspace( 0, 2, 6 ); +* // returns [ 1, ~2.5, ~6.31, ~15.85, ~39.81, 100 ] +*/ +declare function logspace( x1: number, x2: number, len?: number ): Array; // tslint-disable-line max-line-length + + +// EXPORTS // + +export = logspace; diff --git a/logspace/docs/types/test.ts b/logspace/docs/types/test.ts new file mode 100644 index 00000000..5d2908ee --- /dev/null +++ b/logspace/docs/types/test.ts @@ -0,0 +1,60 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import logspace = require( './index' ); + + +// TESTS // + +// The function returns an array of numbers... +{ + logspace( 0, 11, 20 ); // $ExpectType number[] + logspace( 0, 10 ); // $ExpectType number[] +} + +// The function does not compile if provided values other than two numbers for the first two parameters... +{ + logspace( true, 10 ); // $ExpectError + logspace( false, 10 ); // $ExpectError + logspace( '5', 10 ); // $ExpectError + logspace( [], 10 ); // $ExpectError + logspace( {}, 10 ); // $ExpectError + logspace( ( x: number ): number => x, 10 ); // $ExpectError + + logspace( 9, true ); // $ExpectError + logspace( 9, false ); // $ExpectError + logspace( 5, '5' ); // $ExpectError + logspace( 8, [] ); // $ExpectError + logspace( 9, {} ); // $ExpectError + logspace( 8, ( x: number ): number => x ); // $ExpectError +} + +// The function does not compile if provided a value other than a number for the third parameter... +{ + logspace( 3, 20, true ); // $ExpectError + logspace( 4, 20, false ); // $ExpectError + logspace( 2, 20, '5' ); // $ExpectError + logspace( 2, 20, [] ); // $ExpectError + logspace( 9, 20, ( x: number ): number => x ); // $ExpectError +} + +// The function does not compile if provided insufficient arguments... +{ + logspace(); // $ExpectError + logspace( 3 ); // $ExpectError +} diff --git a/logspace/examples/index.js b/logspace/examples/index.js new file mode 100644 index 00000000..47be033d --- /dev/null +++ b/logspace/examples/index.js @@ -0,0 +1,37 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var logspace = require( './../lib' ); +var out; + +// Default behavior: +console.log( '\nDefault:' ); +out = logspace( 0, 3 ); +console.log( out.join( '\n' ) ); + +// Specify length: +console.log( '\nLength 100:' ); +out = logspace( 0, 3, 100 ); +console.log( out.join( '\n' ) ); + +// Create an array with decremented values: +console.log( '\nDecremented:' ); +out = logspace( 3, 0, 10 ); +console.log( out.join( '\n' ) ); diff --git a/logspace/lib/index.js b/logspace/lib/index.js new file mode 100644 index 00000000..e7ebad9e --- /dev/null +++ b/logspace/lib/index.js @@ -0,0 +1,40 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Generate a logarithmically spaced numeric array. +* +* @module @stdlib/array/logspace +* +* @example +* var logspace = require( '@stdlib/array/logspace' ); +* +* var arr = logspace( 0, 2, 6 ); +* // returns [ 1, ~2.5, ~6.31, ~15.85, ~39.81, 100 ] +*/ + +// MODULES // + +var logspace = require( './logspace.js' ); + + +// EXPORTS // + +module.exports = logspace; diff --git a/logspace/lib/logspace.js b/logspace/lib/logspace.js new file mode 100644 index 00000000..a2deec86 --- /dev/null +++ b/logspace/lib/logspace.js @@ -0,0 +1,87 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var pow = require( '@stdlib/math/base/special/pow' ); +var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive; +var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; +var isnan = require( '@stdlib/math/base/assert/is-nan' ); + + +// MAIN // + +/** +* Generates a logarithmically spaced numeric array. +* +* @param {number} a - exponent of start value +* @param {number} b - exponent of end value +* @param {NonNegativeInteger} [len=10] - length of output array +* @throws {TypeError} first argument must be numeric +* @throws {TypeError} second argument must be numeric +* @throws {TypeError} third argument must be a nonnegative integer +* @returns {Array} logarithmically spaced numeric array +* +* @example +* var arr = logspace( 0, 2, 6 ); +* // returns [ 1, ~2.5, ~6.31, ~15.85, ~39.81, 100 ] +*/ +function logspace( a, b, len ) { + var arr; + var end; + var tmp; + var d; + var i; + if ( !isNumber( a ) || isnan( a ) ) { + throw new TypeError( 'invalid argument. Exponent of start value must be numeric. Value: `' + a + '`.' ); + } + if ( !isNumber( b ) || isnan( b ) ) { + throw new TypeError( 'invalid argument. Exponent of stop value must be numeric. Value: `' + b + '`.' ); + } + if ( arguments.length < 3 ) { + len = 10; + } else { + if ( !isNonNegativeInteger( len ) ) { + throw new TypeError( 'invalid argument. Length must be a nonnegative integer. Value: `' + len + '`.' ); + } + if ( len === 0 ) { + return []; + } + } + // Calculate the increment: + end = len - 1; + d = ( b-a ) / end; + + // Build the output array... + arr = []; + tmp = a; + arr.push( pow( 10, tmp ) ); + for ( i = 1; i < end; i++ ) { + tmp += d; + arr.push( pow( 10, tmp ) ); + } + arr.push( pow( 10, b ) ); + return arr; +} + + +// EXPORTS // + +module.exports = logspace; diff --git a/logspace/package.json b/logspace/package.json new file mode 100644 index 00000000..c1686865 --- /dev/null +++ b/logspace/package.json @@ -0,0 +1,64 @@ +{ + "name": "@stdlib/array/logspace", + "version": "0.0.0", + "description": "Generate a logarithmically spaced numeric array.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdmath", + "mathematics", + "math", + "utilities", + "utils", + "generic", + "array", + "matlab", + "linear", + "log", + "logarithmic" + ] +} diff --git a/logspace/test/test.js b/logspace/test/test.js new file mode 100644 index 00000000..e0246250 --- /dev/null +++ b/logspace/test/test.js @@ -0,0 +1,154 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var logspace = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.equal( typeof logspace, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error if the first argument is not a numeric value', function test( t ) { + var values; + var i; + + values = [ + '5', + null, + true, + undefined, + NaN, + [], + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + logspace( value, 10 ); + }; + } +}); + +tape( 'the function throws an error if the second argument is not a numeric value', function test( t ) { + var values; + var i; + + values = [ + '5', + null, + true, + undefined, + NaN, + [], + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + logspace( 0, value ); + }; + } +}); + +tape( 'the function throws an error if the `length` value is not a numeric value', function test( t ) { + var values; + var i; + + values = [ + '5', + null, + true, + undefined, + NaN, + [], + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + logspace( 0, 10, value ); + }; + } +}); + +tape( 'the function returns a logarithmically spaced array', function test( t ) { + var expected; + var actual; + var a; + var b; + + a = 0; + b = 3; + + // Default behavior: + actual = logspace( a, b ); + t.strictEqual( actual.length, 10 ); + t.strictEqual( actual[0], 1 ); + t.strictEqual( actual[actual.length-1], 1000 ); + + // Specify the length: + actual = logspace( a, b, 10 ); + t.strictEqual( actual.length, 10 ); + t.strictEqual( actual[0], 1 ); + t.strictEqual( actual[actual.length-1], 1000 ); + + // Verify correct values: + actual = logspace( a, b, 4 ); + expected = [ 1, 10, 100, 1000 ]; + + t.deepEqual( actual, expected ); + + // Decrement: + actual = logspace( b, a, 4 ); + expected = [ 1000, 100, 10, 1 ]; + + t.deepEqual( actual, expected ); + t.end(); +}); + +tape( 'if the length is set to `0`, the function returns an empty array', function test( t ) { + t.deepEqual( logspace(0, 10, 0), [] ); + t.end(); +}); diff --git a/min-dtype/README.md b/min-dtype/README.md new file mode 100644 index 00000000..6c50fe85 --- /dev/null +++ b/min-dtype/README.md @@ -0,0 +1,128 @@ + + +# Minimum Data Type + +> Determine the minimum array [data type][@stdlib/array/dtypes] of the closest "kind" necessary for storing a provided scalar value. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var minDataType = require( '@stdlib/array/min-dtype' ); +``` + +#### minDataType( value ) + +Returns the minimum array [data type][@stdlib/array/dtypes] of the closest "kind" necessary for storing a provided scalar value. + +```javascript +var dt = minDataType( 3.141592653589793 ); +// returns 'float32' + +dt = minDataType( -3 ); +// returns 'int8' + +dt = minDataType( 3 ); +// returns 'uint8' + +dt = minDataType( '3' ); +// returns 'generic' +``` + +
+ + + + + +
+ +## Notes + +- The function does **not** provide precision guarantees for non-integer-valued real numbers. In other words, the function returns the smallest possible floating-point (i.e., inexact) [data type][@stdlib/array/dtypes] for storing numbers having decimals. + +
+ + + + + +
+ +## Examples + + + +```javascript +var roundn = require( '@stdlib/math/base/special/roundn' ); +var randu = require( '@stdlib/random/base/randu' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var discreteUniform = require( '@stdlib/random/base/discrete-uniform' ); +var minDataType = require( '@stdlib/array/min-dtype' ); + +var dt; +var v; +var i; + +// Generate numbers of varying magnitudes and determine the minimum data type for each value... +for ( i = 0; i < 100; i++ ) { + v = randu() * pow( 2.0, discreteUniform( 0, 40 ) ); + if ( randu() < 0.5 ) { + v *= -1; + } + v = roundn( v, discreteUniform( -1, 0 ) ); + dt = minDataType( v ); + console.log( 'min(%d) => %s', v, dt ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/min-dtype/benchmark/benchmark.js b/min-dtype/benchmark/benchmark.js new file mode 100644 index 00000000..d2a78a5b --- /dev/null +++ b/min-dtype/benchmark/benchmark.js @@ -0,0 +1,61 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isString = require( '@stdlib/assert/is-string' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var minDataType = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var values; + var out; + var N; + var i; + + values = [ + -0.0, + 3.14, + 3.0, + -3.0, + 1.0e308, + 3.14e37, + NaN + ]; + N = values.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = minDataType( values[ i%N ] ); + if ( typeof out !== 'string' || out === 'generic' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( !isString( out ) || out === 'generic' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/min-dtype/benchmark/python/numpy/benchmark.py b/min-dtype/benchmark/python/numpy/benchmark.py new file mode 100644 index 00000000..5e5718e5 --- /dev/null +++ b/min-dtype/benchmark/python/numpy/benchmark.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python +# +# @license Apache-2.0 +# +# Copyright (c) 2018 The Stdlib Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Benchmark numpy.min_scalar_type.""" + +from __future__ import print_function +import timeit + +NAME = "min-dtype" +REPEATS = 3 +ITERATIONS = 1000000 + + +def print_version(): + """Print the TAP version.""" + print("TAP version 13") + + +def print_summary(total, passing): + """Print the benchmark summary. + + # Arguments + + * `total`: total number of tests + * `passing`: number of passing tests + + """ + print("#") + print("1.." + str(total)) # TAP plan + print("# total " + str(total)) + print("# pass " + str(passing)) + print("#") + print("# ok") + + +def print_results(elapsed): + """Print benchmark results. + + # Arguments + + * `elapsed`: elapsed time (in seconds) + + # Examples + + ``` python + python> print_results(0.131009101868) + ``` + """ + rate = ITERATIONS / elapsed + + print(" ---") + print(" iterations: " + str(ITERATIONS)) + print(" elapsed: " + str(elapsed)) + print(" rate: " + str(rate)) + print(" ...") + + +def benchmark(): + """Run the benchmark and print benchmark results.""" + setup = "import numpy as np; from random import random;" + stmt = "y = np.min_scalar_type(random()*1000.0)" + + t = timeit.Timer(stmt, setup=setup) + + print_version() + + for i in range(REPEATS): + print("# python::numpy::" + NAME) + elapsed = t.timeit(number=ITERATIONS) + print_results(elapsed) + print("ok " + str(i+1) + " benchmark finished") + + print_summary(REPEATS, REPEATS) + + +def main(): + """Run the benchmark.""" + benchmark() + + +if __name__ == "__main__": + main() diff --git a/min-dtype/docs/repl.txt b/min-dtype/docs/repl.txt new file mode 100644 index 00000000..bc72a8d1 --- /dev/null +++ b/min-dtype/docs/repl.txt @@ -0,0 +1,34 @@ + +{{alias}}( value ) + Returns the minimum array data type of the closest "kind" necessary for + storing a provided scalar value. + + The function does *not* provide precision guarantees for non-integer-valued + real numbers. In other words, the function returns the smallest possible + floating-point (i.e., inexact) data type for storing numbers having + decimals. + + Parameters + ---------- + value: any + Scalar value. + + Returns + ------- + dt: string + Array data type. + + Examples + -------- + > var dt = {{alias}}( 3.141592653589793 ) + 'float32' + > dt = {{alias}}( 3 ) + 'uint8' + > dt = {{alias}}( -3 ) + 'int8' + > dt = {{alias}}( '-3' ) + 'generic' + + See Also + -------- + diff --git a/min-dtype/docs/types/index.d.ts b/min-dtype/docs/types/index.d.ts new file mode 100644 index 00000000..57a9ef00 --- /dev/null +++ b/min-dtype/docs/types/index.d.ts @@ -0,0 +1,44 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/** +* Returns the minimum array data type of the closest "kind" necessary for storing a provided scalar value. +* +* ## Notes +* +* - The function does *not* provide precision guarantees for non-integer-valued real numbers. In other words, the function returns the smallest possible floating-point (i.e., inexact) data type for storing numbers having decimals. +* +* @param value - scalar value +* @returns array data type +* +* @example +* var dt = minDataType( 3.141592653589793 ); +* // returns 'float32' +* +* @example +* var dt = minDataType( 3 ); +* // returns 'uint8' +*/ +declare function minDataType( value: any ): string; + + +// EXPORTS // + +export = minDataType; diff --git a/min-dtype/docs/types/test.ts b/min-dtype/docs/types/test.ts new file mode 100644 index 00000000..a6499525 --- /dev/null +++ b/min-dtype/docs/types/test.ts @@ -0,0 +1,32 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import minDataType = require( './index' ); + +// TESTS // + +// The function returns a string.. +{ + minDataType( 2.13 ); // $ExpectType string +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + minDataType(); // $ExpectError + minDataType( [ 1, 2, 3 ], 3 ); // $ExpectError +} diff --git a/min-dtype/examples/index.js b/min-dtype/examples/index.js new file mode 100644 index 00000000..d3254b8c --- /dev/null +++ b/min-dtype/examples/index.js @@ -0,0 +1,40 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var roundn = require( '@stdlib/math/base/special/roundn' ); +var randu = require( '@stdlib/random/base/randu' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var discreteUniform = require( '@stdlib/random/base/discrete-uniform' ); +var minDataType = require( './../lib' ); + +var dt; +var v; +var i; + +// Generate numbers of varying magnitudes and determine the minimum data type for each value... +for ( i = 0; i < 100; i++ ) { + v = randu() * pow( 2.0, discreteUniform( 0, 40 ) ); + if ( randu() < 0.5 ) { + v *= -1; + } + v = roundn( v, discreteUniform( -1, 0 ) ); + dt = minDataType( v ); + console.log( 'min(%d) => %s', v, dt ); +} diff --git a/min-dtype/lib/index.js b/min-dtype/lib/index.js new file mode 100644 index 00000000..c81b6d32 --- /dev/null +++ b/min-dtype/lib/index.js @@ -0,0 +1,43 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Determine the minimum array data type of the closest "kind" necessary for storing a provided scalar value. +* +* @module @stdlib/array/min-dtype +* +* @example +* var minDataType = require( '@stdlib/array/min-dtype' ); +* +* var dt = minDataType( 3.141592653589793 ); +* // returns 'float32' +* +* dt = minDataType( 3 ); +* // returns 'uint8' +*/ + +// MODULES // + +var minDataType = require( './main.js' ); + + +// EXPORTS // + +module.exports = minDataType; diff --git a/min-dtype/lib/main.js b/min-dtype/lib/main.js new file mode 100644 index 00000000..3b665bdc --- /dev/null +++ b/min-dtype/lib/main.js @@ -0,0 +1,100 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isInteger = require( '@stdlib/math/base/assert/is-integer' ); +var isNegativeZero = require( '@stdlib/math/base/assert/is-negative-zero' ); +var PINF = require( '@stdlib/constants/float64/pinf' ); +var NINF = require( '@stdlib/constants/float64/ninf' ); +var FLOAT32_SMALLEST_SUBNORMAL = require( '@stdlib/constants/float32/smallest-subnormal' ); // eslint-disable-line id-length +var INT8_MIN = require( '@stdlib/constants/int8/min' ); +var INT16_MIN = require( '@stdlib/constants/int16/min' ); +var INT32_MIN = require( '@stdlib/constants/int32/min' ); +var UINT8_MAX = require( '@stdlib/constants/uint8/max' ); +var UINT16_MAX = require( '@stdlib/constants/uint16/max' ); +var UINT32_MAX = require( '@stdlib/constants/uint32/max' ); + + +// MAIN // + +/** +* Returns the minimum array data type of the closest "kind" necessary for storing a provided scalar value. +* +* @param {*} value - scalar value +* @returns {string} array data type +* +* @example +* var dt = minDataType( 3.141592653589793 ); +* // returns 'float32' +* +* @example +* var dt = minDataType( 3 ); +* // returns 'uint8' +*/ +function minDataType( value ) { + if ( typeof value !== 'number' ) { + return 'generic'; + } + if ( value !== value || value === PINF || value === NINF ) { + return 'float32'; + } + if ( isInteger( value ) ) { + if ( value === 0 && isNegativeZero( value ) ) { + return 'float32'; + } + if ( value < 0 ) { + if ( value >= INT8_MIN ) { + return 'int8'; + } + if ( value >= INT16_MIN ) { + return 'int16'; + } + if ( value >= INT32_MIN ) { + return 'int32'; + } + return 'float64'; + } + if ( value <= UINT8_MAX ) { + return 'uint8'; + } + if ( value <= UINT16_MAX ) { + return 'uint16'; + } + if ( value <= UINT32_MAX ) { + return 'uint32'; + } + return 'float64'; + } + // Assume that if we are provided a tiny value, we don't want to underflow to zero by storing as `float32`... + if ( + value > -FLOAT32_SMALLEST_SUBNORMAL && + value < FLOAT32_SMALLEST_SUBNORMAL + ) { + return 'float64'; + } + // Any number which reaches this point is less than the maximum single-precision floating-point number, as floating-point format supports a limited number of decimals (e.g., (1.0+EPS)*10**15 => 1000000000000000.2, which is less than ~3.4e38)... + return 'float32'; +} + + +// EXPORTS // + +module.exports = minDataType; diff --git a/min-dtype/package.json b/min-dtype/package.json new file mode 100644 index 00000000..d14b50df --- /dev/null +++ b/min-dtype/package.json @@ -0,0 +1,67 @@ +{ + "name": "@stdlib/array/min-dtype", + "version": "0.0.0", + "description": "Determine the minimum array data type of the closest kind necessary for storing a provided scalar value.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "array", + "scalar", + "type", + "memory", + "minimum", + "dtype", + "utilities", + "utility", + "utils", + "util" + ], + "__stdlib__": {} +} diff --git a/min-dtype/test/test.js b/min-dtype/test/test.js new file mode 100644 index 00000000..8ba7b683 --- /dev/null +++ b/min-dtype/test/test.js @@ -0,0 +1,102 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var PINF = require( '@stdlib/constants/float64/pinf' ); +var NINF = require( '@stdlib/constants/float64/ninf' ); +var minDataType = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof minDataType, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function returns the minimum array data type of the closest "kind" necessary for storing a provided scalar value', function test( t ) { + var expected; + var actual; + var values; + var i; + + values = [ + NaN, + 0, + 0.0, + -0.0, + 1, + -1, + 300, // >2**8 + -300, + 65537, // >2**16 + -65537, + 4294967297, // >2**32 + -4294967297, + 3.14, + -3.14, + 1.0e40, // >10**38 + -1.0e40, + -1.0e-46, // <10**-45 + 1.0e-46, + PINF, + NINF, + 'beep', + {}, + true, + false, + [] + ]; + expected = [ + 'float32', + 'uint8', + 'uint8', + 'float32', + 'uint8', + 'int8', + 'uint16', + 'int16', + 'uint32', + 'int32', + 'float64', + 'float64', + 'float32', + 'float32', + 'float64', + 'float64', + 'float64', + 'float64', + 'float32', + 'float32', + 'generic', + 'generic', + 'generic', + 'generic', + 'generic' + ]; + for ( i = 0; i < values.length; i++ ) { + actual = minDataType( values[i] ); + t.strictEqual( actual, expected[ i ], 'returns expected value when provided '+values[i] ); + } + t.end(); +}); diff --git a/next-dtype/README.md b/next-dtype/README.md new file mode 100644 index 00000000..1df79cd7 --- /dev/null +++ b/next-dtype/README.md @@ -0,0 +1,131 @@ + + +# Next Data Type + +> Return the next larger array [data type][@stdlib/array/dtypes] of the same kind. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var nextDataType = require( '@stdlib/array/next-dtype' ); +``` + +#### nextDataType( \[dtype] ) + +If provided a `dtype` argument, returns the next larger array [data type][@stdlib/array/dtypes] of the same kind. + +```javascript +var out = nextDataType( 'float32' ); +// returns 'float64' +``` + +If a [data type][@stdlib/array/dtypes] does not have a next larger [data type][@stdlib/array/dtypes] or the next larger data type is not supported, the function returns `-1`. + +```javascript +var out = nextDataType( 'float64' ); +// returns -1 +``` + +If not provided a `dtype` argument, the function returns a table. + +```javascript +var out = nextDataType(); +// returns {...} +``` + +If provided an unrecognized or unsupported `dtype`, the function returns `null`. + +```javascript +var out = nextDataType( 'foo' ); +// returns null +``` + +
+ + + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var dtypes = require( '@stdlib/array/dtypes' ); +var nextDataType = require( '@stdlib/array/next-dtype' ); + +var DTYPES; +var dt; +var i; + +// Get the list of supported array data types: +DTYPES = dtypes(); + +// Print the next larger data type for each supported data type... +for ( i = 0; i < DTYPES.length; i++ ) { + dt = nextDataType( DTYPES[ i ] ); + console.log( '%s => %s', DTYPES[ i ], dt ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/next-dtype/benchmark/benchmark.js b/next-dtype/benchmark/benchmark.js new file mode 100644 index 00000000..87a8c4b8 --- /dev/null +++ b/next-dtype/benchmark/benchmark.js @@ -0,0 +1,71 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isString = require( '@stdlib/assert/is-string' ).isPrimitive; +var dtypes = require( '@stdlib/array/dtypes' ); +var pkg = require( './../package.json' ).name; +var nextDataType = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = nextDataType(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::dtype', function benchmark( b ) { + var out; + var dt; + var i; + + dt = dtypes(); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = nextDataType( dt[ i%dt.length ] ); + if ( typeof out !== 'string' && out !== -1 ) { + b.fail( 'should return a string or -1' ); + } + } + b.toc(); + if ( !isString( out ) && out !== -1 ) { + b.fail( 'should return a string or -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/next-dtype/docs/repl.txt b/next-dtype/docs/repl.txt new file mode 100644 index 00000000..bbd3535e --- /dev/null +++ b/next-dtype/docs/repl.txt @@ -0,0 +1,29 @@ + +{{alias}}( [dtype] ) + Returns the next larger array data type of the same kind. + + If not provided a data type, the function returns a table. + + If a data type does not have a next larger data type or the next larger type + is not supported, the function returns `-1`. + + If provided an unrecognized data type, the function returns `null`. + + Parameters + ---------- + dtype: string (optional) + Array data type. + + Returns + ------- + out: Object|string|integer|null + Next larger type(s). + + Examples + -------- + > var out = {{alias}}( 'float32' ) + 'float64' + + See Also + -------- + diff --git a/next-dtype/docs/types/index.d.ts b/next-dtype/docs/types/index.d.ts new file mode 100644 index 00000000..f3b2b140 --- /dev/null +++ b/next-dtype/docs/types/index.d.ts @@ -0,0 +1,42 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/** +* Returns the next larger array data type of the same kind. +* +* ## Notes +* +* - If not provided a data type, the function returns a table. +* - If a data type does not have a next larger data type or the next larger type is not supported, the function returns `-1`. +* - If provided an unrecognized data type, the function returns `null`. +* +* @param dtype - array data type +* @returns next larger data type(s) or null +* +* @example +* var dt = nextDataType( 'float32' ); +* // returns 'float64' +*/ +declare function nextDataType( dtype?: string ): Object | Array | null; + + +// EXPORTS // + +export = nextDataType; diff --git a/next-dtype/docs/types/test.ts b/next-dtype/docs/types/test.ts new file mode 100644 index 00000000..eacd4d7a --- /dev/null +++ b/next-dtype/docs/types/test.ts @@ -0,0 +1,42 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import nextDataType = require( './index' ); + +// TESTS // + +// The function returns a string array, object, or null.. +{ + nextDataType(); // $ExpectType Object | string[] | null + nextDataType( 'float32' ); // $ExpectType Object | string[] | null +} + +// The compiler throws an error if the function is provided a first argument which is not a string... +{ + nextDataType( 123 ); // $ExpectError + nextDataType( true ); // $ExpectError + nextDataType( false ); // $ExpectError + nextDataType( {} ); // $ExpectError + nextDataType( [] ); // $ExpectError + nextDataType( null ); // $ExpectError +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + nextDataType( 'float32', 3 ); // $ExpectError +} diff --git a/next-dtype/examples/index.js b/next-dtype/examples/index.js new file mode 100644 index 00000000..05c754db --- /dev/null +++ b/next-dtype/examples/index.js @@ -0,0 +1,35 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var dtypes = require( '@stdlib/array/dtypes' ); +var nextDataType = require( './../lib' ); + +var DTYPES; +var dt; +var i; + +// Get the list of supported array data types: +DTYPES = dtypes(); + +// Print the next larger data type for each supported data type... +for ( i = 0; i < DTYPES.length; i++ ) { + dt = nextDataType( DTYPES[ i ] ); + console.log( '%s => %s', DTYPES[ i ], dt ); +} diff --git a/next-dtype/lib/index.js b/next-dtype/lib/index.js new file mode 100644 index 00000000..fc66f3a2 --- /dev/null +++ b/next-dtype/lib/index.js @@ -0,0 +1,40 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Return the next larger array data type of the same kind. +* +* @module @stdlib/array/next-dtype +* +* @example +* var nextDataType = require( '@stdlib/array/next-dtype' ); +* +* var dt = nextDataType( 'float32' ); +* // returns 'float64' +*/ + +// MODULES // + +var nextDataType = require( './main.js' ); + + +// EXPORTS // + +module.exports = nextDataType; diff --git a/next-dtype/lib/main.js b/next-dtype/lib/main.js new file mode 100644 index 00000000..e31af2b1 --- /dev/null +++ b/next-dtype/lib/main.js @@ -0,0 +1,77 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var objectKeys = require( '@stdlib/utils/keys' ); +var hasOwnProp = require( '@stdlib/assert/has-own-property' ); +var NEXT_DTYPES = require( './next_dtypes.json' ); + + +// FUNCTIONS // + +/** +* Generates a table. +* +* @private +* @returns {Object} table +*/ +function generateTable() { + var dtypes; + var ntypes; + var out; + var i; + + out = {}; + dtypes = objectKeys( NEXT_DTYPES ); + ntypes = dtypes.length; + for ( i = 0; i < ntypes; i++ ) { + out[ dtypes[i] ] = NEXT_DTYPES[ dtypes[i] ]; + } + return out; +} + + +// MAIN // + +/** +* Returns the next larger array data type of the same kind. +* +* @param {string} [dtype] - array data type +* @returns {(Object|string|integer|null)} next larger data type(s) or null +* +* @example +* var dt = nextDataType( 'float32' ); +* // returns 'float64' +*/ +function nextDataType( dtype ) { + if ( arguments.length === 0 ) { + return generateTable(); + } + if ( hasOwnProp( NEXT_DTYPES, dtype ) ) { + return NEXT_DTYPES[ dtype ]; + } + return null; +} + + +// EXPORTS // + +module.exports = nextDataType; diff --git a/next-dtype/lib/next_dtypes.json b/next-dtype/lib/next_dtypes.json new file mode 100644 index 00000000..752bc432 --- /dev/null +++ b/next-dtype/lib/next_dtypes.json @@ -0,0 +1,12 @@ +{ + "float64": -1, + "float32": "float64", + "int32": -1, + "int16": "int32", + "int8": "int16", + "uint32": -1, + "uint16": "uint32", + "uint8": "uint16", + "uint8c": "uint16", + "generic": -1 +} diff --git a/next-dtype/package.json b/next-dtype/package.json new file mode 100644 index 00000000..6cfd7824 --- /dev/null +++ b/next-dtype/package.json @@ -0,0 +1,66 @@ +{ + "name": "@stdlib/array/next-dtype", + "version": "0.0.0", + "description": "Return the next larger array data type of the same kind.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "array", + "casting", + "cast", + "rules", + "promotion", + "utilities", + "utility", + "utils", + "util" + ], + "__stdlib__": {} +} diff --git a/next-dtype/test/test.js b/next-dtype/test/test.js new file mode 100644 index 00000000..e231464b --- /dev/null +++ b/next-dtype/test/test.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var dtypes = require( '@stdlib/array/dtypes' ); +var nextDataType = require( './../lib' ); + + +// VARIABLES // + +var DTYPES = dtypes(); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof nextDataType, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'if not provided a data type, the function returns a table', function test( t ) { + var out = nextDataType(); + t.strictEqual( typeof out, 'object', 'returns an object' ); + t.strictEqual( out[ 'float32' ], 'float64', 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns the next larger array data type of the same kind', function test( t ) { + var table; + var out; + var dt; + var i; + + table = nextDataType(); + + for ( i = 0; i < DTYPES.length; i++ ) { + dt = DTYPES[ i ]; + out = nextDataType( dt ); + t.strictEqual( out, table[ dt ], 'returns expected value when provided '+dt ); + } + t.end(); +}); + +tape( 'if provided an unrecognized or unsupported data type, the function returns `null`', function test( t ) { + var values; + var i; + + values = [ + 'beep', + 'boop', + 'foo', + 'bar', + true, + false + ]; + for ( i = 0; i < values.length; i++ ) { + t.strictEqual( nextDataType( values[ i ] ), null, 'returns expected value when provided '+values[ i ] ); + } + t.end(); +}); diff --git a/package.json b/package.json new file mode 100644 index 00000000..2d1b34ca --- /dev/null +++ b/package.json @@ -0,0 +1,95 @@ +{ + "name": "@stdlib/array", + "version": "0.0.0", + "description": "Arrays.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "lib/index.js", + "directories": { + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": { + "test": "tape $(find . -type d -name test -exec grep -irl --include=\\*.js tape {} +) | tap-spec", + "test-cov": "istanbul cover --dir ./reports/coverage --report lcov tape -- $(find . -type d -name test -exec grep -irl --include=\\*.js tape {} +)", + "examples": "find examples/** -name \"*.js\" ! -path \"examples/fixtures/**\" | while read -r file; do echo \"\"; echo \"Running example: $file\"; node $file || exit 1; done" + }, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/array.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": { + "@stdlib/assert": "^0.0.x", + "@stdlib/blas": "^0.0.x", + "@stdlib/complex": "^0.0.x", + "@stdlib/constants": "^0.0.x", + "@stdlib/math": "^0.0.x", + "@stdlib/symbol": "^0.0.x", + "@stdlib/types": "^0.0.x", + "@stdlib/utils": "^0.0.x" + }, + "devDependencies": { + "@stdlib/bench": "^0.0.x", + "@stdlib/buffer": "^0.0.x", + "@stdlib/iter": "^0.0.x", + "@stdlib/number": "^0.0.x", + "@stdlib/process": "^0.0.x", + "@stdlib/random": "^0.0.x", + "proxyquire": "^2.0.0", + "tape": "git+https://github.com/kgryte/tape.git#fix/globby", + "istanbul": "^0.4.1", + "tap-spec": "5.x.x" + }, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structures", + "typed", + "arrays", + "array", + "typed-array", + "typed array", + "vector", + "matrix", + "ndarray", + "buffer", + "namespace", + "ns" + ], + "funding": { + "type": "patreon", + "url": "https://www.patreon.com/athan" + } +} diff --git a/pool/README.md b/pool/README.md new file mode 100644 index 00000000..8c170203 --- /dev/null +++ b/pool/README.md @@ -0,0 +1,450 @@ + + +# Typed Array Pool + +> Allocate typed arrays from a typed array memory pool. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var typedarraypool = require( '@stdlib/array/pool' ); +``` + +#### typedarraypool( \[dtype] ) + +Returns an **uninitialized** [typed array][mdn-typed-array] having a specified data type `dtype`. + +```javascript +var arr = typedarraypool(); +// returns [] + +// ... + +typedarraypool.free( arr ); +``` + +The function recognizes the following data types: + +- `float64`: double-precision floating-point numbers (IEEE 754) +- `float32`: single-precision floating-point numbers (IEEE 754) +- `int32`: 32-bit two's complement signed integers +- `uint32`: 32-bit unsigned integers +- `int16`: 16-bit two's complement signed integers +- `uint16`: 16-bit unsigned integers +- `int8`: 8-bit two's complement signed integers +- `uint8`: 8-bit unsigned integers +- `uint8c`: 8-bit unsigned integers clamped to `0-255` + +By default, the output [typed array][mdn-typed-array] is `float64`. To specify an alternative data type, set the `dtype` parameter. + +```javascript +var arr = typedarraypool( 'int32' ); +// returns [] + +// ... + +typedarraypool.free( arr ); +``` + +#### typedarraypool( length\[, dtype] ) + +Returns an **uninitialized** [typed array][mdn-typed-array] having a specified `length` from a [typed array][mdn-typed-array] memory pool. + +```javascript +var arr1 = typedarraypool( 5 ); +// returns + +var arr2 = typedarraypool( 5, 'uint8' ); +// returns + +// ... + +typedarraypool.free( arr1 ); +typedarraypool.free( arr2 ); +``` + +#### typedarraypool( typedarray\[, dtype] ) + +Returns a pooled [typed array][mdn-typed-array] from another [typed array][mdn-typed-array]. + +```javascript +var arr1 = typedarraypool( [ 5.0, -3.0, 2.0 ] ); +// returns [ 5.0, -3.0, 2.0 ] + +var arr2 = typedarraypool( arr1 ); +// returns [ 5.0, -3.0, 2.0 ] + +var arr3 = typedarraypool( arr1, 'int32' ); +// returns [ 5, -3, 2 ] + +// ... + +typedarraypool.free( arr1 ); +typedarraypool.free( arr2 ); +typedarraypool.free( arr3 ); +``` + +#### typedarraypool( obj\[, dtype] ) + +Returns a pooled [typed array][mdn-typed-array] from an array-like `object`. + +```javascript +var arr1 = typedarraypool( [ 0.5, 0.5, 0.5 ] ); +// returns [ 0.5, 0.5, 0.5 ] + +var arr2 = typedarraypool( [ 0.5, 0.5, 0.5 ], 'float32' ); +// returns [ 0.5, 0.5, 0.5 ] + +// ... + +typedarraypool.free( arr1 ); +typedarraypool.free( arr2 ); +``` + +#### typedarraypool.malloc( \[dtype] ) + +Returns an **uninitialized** [typed array][mdn-typed-array] having a specified data type `dtype`. + +```javascript +var arr1 = typedarraypool.malloc(); +// returns [] + +var arr2 = typedarraypool.malloc( 'int32' ); +// returns [] + +// ... + +typedarraypool.free( arr1 ); +typedarraypool.free( arr2 ); +``` + +#### typedarraypool.malloc( length\[, dtype] ) + +Returns an **uninitialized** [typed array][mdn-typed-array] having a specified `length` from a [typed array][mdn-typed-array] memory pool. + +```javascript +var arr1 = typedarraypool.malloc( 5 ); +// returns + +var arr2 = typedarraypool.malloc( 5, 'uint8' ); +// returns + +// ... + +typedarraypool.free( arr1 ); +typedarraypool.free( arr2 ); +``` + +#### typedarraypool.malloc( typedarray\[, dtype] ) + +Returns a pooled [typed array][mdn-typed-array] from another [typed array][mdn-typed-array]. + +```javascript +var arr1 = typedarraypool.malloc( [ 5.0, -3.0, 2.0 ] ); +// returns [ 5.0, -3.0, 2.0 ] + +var arr2 = typedarraypool.malloc( arr1 ); +// returns [ 5.0, -3.0, 2.0 ] + +var arr3 = typedarraypool.malloc( arr1, 'int32' ); +// returns [ 5, -3, 2 ] + +// ... + +typedarraypool.free( arr1 ); +typedarraypool.free( arr2 ); +typedarraypool.free( arr3 ); +``` + +#### typedarraypool.malloc( obj\[, dtype] ) + +Returns a pooled [typed array][mdn-typed-array] from an array-like `object`. + +```javascript +var arr1 = typedarraypool.malloc( [ 0.5, 0.5, 0.5 ] ); +// returns [ 0.5, 0.5, 0.5 ] + +var arr2 = typedarraypool.malloc( [ 0.5, 0.5, 0.5 ], 'float32' ); +// returns [ 0.5, 0.5, 0.5 ] + +// ... + +typedarraypool.free( arr1 ); +typedarraypool.free( arr2 ); +``` + +#### typedarraypool.calloc( \[dtype] ) + +Returns a **zero-initialized** [typed array][mdn-typed-array] having a specified data type `dtype`. + +```javascript +var arr1 = typedarraypool.calloc(); +// returns [] + +var arr2 = typedarraypool.calloc( 'int32' ); +// returns [] + +// ... + +typedarraypool.free( arr1 ); +typedarraypool.free( arr2 ); +``` + +#### typedarraypool.calloc( length\[, dtype] ) + +Returns a **zero-initialized** [typed array][mdn-typed-array] having a specified `length` from a [typed array][mdn-typed-array] memory pool. + +```javascript +var arr1 = typedarraypool.calloc( 5 ); +// returns [ 0.0, 0.0, 0.0, 0.0, 0.0 ] + +var arr2 = typedarraypool.calloc( 5, 'uint8' ); +// returns [ 0, 0, 0, 0, 0 ] + +// ... + +typedarraypool.free( arr1 ); +typedarraypool.free( arr2 ); +``` + +#### typedarraypool.free( buf ) + +Frees a [typed array][mdn-typed-array] or typed array [buffer][mdn-arraybuffer] for use in a future allocation. + +```javascript +var arr = typedarraypool( 10, 'float64' ); +// returns + +// ... + +// Free the allocated typed array for use in a future allocation: +typedarraypool.free( arr ); + +// Create another typed array: +arr = typedarraypool( 10, 'float64' ); +// returns + +// ... + +// Free the allocated typed array buffer for use in a future allocation: +typedarraypool.free( arr.buffer ); +``` + +#### typedarraypool.clear() + +Clears the [typed array][mdn-typed-array] pool allowing garbage collection of previously allocated (and currently free) [array buffers][mdn-arraybuffer]. + +```javascript +var arr = typedarraypool( 10, 'float64' ); +// returns + +// ... + +typedarraypool.free( arr ); + +// ... + +// Clear all freed buffers: +typedarraypool.clear(); +``` + +#### typedarraypool.highWaterMark + +**Read-only** property returning the pool's high water mark (in bytes). + +```javascript +var limit = typedarraypool.highWaterMark; +// returns +``` + +Once a high water mark is reached, [typed array][mdn-typed-array] allocation **fails**. + +#### typedarraypool.nbytes + +**Read-only** property returning the total number of allocated bytes. + +```javascript +var arr = typedarraypool( 5, 'float64' ); + +var nbytes = typedarraypool.nbytes; +// returns +``` + +The returned value is the total **accumulated** value. Hence, anytime a pool must allocate a new [array buffer][mdn-arraybuffer] (i.e., more memory), the pool increments this value. The only time this value is decremented is when a pool is cleared. This behavior means that, while allocated buffers which are never freed may, in fact, be garbage collected, they continue to count against the high water mark limit. Accordingly, you should **always** free allocated buffers in order to prevent the pool from believing that non-freed buffers are continually in use. + +#### typedarraypool.factory( \[options] ) + +Creates a new [typed array][mdn-typed-array] pool. + +```javascript +var pool = typedarraypool.factory(); + +var arr = pool( 5, 'float64' ); +// returns + +// ... + +pool.free( arr ); +``` + +The method accepts the following `options`: + +- **highWaterMark**: maximum total memory (in bytes) which can be allocated. Default: `2^53` bytes. + +By default, the maximum total memory a pool may allocate is `2^53` bytes (approximately `1` petabyte, which, in practical terms, means a pool has **unlimited** capacity). To specify an alternative limit, set the `highWaterMark` option. + +```javascript +// Create a new typed array pool which can allocate up to 1MB: +var pool = typedarraypool.factory({ + 'highWaterMark': 1e6 +}); + +var arr = pool( 5, 'float64' ); +// returns + +// ... + +pool.free( arr ); +``` + +
+ + + + + +
+ +## Notes + +- Uninitialized typed arrays may contain sensitive contents. If security is paramount (e.g., if freed [typed arrays][mdn-typed-array] have been used to store sensitive contents), use `calloc`. +- An allocated [typed array][mdn-typed-array] is **guaranteed** to have an underlying [array buffer][mdn-arraybuffer] with _at least_ `N * w` bytes, where `N` is the number of [typed array][mdn-typed-array] elements and `w` is the number of bytes per element. Note, however, that the underlying [array buffer][mdn-arraybuffer] is likely to have **excess** capacity. Thus, if you create many [typed arrays][mdn-typed-array] which are held in memory and are **not** freed, you are likely to consume significantly more memory than if you had directly used [typed array][mdn-typed-array] constructors. However, if you create many [typed arrays][mdn-typed-array] which are rapidly discarded and of relatively large size, then using a [typed array][mdn-typed-array] pool can offer significant performance advantages. + +
+ + + + + +
+ +## Examples + + + +```javascript +var randu = require( '@stdlib/random/base/randu' ); +var typedarraypool = require( '@stdlib/array/pool' ).factory; + +// Create a typed array pool which can allocate at most 1GB: +var typedarray = typedarraypool({ + 'highWaterMark': 1e9 +}); + +// Inspect the pool: +console.log( 'Max bytes: %d', typedarray.highWaterMark ); +console.log( 'nbytes: %d', typedarray.nbytes ); + +// Allocate an array for storing double-precision floating-point numbers: +var arr1 = typedarray( 5, 'float64' ); +// returns [ 0.0, 0.0, 0.0, 0.0, 0.0 ] + +// Inspect the pool: +console.log( 'nbytes: %d', typedarray.nbytes ); + +// Fill the array... +var i; +for ( i = 0; i < arr1.length; i++ ) { + arr1[ i ] = randu(); +} + +// Inspect array contents: +console.log( arr1 ); + +// Free the array: +typedarray.free( arr1 ); + +// Allocate another array similar to the previous one: +var arr2 = typedarray( 5, 'float64' ); +// returns + +// Check that we have been returned a new typed array view: +console.log( arr2 === arr1 ); +// => false + +// Inspect array contents: +console.log( arr2 ); + +// Free the array: +typedarray.free( arr2 ); + +// Allocate an initialized array: +var arr3 = typedarray.calloc( 5, 'float64' ); +// returns [ 0.0, 0.0, 0.0, 0.0, 0.0 ] + +// Inspect array contents: +console.log( arr3 ); + +// Free the array: +typedarray.free( arr3 ); + +// Clear the pool: +typedarray.clear(); + +// Inspect the pool: +console.log( 'nbytes: %d', typedarray.nbytes ); +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/pool/benchmark/benchmark.calloc.js b/pool/benchmark/benchmark.calloc.js new file mode 100644 index 00000000..1b491e86 --- /dev/null +++ b/pool/benchmark/benchmark.calloc.js @@ -0,0 +1,209 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':calloc', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.calloc( 0 ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':calloc:dtype=float64', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.calloc( 0, 'float64' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':calloc:dtype=float32', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.calloc( 0, 'float32' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':calloc:dtype=int32', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.calloc( 0, 'int32' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':calloc:dtype=uint32', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.calloc( 0, 'uint32' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':calloc:dtype=int16', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.calloc( 0, 'int16' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':calloc:dtype=uint16', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.calloc( 0, 'uint16' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':calloc:dtype=int8', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.calloc( 0, 'int8' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':calloc:dtype=uint8', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.calloc( 0, 'uint8' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':calloc:dtype=uint8c', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.calloc( 0, 'uint8c' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/pool/benchmark/benchmark.factory.js b/pool/benchmark/benchmark.factory.js new file mode 100644 index 00000000..544daabe --- /dev/null +++ b/pool/benchmark/benchmark.factory.js @@ -0,0 +1,71 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':factory', function benchmark( b ) { + var f; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + f = typedarray.factory(); + if ( typeof f !== 'function' ) { + b.fail( 'should return a function' ); + } + } + b.toc(); + if ( !isFunction( f ) ) { + b.fail( 'should return a function' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':factory:highWaterMark', function benchmark( b ) { + var opts; + var f; + var i; + + opts = { + 'highWaterMark': 0 + }; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + opts.highWaterMark = i; + f = typedarray.factory( opts ); + if ( typeof f !== 'function' ) { + b.fail( 'should return a function' ); + } + } + b.toc(); + if ( !isFunction( f ) ) { + b.fail( 'should return a function' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/pool/benchmark/benchmark.js b/pool/benchmark/benchmark.js new file mode 100644 index 00000000..d989beaa --- /dev/null +++ b/pool/benchmark/benchmark.js @@ -0,0 +1,209 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0 ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=float64', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0, 'float64' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=float32', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0, 'float32' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=int32', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0, 'int32' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint32', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0, 'uint32' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=int16', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0, 'int16' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint16', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0, 'uint16' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=int8', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0, 'int8' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint8', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0, 'uint8' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint8c', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0, 'uint8c' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/pool/benchmark/benchmark.length.float32.js b/pool/benchmark/benchmark.length.float32.js new file mode 100644 index 00000000..b18c1806 --- /dev/null +++ b/pool/benchmark/benchmark.length.float32.js @@ -0,0 +1,102 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {Function} fcn - allocation function +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( fcn, len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = fcn( len, 'float32' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + typedarray.free( arr ); + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + + f = createBenchmark( typedarray, len ); + bench( pkg+':dtype=float32,len='+len, f ); + + f = createBenchmark( typedarray.malloc, len ); + bench( pkg+':malloc:dtype=float32,len='+len, f ); + + f = createBenchmark( typedarray.calloc, len ); + bench( pkg+':calloc:dtype=float32,len='+len, f ); + } +} + +main(); diff --git a/pool/benchmark/benchmark.length.float64.js b/pool/benchmark/benchmark.length.float64.js new file mode 100644 index 00000000..4fa6b51d --- /dev/null +++ b/pool/benchmark/benchmark.length.float64.js @@ -0,0 +1,102 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {Function} fcn - allocation function +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( fcn, len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = fcn( len, 'float64' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + typedarray.free( arr ); + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + + f = createBenchmark( typedarray, len ); + bench( pkg+':dtype=float64,len='+len, f ); + + f = createBenchmark( typedarray.malloc, len ); + bench( pkg+':malloc:dtype=float64,len='+len, f ); + + f = createBenchmark( typedarray.calloc, len ); + bench( pkg+':calloc:dtype=float64,len='+len, f ); + } +} + +main(); diff --git a/pool/benchmark/benchmark.length.int16.js b/pool/benchmark/benchmark.length.int16.js new file mode 100644 index 00000000..16f37d5d --- /dev/null +++ b/pool/benchmark/benchmark.length.int16.js @@ -0,0 +1,102 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {Function} fcn - allocation function +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( fcn, len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = fcn( len, 'int16' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + typedarray.free( arr ); + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + + f = createBenchmark( typedarray, len ); + bench( pkg+':dtype=int16,len='+len, f ); + + f = createBenchmark( typedarray.malloc, len ); + bench( pkg+':malloc:dtype=int16,len='+len, f ); + + f = createBenchmark( typedarray.calloc, len ); + bench( pkg+':calloc:dtype=int16,len='+len, f ); + } +} + +main(); diff --git a/pool/benchmark/benchmark.length.int32.js b/pool/benchmark/benchmark.length.int32.js new file mode 100644 index 00000000..048aac3b --- /dev/null +++ b/pool/benchmark/benchmark.length.int32.js @@ -0,0 +1,102 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {Function} fcn - allocation function +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( fcn, len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = fcn( len, 'int32' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + typedarray.free( arr ); + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + + f = createBenchmark( typedarray, len ); + bench( pkg+':dtype=int32,len='+len, f ); + + f = createBenchmark( typedarray.malloc, len ); + bench( pkg+':malloc:dtype=int32,len='+len, f ); + + f = createBenchmark( typedarray.calloc, len ); + bench( pkg+':calloc:dtype=int32,len='+len, f ); + } +} + +main(); diff --git a/pool/benchmark/benchmark.length.int8.js b/pool/benchmark/benchmark.length.int8.js new file mode 100644 index 00000000..a513b988 --- /dev/null +++ b/pool/benchmark/benchmark.length.int8.js @@ -0,0 +1,102 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {Function} fcn - allocation function +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( fcn, len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = fcn( len, 'int8' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + typedarray.free( arr ); + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + + f = createBenchmark( typedarray, len ); + bench( pkg+':dtype=int8,len='+len, f ); + + f = createBenchmark( typedarray.malloc, len ); + bench( pkg+':malloc:dtype=int8,len='+len, f ); + + f = createBenchmark( typedarray.calloc, len ); + bench( pkg+':calloc:dtype=int8,len='+len, f ); + } +} + +main(); diff --git a/pool/benchmark/benchmark.length.uint16.js b/pool/benchmark/benchmark.length.uint16.js new file mode 100644 index 00000000..33f98807 --- /dev/null +++ b/pool/benchmark/benchmark.length.uint16.js @@ -0,0 +1,102 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {Function} fcn - allocation function +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( fcn, len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = fcn( len, 'uint16' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + typedarray.free( arr ); + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + + f = createBenchmark( typedarray, len ); + bench( pkg+':dtype=uint16,len='+len, f ); + + f = createBenchmark( typedarray.malloc, len ); + bench( pkg+':malloc:dtype=uint16,len='+len, f ); + + f = createBenchmark( typedarray.calloc, len ); + bench( pkg+':calloc:dtype=uint16,len='+len, f ); + } +} + +main(); diff --git a/pool/benchmark/benchmark.length.uint32.js b/pool/benchmark/benchmark.length.uint32.js new file mode 100644 index 00000000..51fd6124 --- /dev/null +++ b/pool/benchmark/benchmark.length.uint32.js @@ -0,0 +1,102 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {Function} fcn - allocation function +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( fcn, len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = fcn( len, 'uint32' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + typedarray.free( arr ); + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + + f = createBenchmark( typedarray, len ); + bench( pkg+':dtype=uint32,len='+len, f ); + + f = createBenchmark( typedarray.malloc, len ); + bench( pkg+':malloc:dtype=uint32,len='+len, f ); + + f = createBenchmark( typedarray.calloc, len ); + bench( pkg+':calloc:dtype=uint32,len='+len, f ); + } +} + +main(); diff --git a/pool/benchmark/benchmark.length.uint8.js b/pool/benchmark/benchmark.length.uint8.js new file mode 100644 index 00000000..ecfaef73 --- /dev/null +++ b/pool/benchmark/benchmark.length.uint8.js @@ -0,0 +1,102 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {Function} fcn - allocation function +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( fcn, len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = fcn( len, 'uint8' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + typedarray.free( arr ); + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + + f = createBenchmark( typedarray, len ); + bench( pkg+':dtype=uint8,len='+len, f ); + + f = createBenchmark( typedarray.malloc, len ); + bench( pkg+':malloc:dtype=uint8,len='+len, f ); + + f = createBenchmark( typedarray.calloc, len ); + bench( pkg+':calloc:dtype=uint8,len='+len, f ); + } +} + +main(); diff --git a/pool/benchmark/benchmark.length.uint8c.js b/pool/benchmark/benchmark.length.uint8c.js new file mode 100644 index 00000000..558127d8 --- /dev/null +++ b/pool/benchmark/benchmark.length.uint8c.js @@ -0,0 +1,102 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {Function} fcn - allocation function +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( fcn, len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = fcn( len, 'uint8c' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + typedarray.free( arr ); + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + + f = createBenchmark( typedarray, len ); + bench( pkg+':dtype=uint8c,len='+len, f ); + + f = createBenchmark( typedarray.malloc, len ); + bench( pkg+':malloc:dtype=uint8c,len='+len, f ); + + f = createBenchmark( typedarray.calloc, len ); + bench( pkg+':calloc:dtype=uint8c,len='+len, f ); + } +} + +main(); diff --git a/pool/benchmark/benchmark.malloc.js b/pool/benchmark/benchmark.malloc.js new file mode 100644 index 00000000..fd8d5709 --- /dev/null +++ b/pool/benchmark/benchmark.malloc.js @@ -0,0 +1,209 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':malloc', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.malloc( 0 ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':malloc:dtype=float64', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.malloc( 0, 'float64' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':malloc:dtype=float32', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.malloc( 0, 'float32' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':malloc:dtype=int32', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.malloc( 0, 'int32' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':malloc:dtype=uint32', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.malloc( 0, 'uint32' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':malloc:dtype=int16', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.malloc( 0, 'int16' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':malloc:dtype=uint16', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.malloc( 0, 'uint16' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':malloc:dtype=int8', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.malloc( 0, 'int8' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':malloc:dtype=uint8', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.malloc( 0, 'uint8' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':malloc:dtype=uint8c', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray.malloc( 0, 'uint8c' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/pool/docs/repl.txt b/pool/docs/repl.txt new file mode 100644 index 00000000..b0bc69d0 --- /dev/null +++ b/pool/docs/repl.txt @@ -0,0 +1,345 @@ + +{{alias}}( [dtype] ) + Returns an uninitialized typed array from a typed array memory pool. + + Memory is **uninitialized**, which means that the contents of a returned + typed array may contain sensitive contents. + + The function supports the following data types: + + - float64: double-precision floating-point numbers (IEEE 754) + - float32: single-precision floating-point numbers (IEEE 754) + - int32: 32-bit two's complement signed integers + - uint32: 32-bit unsigned integers + - int16: 16-bit two's complement signed integers + - uint16: 16-bit unsigned integers + - int8: 8-bit two's complement signed integers + - uint8: 8-bit unsigned integers + - uint8c: 8-bit unsigned integers clamped to 0-255 + + The default typed array data type is `float64`. + + Parameters + ---------- + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray|null + If the function is unable to allocate a typed array from the typed array + pool (e.g., due to insufficient memory), the function returns `null`. + + Examples + -------- + > var arr = {{alias}}() + [] + > arr = {{alias}}( 'float32' ) + [] + + +{{alias}}( length[, dtype] ) + Returns an uninitialized typed array having a specified length from a typed + array memory pool. + + Parameters + ---------- + length: integer + Typed array length. + + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray|null + If the function is unable to allocate a typed array from the typed array + pool (e.g., due to insufficient memory), the function returns `null`. + + Examples + -------- + > var arr = {{alias}}( 5 ) + + > arr = {{alias}}( 5, 'int32' ) + + + +{{alias}}( typedarray[, dtype] ) + Creates a pooled typed array from another typed array. + + Parameters + ---------- + typedarray: TypedArray + Typed array from which to generate another typed array. + + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray|null + If the function is unable to allocate a typed array from the typed array + pool (e.g., due to insufficient memory), the function returns `null`. + + Examples + -------- + > var arr1 = {{alias}}( [ 0.5, 0.5, 0.5 ] ); + > var arr2 = {{alias}}( arr1, 'float32' ) + [ 0.5, 0.5, 0.5 ] + + +{{alias}}( obj[, dtype] ) + Creates a pooled typed array from an array-like object. + + Parameters + ---------- + obj: Object + Array-like object from which to generate a typed array. + + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray|null + If the function is unable to allocate a typed array from the typed array + pool (e.g., due to insufficient memory), the function returns `null`. + + Examples + -------- + > var arr1 = [ 0.5, 0.5, 0.5 ]; + > var arr2 = {{alias}}( arr1, 'float32' ) + [ 0.5, 0.5, 0.5 ] + + +{{alias}}.malloc( [dtype] ) + Returns an uninitialized typed array from a typed array memory pool. + + This method shares the same security vulnerabilities mentioned above. + + Parameters + ---------- + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray|null + If the function is unable to allocate a typed array from the typed array + pool (e.g., due to insufficient memory), the function returns `null`. + + Examples + -------- + > var arr = {{alias}}.malloc() + + > arr = {{alias}}.malloc( 'float32' ) + + + +{{alias}}.malloc( length[, dtype] ) + Returns a typed array having a specified length from a typed array memory + pool. + + Parameters + ---------- + length: integer + Typed array length. + + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray|null + If the function is unable to allocate a typed array from the typed array + pool (e.g., due to insufficient memory), the function returns `null`. + + Examples + -------- + > var arr = {{alias}}.malloc( 5 ) + + > arr = {{alias}}.malloc( 5, 'int32' ) + + + +{{alias}}.malloc( typedarray[, dtype] ) + Creates a pooled typed array from another typed array. + + Parameters + ---------- + typedarray: TypedArray + Typed array from which to generate another typed array. + + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray|null + If the function is unable to allocate a typed array from the typed array + pool (e.g., due to insufficient memory), the function returns `null`. + + Examples + -------- + > var arr1 = {{alias}}.malloc( [ 0.5, 0.5, 0.5 ] ); + > var arr2 = {{alias}}.malloc( arr1, 'float32' ) + [ 0.5, 0.5, 0.5 ] + + +{{alias}}.malloc( obj[, dtype] ) + Creates a pooled typed array from an array-like object. + + Parameters + ---------- + obj: Object + Array-like object from which to generate a typed array. + + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray|null + If the function is unable to allocate a typed array from the typed array + pool (e.g., due to insufficient memory), the function returns `null`. + + Examples + -------- + > var arr1 = [ 0.5, 0.5, 0.5 ]; + > var arr2 = {{alias}}.malloc( arr1, 'float32' ) + [ 0.5, 0.5, 0.5 ] + + +{{alias}}.calloc( [dtype] ) + Returns a zero-initialized typed array from a typed array memory pool. + + Parameters + ---------- + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray|null + If the function is unable to allocate a typed array from the typed array + pool (e.g., due to insufficient memory), the function returns `null`. + + Examples + -------- + > var arr = {{alias}}.calloc() + [] + > arr = {{alias}}.calloc( 'float32' ) + [] + + +{{alias}}.calloc( length[, dtype] ) + Returns a zero-initialized typed array having a specified length from a + typed array memory pool. + + Parameters + ---------- + length: integer + Typed array length. + + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray|null + If the function is unable to allocate a typed array from the typed array + pool (e.g., due to insufficient memory), the function returns `null`. + + Examples + -------- + > var arr = {{alias}}.calloc( 5 ) + [ 0.0, 0.0, 0.0, 0.0, 0.0 ] + > arr = {{alias}}.calloc( 5, 'int32' ) + [ 0, 0, 0, 0, 0 ] + + +{{alias}}.free( buf ) + Frees a typed array or typed array buffer for use in a future allocation. + + Parameters + ---------- + buf: TypedArray|ArrayBuffer + Typed array or typed array buffer to free. + + Examples + -------- + > var arr = {{alias}}( 5 ) + + > {{alias}}.free( arr ) + + +{{alias}}.clear() + Clears the typed array pool allowing garbage collection of previously + allocated (and currently free) array buffers. + + Examples + -------- + > var arr = {{alias}}( 5 ) + + > {{alias}}.free( arr ); + > {{alias}}.clear() + + +{{alias}}.highWaterMark + Read-only property returning the pool's high water mark. + + Once a high water mark is reached, typed array allocation fails. + + Examples + -------- + > {{alias}}.highWaterMark + + +{{alias}}.nbytes + Read-only property returning the total number of allocated bytes. + + The returned value is the total accumulated value. Hence, anytime a pool + must allocate a new array buffer (i.e., more memory), the pool increments + this value. + + The only time this value is decremented is when a pool is cleared. + + This behavior means that, while allocated buffers which are never freed may, + in fact, be garbage collected, they continue to count against the high water + mark limit. + + Accordingly, you should *always* free allocated buffers in order to prevent + the pool from believing that non-freed buffers are continually in use. + + Examples + -------- + > var arr = {{alias}}( 5 ) + + > {{alias}}.nbytes + + +{{alias}}.factory( [options] ) + Creates a typed array pool. + + Parameters + ---------- + options: Object (optional) + Function options. + + options.highWaterMark: integer (optional) + Maximum total memory (in bytes) which can be allocated. + + Returns + ------- + fcn: Function + Function for creating typed arrays from a typed array memory pool. + + Examples + -------- + > var pool = {{alias}}.factory(); + > var arr1 = pool( 3, 'float64' ) + + + See Also + -------- + diff --git a/pool/docs/types/index.d.ts b/pool/docs/types/index.d.ts new file mode 100644 index 00000000..0239a14b --- /dev/null +++ b/pool/docs/types/index.d.ts @@ -0,0 +1,361 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/// + +import { ArrayLike, TypedArray } from '@stdlib/types/array'; +import ArrayBuffer = require( '@stdlib/array/buffer' ); + +type DataType = 'float64' | 'float32' | 'int32' | 'uint32' | 'int16' | 'uint16' | 'int8' | 'uint8' | 'uint8c'; // tslint-disable-line max-line-length + +/** +* Typed array or null. +*/ +type TypedArrayOrNull = TypedArray | null; + +/** +* Interface defining pool options. +*/ +interface Options { + /** + * Maximum total memory which can be allocated. + */ + highWaterMark?: number; +} + +/** +* Pool interface. +*/ +interface Pool { + /** + * Returns an uninitialized typed array. + * + * ## Notes + * + * - Memory is **not** initialized. + * - Memory is lazily allocated. + * - If the function returns `null`, the function was unable to allocate a new typed array from the typed array pool (most likely due to insufficient memory). + * + * @param dtype - data type (default: 'float64') + * @returns typed array or null + * + * @example + * var arr = typedarraypool(); + * // returns [] + * + * @example + * var arr = typedarraypool( 'float32' ); + * // returns [] + */ + ( dtype?: DataType ): TypedArrayOrNull; + + /** + * Returns an uninitialized typed array. + * + * ## Notes + * + * - Memory is **not** initialized. + * - Memory is lazily allocated. + * - If the function returns `null`, the function was unable to allocate a new typed array from the typed array pool (most likely due to insufficient memory). + * + * @param arg - an array length or an array-like object + * @param dtype - data type (default: 'float64') + * @returns typed array or null + * + * @example + * // Allocate an array of doubles: + * var arr = typedarraypool( 5, 'float64' ); + * // e.g., returns [ 0.0, 0.0, 0.0, 0.0, 0.0 ] + * + * arr[ 0 ] = 3.14; + * arr[ 1 ] = 3.14; + * + * // ... + * + * // Free the allocated memory to be used in a future allocation: + * typedarraypool.free( arr ); + * + * @example + * var arr1 = typedarraypool( [ 0.5, 0.5, 0.5 ] ); + * var arr2 = typedarraypool( arr1, 'float32' ); + * // returns [ 0.5, 0.5, 0.5 ] + * + * @example + * var arr1 = [ 0.5, 0.5, 0.5 ]; + * var arr2 = typedarraypool( arr1, 'float32' ); + * // returns [ 0.5, 0.5, 0.5 ] + */ + ( arg: number | ArrayLike, dtype?: DataType ): TypedArrayOrNull; + + /** + * Returns a zero-initialized typed array from a typed array memory pool. + * + * ## Notes + * + * - If the function returns `null`, the function was unable to allocate a new typed array from the typed array pool (most likely due to insufficient memory). + * + * @param dtype - data type (default: 'float64') + * @returns typed array or null + * + * @example + * var arr1 = typedarraypool.calloc(); + * // returns [] + * + * var arr2 = typedarraypool.calloc( 'int32' ); + * // returns [] + * + * // ... + * + * typedarraypool.free( arr1 ); + * typedarraypool.free( arr2 ); + */ + calloc( dtype?: DataType ): TypedArrayOrNull; + + /** + * Returns an uninitialized typed array. + * + * ## Notes + * + * - If the function returns `null`, the function was unable to allocate a new typed array from the typed array pool (most likely due to insufficient memory). + * + * @param length - typed array length + * @param dtype - data type (default: 'float64') + * @returns typed array or null + * + * @example + * var arr1 = typedarraypool.calloc( 5 ); + * // returns [ 0.0, 0.0, 0.0, 0.0, 0.0 ] + * + * var arr2 = typedarraypool.calloc( 5, 'uint8' ); + * // returns [ 0, 0, 0, 0, 0 ] + * + * // ... + * + * typedarraypool.free( arr1 ); + * typedarraypool.free( arr2 ); + */ + calloc( length: number, dtype?: DataType ): TypedArrayOrNull; + + /** + * Returns an uninitialized typed array. + * + * ## Notes + * + * - Memory is **not** initialized. + * - Memory is lazily allocated. + * - If the function returns `null`, the function was unable to allocate a new typed array from the typed array pool (most likely due to insufficient memory). + * + * @param dtype - data type (default: 'float64') + * @returns typed array or null + * + * @example + * var arr1 = typedarraypool.malloc(); + * // returns [] + * + * var arr2 = typedarraypool.malloc( 'int32' ); + * // returns [] + * + * // ... + * + * typedarraypool.free( arr1 ); + * typedarraypool.free( arr2 ); + */ + malloc( dtype?: DataType ): TypedArrayOrNull; + + /** + * Returns an uninitialized typed array. + * + * ## Notes + * + * - Memory is **not** initialized. + * - Memory is lazily allocated. + * - If the function returns `null`, the function was unable to allocate a new typed array from the typed array pool (most likely due to insufficient memory). + * + * @param arg - an array length or an array-like object + * @param dtype - data type (default: 'float64') + * @returns typed array or null + * + * @example + * var arr1 = typedarraypool.malloc( 5 ); + * // returns + * + * var arr2 = typedarraypool.malloc( 5, 'uint8' ); + * // returns + * + * // ... + * + * typedarraypool.free( arr1 ); + * typedarraypool.free( arr2 ); + * + * @example + * var arr1 = typedarraypool.malloc( [ 5.0, -3.0, 2.0 ] ); + * // returns [ 5.0, -3.0, 2.0 ] + * + * var arr2 = typedarraypool.malloc( arr1 ); + * // returns [ 5.0, -3.0, 2.0 ] + * + * var arr3 = typedarraypool.malloc( arr1, 'int32' ); + * // returns [ 5, -3, 2 ] + * + * // ... + * + * typedarraypool.free( arr1 ); + * typedarraypool.free( arr2 ); + * typedarraypool.free( arr3 ); + * + * @example + * var arr1 = typedarraypool.malloc( [ 0.5, 0.5, 0.5 ] ); + * // returns [ 0.5, 0.5, 0.5 ] + * + * var arr2 = typedarraypool.malloc( [ 0.5, 0.5, 0.5 ], 'float32' ); + * // returns [ 0.5, 0.5, 0.5 ] + * + * // ... + * + * typedarraypool.free( arr1 ); + * typedarraypool.free( arr2 ); + */ + malloc( arg: number | ArrayLike, dtype?: DataType ): TypedArrayOrNull; + + /** + * Frees a typed array or typed array buffer for use in a future allocation. + * + * @param buf - typed array or typed array buffer to free + * + * @example + * var arr = typedarraypool( 10, 'float64' ); + * // returns + * + * // ... + * + * // Free the allocated typed array for use in a future allocation: + * typedarraypool.free( arr ); + * + * // Create another typed array: + * arr = typedarraypool( 10, 'float64' ); + * // returns + * + * // ... + * + * // Free the allocated typed array buffer for use in a future allocation: + * typedarraypool.free( arr.buffer ); + */ + free( buf: TypedArray | ArrayBuffer ): void; + + /** + * Clears the typed array pool allowing garbage collection of previously allocated (and currently free) array buffers. + * + * @example + * var arr = typedarraypool( 10, 'float64' ); + * // returns + * + * // ... + * + * typedarraypool.free( arr ); + * + * // ... + * + * // Clear all freed buffers: + * typedarraypool.clear(); + */ + clear(): void; + + /** + * Read-only property returning the pool's high water mark. + * + * ## Notes + * + * - Once a high water mark is reached, typed array allocation fails. + * + * @example + * var limit = typedarraypool.highWaterMark; + * // returns + */ + readonly highWaterMark: number; + + /** + * Read-only property returning the total number of allocated bytes. + * + * @example + * var arr = typedarraypool( 5, 'float64' ); + * + * var nbytes = typedarraypool.nbytes; + * // returns + */ + readonly nbytes: number; + + /** + * Creates a typed array pool. + * + * @param options - pool options + * @param options.highWaterMark - maximum total memory which can be allocated + * @throws must provide valid options + * @returns allocator + * + * @example + * var allocator = typedarraypool.factory(); + * + * // Allocate an array of doubles: + * var arr = allocator( 5, 'float64' ); + * // returns [ 0.0, 0.0, 0.0, 0.0, 0.0 ] + * + * arr[ 0 ] = 3.14; + * arr[ 1 ] = 3.14; + * + * // ... + * + * // Free the allocated memory to be used in a future allocation: + * allocator.free( arr ); + */ + factory( options?: Options ): Pool; +} + +/** +* Returns an uninitialized typed array. +* +* ## Notes +* +* - Memory is **not** initialized. +* - Memory is lazily allocated. +* - If the function returns `null`, the function was unable to allocate a new typed array from the typed array pool (most likely due to insufficient memory). +* +* @param arg - an array length or an array-like object +* @param dtype - data type (default: 'float64') +* @returns typed array or null +* +* @example +* // Allocate an array of doubles: +* var arr = typedarraypool( 5, 'float64' ); +* // e.g., returns [ 0.0, 0.0, 0.0, 0.0, 0.0 ] +* +* arr[ 0 ] = 3.14; +* arr[ 1 ] = 3.14; +* +* // ... +* +* // Free the allocated memory to be used in a future allocation: +* typedarraypool.free( arr ); +*/ +declare var typedarraypool: Pool; + + +// EXPORTS // + +export = typedarraypool; diff --git a/pool/docs/types/test.ts b/pool/docs/types/test.ts new file mode 100644 index 00000000..1014bba5 --- /dev/null +++ b/pool/docs/types/test.ts @@ -0,0 +1,193 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* tslint:disable:no-empty */ +/* tslint:disable:no-unused-expression */ + +import typedarraypool = require( './index' ); + + +// TESTS // + +// The function returns a typed array or null... +{ + typedarraypool(); // $ExpectType TypedArrayOrNull + typedarraypool( 'float32' ); // $ExpectType TypedArrayOrNull + typedarraypool( 12 ); // $ExpectType TypedArrayOrNull + typedarraypool( 12, 'int32' ); // $ExpectType TypedArrayOrNull + typedarraypool( [ 1, 2, 3 ] ); // $ExpectType TypedArrayOrNull + const arr = new Int32Array( [ 2, 5, 5, 7 ] ); + typedarraypool( arr, 'float64' ); // $ExpectType TypedArrayOrNull +} + +// The compiler throws an error if the function is provided a first argument which is neither a number nor array-like object... +{ + typedarraypool( true ); // $ExpectError + typedarraypool( false ); // $ExpectError + typedarraypool( null ); // $ExpectError + typedarraypool( {} ); // $ExpectError +} + +// The compiler throws an error if the function is provided a second argument which is not a recognized data type... +{ + typedarraypool( 4, true ); // $ExpectError + typedarraypool( 4, false ); // $ExpectError + typedarraypool( 4, null ); // $ExpectError + typedarraypool( 4, 'abc' ); // $ExpectError + typedarraypool( 4, 123 ); // $ExpectError + typedarraypool( 4, [] ); // $ExpectError + typedarraypool( 4, {} ); // $ExpectError + typedarraypool( 4, ( x: number ): number => x ); // $ExpectError +} + +// The compiler throws an error if the function is provided an incorrect number of arguments... +{ + typedarraypool( 4, 'int32', {} ); // $ExpectError +} + +// Attached to the main export is a `malloc` method which returns a typed array or null... +{ + typedarraypool.malloc(); // $ExpectType TypedArrayOrNull + typedarraypool.malloc( 'float32' ); // $ExpectType TypedArrayOrNull + typedarraypool.malloc( 12 ); // $ExpectType TypedArrayOrNull + typedarraypool.malloc( 12, 'int32' ); // $ExpectType TypedArrayOrNull + typedarraypool.malloc( [ 1, 2, 3 ] ); // $ExpectType TypedArrayOrNull + const arr = new Int32Array( [ 2, 5, 5, 7 ] ); + typedarraypool.malloc( arr, 'float64' ); // $ExpectType TypedArrayOrNull +} + +// The compiler throws an error if the `malloc` method is provided a first argument which is neither a number nor array-like object... +{ + typedarraypool.malloc( true ); // $ExpectError + typedarraypool.malloc( false ); // $ExpectError + typedarraypool.malloc( null ); // $ExpectError + typedarraypool.malloc( {} ); // $ExpectError +} + +// The compiler throws an error if the `malloc` method is provided a second argument which is not a recognized data type... +{ + typedarraypool.malloc( 4, true ); // $ExpectError + typedarraypool.malloc( 4, false ); // $ExpectError + typedarraypool.malloc( 4, null ); // $ExpectError + typedarraypool.malloc( 4, 'abc' ); // $ExpectError + typedarraypool.malloc( 4, 123 ); // $ExpectError + typedarraypool.malloc( 4, [] ); // $ExpectError + typedarraypool.malloc( 4, {} ); // $ExpectError + typedarraypool.malloc( 4, ( x: number ): number => x ); // $ExpectError +} + +// The compiler throws an error if the `malloc` method is provided an incorrect number of arguments... +{ + typedarraypool.malloc( 4, 'int32', {} ); // $ExpectError +} + +// Attached to the main export is a `calloc` method which returns a typed array or null... +{ + typedarraypool.calloc(); // $ExpectType TypedArrayOrNull + typedarraypool.calloc( 'float32' ); // $ExpectType TypedArrayOrNull + typedarraypool.calloc( 12 ); // $ExpectType TypedArrayOrNull + typedarraypool.calloc( 12, 'int32' ); // $ExpectType TypedArrayOrNull +} + +// The compiler throws an error if the `calloc` method is provided a first argument which is not a number... +{ + typedarraypool.calloc( 'abc' ); // $ExpectError + typedarraypool.calloc( true ); // $ExpectError + typedarraypool.calloc( false ); // $ExpectError + typedarraypool.calloc( null ); // $ExpectError + typedarraypool.calloc( {} ); // $ExpectError + typedarraypool.calloc( [] ); // $ExpectError + typedarraypool.calloc( ( x: number ): number => x ); // $ExpectError +} + +// The compiler throws an error if the `calloc` method is provided a second argument which is not a recognized data type... +{ + typedarraypool.calloc( 4, true ); // $ExpectError + typedarraypool.calloc( 4, false ); // $ExpectError + typedarraypool.calloc( 4, null ); // $ExpectError + typedarraypool.calloc( 4, 'abc' ); // $ExpectError + typedarraypool.calloc( 4, 123 ); // $ExpectError + typedarraypool.calloc( 4, [] ); // $ExpectError + typedarraypool.calloc( 4, {} ); // $ExpectError + typedarraypool.calloc( 4, ( x: number ): number => x ); // $ExpectError +} + +// The compiler throws an error if the `calloc` method is provided an incorrect number of arguments... +{ + typedarraypool.calloc( 4, 'int32', {} ); // $ExpectError +} + +// Attached to the main export is a `factory` method which returns a typed array pool.. +{ + typedarraypool.factory(); // $ExpectType Pool + typedarraypool.factory( { 'highWaterMark': 556 } ); // $ExpectType Pool +} + +// The compiler throws an error if the `factory` method is provided a `highWaterMark` option which is not a number... +{ + typedarraypool.factory( { 'highWaterMark': true } ); // $ExpectError + typedarraypool.factory( { 'highWaterMark': false } ); // $ExpectError + typedarraypool.factory( { 'highWaterMark': 'abc' } ); // $ExpectError + typedarraypool.factory( { 'highWaterMark': null } ); // $ExpectError + typedarraypool.factory( { 'highWaterMark': [] } ); // $ExpectError + typedarraypool.factory( { 'highWaterMark': {} } ); // $ExpectError + typedarraypool.factory( { 'highWaterMark': ( x: number ): number => x } ); // $ExpectError +} + +// The compiler throws an error if the `factory` method is provided an incorrect number of arguments... +{ + typedarraypool.factory( {}, {} ); // $ExpectError +} + +// Attached to the main export is a `free` method which returns void... +{ + const arr = new Int32Array( [ 2, 5, 5, 7 ] ); + typedarraypool.free( arr ); // $ExpectType void +} + +// The compiler throws an error if the `free` method is provided a first argument which is neither a typed array nor array buffer... +{ + typedarraypool.free( true ); // $ExpectError + typedarraypool.free( false ); // $ExpectError + typedarraypool.free( 123 ); // $ExpectError + typedarraypool.free( 'abc' ); // $ExpectError + typedarraypool.free( null ); // $ExpectError + typedarraypool.free( {} ); // $ExpectError + typedarraypool.free( ( x: number ): number => x ); // $ExpectError +} + +// Attached to the main export is a `clear` method which returns void... +{ + typedarraypool.clear(); // $ExpectType void +} + +// The compiler throws an error if the `clear` method is provided arguments... +{ + typedarraypool.clear( {} ); // $ExpectError + typedarraypool.clear( {}, {} ); // $ExpectError +} + +// Attached to the main export is a `highWaterMark` property... +{ + typedarraypool.highWaterMark; // $ExpectType number +} + +// Attached to the main export is a `nbytes` property... +{ + typedarraypool.nbytes; // $ExpectType number +} diff --git a/pool/examples/index.js b/pool/examples/index.js new file mode 100644 index 00000000..dd39ad87 --- /dev/null +++ b/pool/examples/index.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var randu = require( '@stdlib/random/base/randu' ); +var typedarraypool = require( './../lib' ).factory; + +// Create a typed array pool which can allocate at most 1GB: +var typedarray = typedarraypool({ + 'highWaterMark': 1e9 +}); + +// Inspect the pool: +console.log( 'Max bytes: %d', typedarray.highWaterMark ); +console.log( 'nbytes: %d', typedarray.nbytes ); + +// Allocate an array for storing double-precision floating-point numbers: +var arr1 = typedarray( 5, 'float64' ); +// returns [ 0.0, 0.0, 0.0, 0.0, 0.0 ] + +// Inspect the pool: +console.log( 'nbytes: %d', typedarray.nbytes ); + +// Fill the array... +var i; +for ( i = 0; i < arr1.length; i++ ) { + arr1[ i ] = randu(); +} + +// Inspect array contents: +console.log( arr1 ); + +// Free the array: +typedarray.free( arr1 ); + +// Allocate another array similar to the previous one: +var arr2 = typedarray( 5, 'float64' ); +// returns + +// Check that we have been returned a new typed array view: +console.log( arr2 === arr1 ); +// => false + +// Inspect array contents: +console.log( arr2 ); + +// Free the array: +typedarray.free( arr2 ); + +// Allocate an initialized array: +var arr3 = typedarray.calloc( 5, 'float64' ); +// returns [ 0.0, 0.0, 0.0, 0.0, 0.0 ] + +// Inspect array contents: +console.log( arr3 ); + +// Free the array: +typedarray.free( arr3 ); + +// Clear the pool: +typedarray.clear(); + +// Inspect the pool: +console.log( 'nbytes: %d', typedarray.nbytes ); diff --git a/pool/lib/bytes_per_element.json b/pool/lib/bytes_per_element.json new file mode 100644 index 00000000..094d12b6 --- /dev/null +++ b/pool/lib/bytes_per_element.json @@ -0,0 +1,11 @@ +{ + "float64": 8, + "float32": 4, + "int16": 2, + "int32": 4, + "int8": 1, + "uint16": 2, + "uint32": 4, + "uint8": 1, + "uint8c": 1 +} diff --git a/pool/lib/defaults.json b/pool/lib/defaults.json new file mode 100644 index 00000000..c71c8f21 --- /dev/null +++ b/pool/lib/defaults.json @@ -0,0 +1,3 @@ +{ + "highWaterMark": 9007199254740992 +} diff --git a/pool/lib/factory.js b/pool/lib/factory.js new file mode 100644 index 00000000..940e8a03 --- /dev/null +++ b/pool/lib/factory.js @@ -0,0 +1,308 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isString = require( '@stdlib/assert/is-string' ).isPrimitive; +var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; +var isCollection = require( '@stdlib/assert/is-collection' ); +var isTypedArrayLike = require( '@stdlib/assert/is-typed-array-like' ); +var isArrayBuffer = require( '@stdlib/assert/is-arraybuffer' ); +var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); +var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' ); +var ctors = require( '@stdlib/array/typed-ctors' ); +var copy = require( '@stdlib/utils/copy' ); +var ArrayBuffer = require( '@stdlib/array/buffer' ); +var ceil = require( '@stdlib/math/base/special/ceil' ); +var floor = require( '@stdlib/math/base/special/floor' ); +var ceil2 = require( '@stdlib/math/base/special/ceil2' ); +var log2 = require( '@stdlib/math/base/special/log2' ); +var min = require( '@stdlib/math/base/special/min' ); +var defaults = require( './defaults.json' ); +var validate = require( './validate.js' ); +var createPool = require( './pool.js' ); +var BYTES_PER_ELEMENT = require( './bytes_per_element.json' ); + + +// MAIN // + +/** +* Creates a typed array pool. +* +* @param {Options} [options] - pool options +* @param {NonNegativeInteger} [options.highWaterMark] - maximum total memory which can be allocated +* @throws {TypeError} options argument must be an object +* @throws {TypeError} must provide valid options +* @returns {Function} allocator +* +* @example +* var typedarraypool = factory(); +* +* // Allocate an array of doubles: +* var arr = typedarraypool( 5, 'float64' ); +* // returns [ 0.0, 0.0, 0.0, 0.0, 0.0 ] +* +* arr[ 0 ] = 3.14; +* arr[ 1 ] = 3.14; +* +* // ... +* +* // Free the allocated memory to be used in a future allocation: +* typedarraypool.free( arr ); +*/ +function factory( options ) { + var nbytes; + var pool; + var opts; + var err; + + opts = copy( defaults ); + if ( arguments.length ) { + err = validate( opts, options ); + if ( err ) { + throw err; + } + } + pool = createPool( ceil( log2( opts.highWaterMark ) ) ); + nbytes = 0; + + setReadOnly( malloc, 'malloc', malloc ); // circular reference + setReadOnly( malloc, 'calloc', calloc ); + setReadOnly( malloc, 'free', free ); + setReadOnly( malloc, 'clear', clear ); + setReadOnly( malloc, 'highWaterMark', opts.highWaterMark ); + setReadOnlyAccessor( malloc, 'nbytes', getBytes ); + + return malloc; + + /** + * Returns the number of allocated bytes. + * + * @private + * @returns {NonNegativeInteger} number of allocated bytes + */ + function getBytes() { + return nbytes; + } + + /** + * Returns an array buffer. + * + * @private + * @param {NonNegativeInteger} n - number of bytes + * @returns {(ArrayBuffer|null)} array buffer or null + */ + function arraybuffer( n ) { + var buf; + var i; + + // Convert the number of bytes to an index in our pool table: + i = log2( n ); + + // If we already have an available array buffer, use it... + if ( i < pool.length && pool[ i ].length ) { + return pool[ i ].pop(); + } + // Before allocating a new array buffer, ensure that we have not exceeded the maximum number of bytes we are allowed to allocate... + if ( nbytes+n > opts.highWaterMark ) { + return null; + } + buf = new ArrayBuffer( n ); + + // Update the running counter of allocated bytes: + nbytes += n; + + return buf; + } + + /** + * Returns a typed array. + * + * @private + * @param {Function} ctor - typed array constructor + * @param {NonNegativeInteger} len - view length + * @param {string} dtype - data type + * @returns {(TypedArray|null)} typed array or null + */ + function typedarray( ctor, len, dtype ) { + var buf; + if ( len === 0 ) { + return new ctor( 0 ); + } + buf = arraybuffer( ceil2( len )*BYTES_PER_ELEMENT[ dtype ] ); + if ( buf === null ) { + return buf; + } + return new ctor( buf, 0, len ); + } + + /** + * Returns an uninitialized typed array. + * + * ## Notes + * + * - Memory is **not** initialized. + * - Memory is lazily allocated. + * - If the function returns `null`, the function was unable to allocate a new typed array from the typed array pool (most likely due to insufficient memory). + * + * @private + * @param {(NonNegativeInteger|Collection)} [arg] - an array length or an array-like object + * @param {string} [dtype="float64"] - data type + * @throws {TypeError} must provide a valid array length or an array-like object + * @throws {TypeError} must provide a recognized data type + * @returns {(TypedArray|null)} typed array or null + */ + function malloc() { + var nargs; + var dtype; + var ctor; + var len; + var arr; + var out; + var i; + + nargs = arguments.length; + if ( nargs && isString( arguments[ nargs-1 ] ) ) { + nargs -= 1; + dtype = arguments[ nargs ]; + } else { + dtype = 'float64'; + } + ctor = ctors( dtype ); + if ( ctor === null ) { + throw new TypeError( 'invalid argument. Must provide a recognized data type. Value: `'+dtype+'`.' ); + } + if ( nargs <= 0 ) { + return new ctor( 0 ); + } + // Check if provided a typed array length... + if ( isNonNegativeInteger( arguments[ 0 ] ) ) { + return typedarray( ctor, arguments[ 0 ], dtype ); + } + // Check if provided an array-like object containing data elements... + if ( isCollection( arguments[ 0 ] ) ) { + arr = arguments[ 0 ]; + len = arr.length; + out = typedarray( ctor, len, dtype ); + if ( out === null ) { + return out; + } + for ( i = 0; i < len; i++ ) { + out[ i ] = arr[ i ]; + } + return out; + } + throw new TypeError( 'invalid argument. First argument must be either an array length or an array-like object. Value: `'+arguments[ 0 ]+'`.' ); + } + + /** + * Returns a zero-initialized typed array. + * + * ## Notes + * + * - If the function returns `null`, the function was unable to allocate a new typed array from the typed array pool (most likely due to insufficient memory). + * + * @private + * @param {NonNegativeInteger} [len=0] - array length + * @param {string} [dtype="float64"] - data type + * @throws {TypeError} must provide a valid array length + * @throws {TypeError} must provide a recognized data type + * @returns {(TypedArray|null)} typed array or null + */ + function calloc() { + var nargs; + var out; + var i; + + nargs = arguments.length; + if ( nargs === 0 ) { + out = malloc(); + } else if ( nargs === 1 ) { + out = malloc( arguments[ 0 ] ); + } else { + out = malloc( arguments[ 0 ], arguments[ 1 ] ); + } + if ( out !== null ) { + // Initialize the memory... + for ( i = 0; i < out.length; i++ ) { + out[ i ] = 0.0; + } + } + return out; + } + + /** + * Frees a typed array or typed array buffer. + * + * ## Notes + * + * - Implicitly, we support providing non-internally allocated arrays and array buffer (e.g., "freeing" a typed array allocated in userland); however, the freed array buffer is likely to have excess capacity when compared to other members in its pool. + * + * @private + * @param {(TypedArray|ArrayBuffer)} buf - typed array or array buffer to free + * @throws {TypeError} must provide a typed array or typed array buffer + * @returns {boolean} boolean indicating whether the typed array or array buffer was successfully freed + */ + function free( buf ) { + var n; + var p; + var i; + if ( isTypedArrayLike( buf ) && buf.buffer ) { + buf = buf.buffer; + } else if ( !isArrayBuffer( buf ) ) { + throw new TypeError( 'invalid argument. Must provide a typed array or typed array buffer. Value: `'+buf+'`.' ); + } + if ( buf.byteLength > 0 ) { + n = floor( log2( buf.byteLength ) ); + + // Prohibit "freeing" array buffers which would potentially allow users to circumvent high water mark limits: + n = min( pool.length-1, n ); + + // Ensure that we do not attempt to free the same buffer more than once... + p = pool[ n ]; + for ( i = 0; i < p.length; i++ ) { + if ( p[ i ] === buf ) { + return false; + } + } + // Add the buffer to our pool of free buffers: + p.push( buf ); + } + return true; + } + + /** + * Clears the typed array pool allowing garbage collection of previously allocated (and currently free) array buffers. + * + * @private + */ + function clear() { + var i; + for ( i = 0; i < pool.length; i++ ) { + pool[ i ].length = 0; + } + nbytes = 0; + } +} + + +// EXPORTS // + +module.exports = factory; diff --git a/pool/lib/index.js b/pool/lib/index.js new file mode 100644 index 00000000..8130a3d2 --- /dev/null +++ b/pool/lib/index.js @@ -0,0 +1,56 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Typed array pool. +* +* @module @stdlib/array/pool +* +* @example +* var typedarraypool = require( '@stdlib/array/pool' ); +* +* // Allocate an array of doubles: +* var arr = typedarraypool( 5, 'float64' ); +* // returns [ 0.0, 0.0, 0.0, 0.0, 0.0 ] +* +* arr[ 0 ] = 3.14; +* arr[ 1 ] = 3.14; +* +* // ... +* +* // Free the allocated memory to be used in a future allocation: +* typedarraypool.free( arr ); +*/ + +// MODULES // + +var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); +var typedarraypool = require( './main.js' ); +var factory = require( './factory.js' ); + + +// MAIN // + +setReadOnly( typedarraypool, 'factory', factory ); + + +// EXPORTS // + +module.exports = typedarraypool; diff --git a/pool/lib/main.js b/pool/lib/main.js new file mode 100644 index 00000000..8f69ee3a --- /dev/null +++ b/pool/lib/main.js @@ -0,0 +1,63 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var factory = require( './factory.js' ); + + +// MAIN // + +/** +* Returns an uninitialized typed array. +* +* ## Notes +* +* - Memory is **not** initialized. +* - Memory is lazily allocated. +* - If the function returns `null`, the function was unable to allocate a new typed array from the typed array pool (most likely due to insufficient memory). +* +* @name typedarraypool +* @type {Function} +* @param {(NonNegativeInteger|ArrayLikeObject)} [arg] - an array length or an array-like object +* @param {string} [dtype="float64"] - data type +* @throws {TypeError} must provide a valid array length or an array-like object +* @throws {TypeError} must provide a recognized data type +* @returns {(TypedArray|null)} typed array or null +* +* @example +* // Allocate an array of doubles: +* var arr = typedarraypool( 5, 'float64' ); +* // e.g., returns [ 0.0, 0.0, 0.0, 0.0, 0.0 ] +* +* arr[ 0 ] = 3.14; +* arr[ 1 ] = 3.14; +* +* // ... +* +* // Free the allocated memory to be used in a future allocation: +* typedarraypool.free( arr ); +*/ +var typedarraypool = factory(); + + +// EXPORTS // + +module.exports = typedarraypool; diff --git a/pool/lib/pool.js b/pool/lib/pool.js new file mode 100644 index 00000000..5abd2872 --- /dev/null +++ b/pool/lib/pool.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MAIN // + +/** +* Initializes a cache for pooled typed array buffers. +* +* @private +* @param {NonNegativeInteger} n - base-2 logarithm of the maximum typed array size +* @returns {ArrayArray} initialized cache +*/ +function pool( n ) { + var out; + var i; + + out = []; + for ( i = 0; i < n+1; i++ ) { + out.push( [] ); + } + return out; +} + + +// EXPORTS // + +module.exports = pool; diff --git a/pool/lib/validate.js b/pool/lib/validate.js new file mode 100644 index 00000000..4d6b7149 --- /dev/null +++ b/pool/lib/validate.js @@ -0,0 +1,65 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isObject = require( '@stdlib/assert/is-plain-object' ); +var hasOwnProp = require( '@stdlib/assert/has-own-property' ); +var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; + + +// MAIN // + +/** +* Validates function options. +* +* @private +* @param {Object} opts - destination object +* @param {Options} options - function options +* @param {NonNegativeInteger} [options.highWaterMark] - maximum total memory which can be allocated +* @returns {(Error|null)} null or an error object +* +* @example +* var opts = {}; +* var options = { +* 'highWaterMark': 1024 +* }; +* var err = validate( opts, options ); +* if ( err ) { +* throw err; +* } +*/ +function validate( opts, options ) { + if ( !isObject( options ) ) { + return new TypeError( 'invalid argument. Options must be an object. Value: `' + options + '`.' ); + } + if ( hasOwnProp( options, 'highWaterMark' ) ) { + opts.highWaterMark = options.highWaterMark; + if ( !isNonNegativeInteger( opts.highWaterMark ) ) { + return new TypeError( 'invalid option. `highWaterMark` option must be a nonnegative integer. Option: `' + opts.highWaterMark + '`.' ); + } + } + return null; +} + + +// EXPORTS // + +module.exports = validate; diff --git a/pool/package.json b/pool/package.json new file mode 100644 index 00000000..ca1da566 --- /dev/null +++ b/pool/package.json @@ -0,0 +1,99 @@ +{ + "name": "@stdlib/array/pool", + "version": "0.0.0", + "description": "Typed array pool.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structure", + "typed", + "array", + "typed array", + "typed-array", + "vector", + "ndarray", + "matrix", + "float64array", + "float32array", + "int32array", + "uint32array", + "int16array", + "uint16array", + "int8array", + "uint8array", + "uint8clampedarray", + "float64", + "double", + "precision", + "double-precision", + "single", + "float", + "single-precision", + "float32", + "ieee754", + "integer", + "int32", + "signed", + "unsigned", + "uint32", + "int16", + "uint16", + "int8", + "uint8", + "uint8c", + "clamped", + "short", + "long", + "pool", + "memory", + "mem" + ] +} diff --git a/pool/test/test.factory.js b/pool/test/test.factory.js new file mode 100644 index 00000000..d71c48ef --- /dev/null +++ b/pool/test/test.factory.js @@ -0,0 +1,1928 @@ +/* eslint-disable max-lines */ + +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var Float64Array = require( '@stdlib/array/float64' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Int8Array = require( '@stdlib/array/int8' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); +var instanceOf = require( '@stdlib/assert/instance-of' ); +var randu = require( '@stdlib/random/base/randu' ); +var factory = require( './../lib/factory.js' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof factory, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function returns a function (no options)', function test( t ) { + t.strictEqual( typeof factory(), 'function', 'returns a function' ); + t.end(); +}); + +tape( 'the function returns a function (options)', function test( t ) { + t.strictEqual( typeof factory( {} ), 'function', 'returns a function' ); + t.end(); +}); + +tape( 'the function throws an error if provided an invalid options argument', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + [], + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + factory( value ); + }; + } +}); + +tape( 'the function throws an error if provided a `highWaterMark` option which is not a nonnegative integer', function test( t ) { + var values; + var i; + + values = [ + '5', + -5, + 3.14, + NaN, + true, + false, + null, + void 0, + [], + {}, + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + factory({ + 'highWaterMark': value + }); + }; + } +}); + +tape( 'the function returns a function which throws an error if provided an unrecognized data type (only argument)', function test( t ) { + var typedarraypool; + var values; + var i; + + values = [ + '5', + 'beep', + 'typedarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32' + ]; + + typedarraypool = factory(); + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarraypool( value ); + }; + } +}); + +tape( 'the function returns a function which throws an error if provided an unrecognized data type (length)', function test( t ) { + var typedarraypool; + var values; + var i; + + values = [ + '5', + 'beep', + 'typedarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32' + ]; + + typedarraypool = factory(); + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarraypool( 10, value ); + }; + } +}); + +tape( 'the function returns a function which throws an error if provided an unrecognized data type (typed array)', function test( t ) { + var typedarraypool; + var values; + var i; + + values = [ + '5', + 'beep', + 'typedarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32' + ]; + + typedarraypool = factory(); + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarraypool( new Float64Array( 10 ), value ); + }; + } +}); + +tape( 'the function returns a function which throws an error if provided an unrecognized data type (array-like object)', function test( t ) { + var typedarraypool; + var values; + var i; + + values = [ + '5', + 'beep', + 'typedarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32' + ]; + + typedarraypool = factory(); + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarraypool( [ 1, 2, 3 ], value ); + }; + } +}); + +tape( 'the function returns a function which throws an error if provided an invalid array length or array-like object argument (no data type argument)', function test( t ) { + var typedarraypool; + var values; + var i; + + values = [ + 3.14, + -1, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + typedarraypool = factory(); + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarraypool( value ); + }; + } +}); + +tape( 'the function returns a function which throws an error if provided an invalid array length or array-like object argument (data type argument)', function test( t ) { + var typedarraypool; + var values; + var i; + + values = [ + 3.14, + -1, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + typedarraypool = factory(); + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarraypool( value, 'float64' ); + }; + } +}); + +tape( 'the function returns a function which returns a typed array (default)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool(); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=float64)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool( 'float64' ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=float32)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool( 'float32' ); + t.strictEqual( instanceOf( arr, Float32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=int32)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool( 'int32' ); + t.strictEqual( instanceOf( arr, Int32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=uint32)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool( 'uint32' ); + t.strictEqual( instanceOf( arr, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=int16)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool( 'int16' ); + t.strictEqual( instanceOf( arr, Int16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=uint16)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool( 'uint16' ); + t.strictEqual( instanceOf( arr, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=int8)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool( 'int8' ); + t.strictEqual( instanceOf( arr, Int8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=uint8)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool( 'uint8' ); + t.strictEqual( instanceOf( arr, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=uint8c)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool( 'uint8c' ); + t.strictEqual( instanceOf( arr, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (default, length)', function test( t ) { + var typedarraypool = factory(); + var arr; + + arr = typedarraypool( 10 ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=float64, length)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool( 10, 'float64' ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=float32, length)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool( 10, 'float32' ); + t.strictEqual( instanceOf( arr, Float32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=int32, length)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool( 10, 'int32' ); + t.strictEqual( instanceOf( arr, Int32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=uint32, length)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool( 10, 'uint32' ); + t.strictEqual( instanceOf( arr, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=int16, length)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool( 10, 'int16' ); + t.strictEqual( instanceOf( arr, Int16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=uint16, length)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool( 10, 'uint16' ); + t.strictEqual( instanceOf( arr, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=int8, length)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool( 10, 'int8' ); + t.strictEqual( instanceOf( arr, Int8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=uint8, length)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool( 10, 'uint8' ); + t.strictEqual( instanceOf( arr, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=uint8c, length)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool( 10, 'uint8c' ); + t.strictEqual( instanceOf( arr, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (default, array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = []; + out = typedarraypool( arr ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=float64, array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = []; + out = typedarraypool( arr, 'float64' ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr, 'float64' ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=float32, array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = []; + out = typedarraypool( arr, 'float32' ); + t.strictEqual( instanceOf( out, Float32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr, 'float32' ); + t.strictEqual( instanceOf( out, Float32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=int32, array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = []; + out = typedarraypool( arr, 'int32' ); + t.strictEqual( instanceOf( out, Int32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr, 'int32' ); + t.strictEqual( instanceOf( out, Int32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=uint32, array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = []; + out = typedarraypool( arr, 'uint32' ); + t.strictEqual( instanceOf( out, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr, 'uint32' ); + t.strictEqual( instanceOf( out, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=int16, array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = []; + out = typedarraypool( arr, 'int16' ); + t.strictEqual( instanceOf( out, Int16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr, 'int16' ); + t.strictEqual( instanceOf( out, Int16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=uint16, array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = []; + out = typedarraypool( arr, 'uint16' ); + t.strictEqual( instanceOf( out, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr, 'uint16' ); + t.strictEqual( instanceOf( out, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=int8, array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = []; + out = typedarraypool( arr, 'int8' ); + t.strictEqual( instanceOf( out, Int8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr, 'int8' ); + t.strictEqual( instanceOf( out, Int8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=uint8, array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = []; + out = typedarraypool( arr, 'uint8' ); + t.strictEqual( instanceOf( out, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr, 'uint8' ); + t.strictEqual( instanceOf( out, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=uint8c, array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = []; + out = typedarraypool( arr, 'uint8c' ); + t.strictEqual( instanceOf( out, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr, 'uint8c' ); + t.strictEqual( instanceOf( out, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (default, typed array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = new Float64Array( 0 ); + out = typedarraypool( arr ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=float64, typed array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = new Float64Array( 0 ); + out = typedarraypool( arr, 'float64' ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr, 'float64' ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=float32, typed array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = new Uint32Array( 0 ); + out = typedarraypool( arr, 'float32' ); + t.strictEqual( instanceOf( out, Float32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Uint32Array( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr, 'float32' ); + t.strictEqual( instanceOf( out, Float32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=int32, typed array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = new Float32Array( 0 ); + out = typedarraypool( arr, 'int32' ); + t.strictEqual( instanceOf( out, Int32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr, 'int32' ); + t.strictEqual( instanceOf( out, Int32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=uint32, typed array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = new Uint8ClampedArray( 0 ); + out = typedarraypool( arr, 'uint32' ); + t.strictEqual( instanceOf( out, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Uint8ClampedArray( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr, 'uint32' ); + t.strictEqual( instanceOf( out, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=int16, typed array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = new Float64Array( 0 ); + out = typedarraypool( arr, 'int16' ); + t.strictEqual( instanceOf( out, Int16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr, 'int16' ); + t.strictEqual( instanceOf( out, Int16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=uint16, typed array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = new Int8Array( 0 ); + out = typedarraypool( arr, 'uint16' ); + t.strictEqual( instanceOf( out, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Int8Array( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr, 'uint16' ); + t.strictEqual( instanceOf( out, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=int8, typed array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = new Int16Array( 0 ); + out = typedarraypool( arr, 'int8' ); + t.strictEqual( instanceOf( out, Int8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Int16Array( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr, 'int8' ); + t.strictEqual( instanceOf( out, Int8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=uint8, typed array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = new Int32Array( 0 ); + out = typedarraypool( arr, 'uint8' ); + t.strictEqual( instanceOf( out, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Int32Array( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr, 'uint8' ); + t.strictEqual( instanceOf( out, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a function which returns a typed array (dtype=uint8c, typed array)', function test( t ) { + var typedarraypool; + var arr; + var out; + + typedarraypool = factory(); + + arr = new Float32Array( 0 ); + out = typedarraypool( arr, 'uint8c' ); + t.strictEqual( instanceOf( out, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr, 'uint8c' ); + t.strictEqual( instanceOf( out, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a `malloc` method which is a circular reference', function test( t ) { + var typedarraypool = factory(); + t.strictEqual( typedarraypool, typedarraypool.malloc, 'is circular reference' ); + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (default)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool.calloc(); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (dtype=float64)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool.calloc( 'float64' ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (dtype=float32)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool.calloc( 'float32' ); + t.strictEqual( instanceOf( arr, Float32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (dtype=int32)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool.calloc( 'int32' ); + t.strictEqual( instanceOf( arr, Int32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (dtype=uint32)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool.calloc( 'uint32' ); + t.strictEqual( instanceOf( arr, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (dtype=int16)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool.calloc( 'int16' ); + t.strictEqual( instanceOf( arr, Int16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (dtype=uint16)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool.calloc( 'uint16' ); + t.strictEqual( instanceOf( arr, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (dtype=int8)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool.calloc( 'int8' ); + t.strictEqual( instanceOf( arr, Int8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (dtype=uint8)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool.calloc( 'uint8' ); + t.strictEqual( instanceOf( arr, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (dtype=uint8c)', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + arr = typedarraypool.calloc( 'uint8c' ); + t.strictEqual( instanceOf( arr, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (default, length)', function test( t ) { + var typedarraypool; + var arr; + var tmp; + var i; + + typedarraypool = factory(); + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10 ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10 ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0.0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (dtype=float64, length)', function test( t ) { + var typedarraypool; + var arr; + var tmp; + var i; + + typedarraypool = factory(); + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10, 'float64' ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10, 'float64' ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0.0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (dtype=float32, length)', function test( t ) { + var typedarraypool; + var arr; + var tmp; + var i; + + typedarraypool = factory(); + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10, 'float32' ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10, 'float32' ); + t.strictEqual( instanceOf( arr, Float32Array ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0.0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (dtype=int32, length)', function test( t ) { + var typedarraypool; + var arr; + var tmp; + var i; + + typedarraypool = factory(); + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10, 'int32' ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10, 'int32' ); + t.strictEqual( instanceOf( arr, Int32Array ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (dtype=uint32, length)', function test( t ) { + var typedarraypool; + var arr; + var tmp; + var i; + + typedarraypool = factory(); + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10, 'uint32' ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10, 'uint32' ); + t.strictEqual( instanceOf( arr, Uint32Array ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (dtype=int16, length)', function test( t ) { + var typedarraypool; + var arr; + var tmp; + var i; + + typedarraypool = factory(); + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10, 'int16' ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10, 'int16' ); + t.strictEqual( instanceOf( arr, Int16Array ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (dtype=uint16, length)', function test( t ) { + var typedarraypool; + var arr; + var tmp; + var i; + + typedarraypool = factory(); + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10, 'uint16' ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10, 'uint16' ); + t.strictEqual( instanceOf( arr, Uint16Array ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (dtype=int8, length)', function test( t ) { + var typedarraypool; + var arr; + var tmp; + var i; + + typedarraypool = factory(); + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10, 'int8' ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10, 'int8' ); + t.strictEqual( instanceOf( arr, Int8Array ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (dtype=uint8, length)', function test( t ) { + var typedarraypool; + var arr; + var tmp; + var i; + + typedarraypool = factory(); + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10, 'uint8' ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10, 'uint8' ); + t.strictEqual( instanceOf( arr, Uint8Array ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method which returns a zero-initialized typed array (dtype=uint8c, length)', function test( t ) { + var typedarraypool; + var arr; + var tmp; + var i; + + typedarraypool = factory(); + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10, 'uint8c' ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10, 'uint8c' ); + t.strictEqual( instanceOf( arr, Uint8ClampedArray ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method for "freeing" allocated typed arrays', function test( t ) { + var typedarraypool; + var arr; + var buf; + var i; + + typedarraypool = factory(); + typedarraypool.clear(); + + arr = typedarraypool( 10, 'uint8c' ); + buf = arr.buffer; + typedarraypool.free( arr ); + + for ( i = 0; i < 10; i++ ) { + arr = typedarraypool( 10, 'uint8c' ); + t.strictEqual( arr.buffer, buf, 'returns expected value' ); + typedarraypool.free( arr ); + } + typedarraypool.clear(); + t.end(); +}); + +tape( 'attached to the returned function is a method for "freeing" allocated typed array buffers', function test( t ) { + var typedarraypool; + var arr; + var buf; + var i; + + typedarraypool = factory(); + typedarraypool.clear(); + + arr = typedarraypool( 10, 'uint8c' ); + buf = arr.buffer; + typedarraypool.free( buf ); + + for ( i = 0; i < 10; i++ ) { + arr = typedarraypool( 10, 'uint8c' ); + t.strictEqual( arr.buffer, buf, 'returns expected value' ); + typedarraypool.free( arr.buffer ); + } + typedarraypool.clear(); + t.end(); +}); + +tape( 'attached to the returned function is a method for "freeing" allocated typed arrays which does not allow for "freeing" allocated typed arrays more than once before being reallocated', function test( t ) { + var typedarraypool; + var bool; + var arr; + + typedarraypool = factory(); + typedarraypool.clear(); + + arr = typedarraypool( 10, 'uint8c' ); + bool = typedarraypool.free( arr ); + t.strictEqual( bool, true, 'returns expected value' ); + + bool = typedarraypool.free( arr ); + t.strictEqual( bool, false, 'returns expected value' ); + + typedarraypool.clear(); + t.end(); +}); + +tape( 'attached to the returned function is a method for "freeing" allocated typed array buffers which does not allow for "freeing" allocated typed array buffers more than once before being reallocated', function test( t ) { + var typedarraypool; + var bool; + var arr; + var buf; + + typedarraypool = factory(); + typedarraypool.clear(); + + arr = typedarraypool( 10, 'uint8c' ); + buf = arr.buffer; + bool = typedarraypool.free( buf ); + t.strictEqual( bool, true, 'returns expected value' ); + + bool = typedarraypool.free( buf ); + t.strictEqual( bool, false, 'returns expected value' ); + + typedarraypool.clear(); + t.end(); +}); + +tape( 'attached to the returned function is a method for "freeing" allocated typed array and typed array buffers which throws if not provided either a typed array or typed array buffer', function test( t ) { + var typedarraypool; + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + [], + {}, + function noop() {} + ]; + + typedarraypool = factory(); + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarraypool.free( value ); + }; + } +}); + +tape( 'attached to the returned function is a property which returns the pool\'s high water mark', function test( t ) { + var typedarraypool = factory(); + t.strictEqual( typeof typedarraypool.highWaterMark, 'number', 'has property' ); + t.end(); +}); + +tape( 'the function supports specifying a high water mark which limits the total amount of memory a pool can allocate', function test( t ) { + var typedarraypool; + var arr1; + var arr2; + + typedarraypool = factory({ + 'highWaterMark': 64 // bytes + }); + + typedarraypool.clear(); + + arr1 = typedarraypool( 8, 'float64' ); + t.strictEqual( arr1.length, 8, 'returns expected value' ); + t.strictEqual( arr1.byteLength, 64, 'returns expected value' ); + + // Specify an array length: + arr2 = typedarraypool( 1e6, 'float64' ); + t.strictEqual( arr2, null, 'returns expected value' ); + + arr2 = typedarraypool.malloc( 1e6, 'float64' ); + t.strictEqual( arr2, null, 'returns expected value' ); + + arr2 = typedarraypool.calloc( 1e6, 'float64' ); + t.strictEqual( arr2, null, 'returns expected value' ); + + // Provide an array from which to copy elements: + arr2 = typedarraypool( new Float64Array( 20 ), 'float64' ); + t.strictEqual( arr2, null, 'returns expected value' ); + + arr2 = typedarraypool.malloc( new Float64Array( 20 ), 'float64' ); + t.strictEqual( arr2, null, 'returns expected value' ); + + arr2 = typedarraypool.calloc( new Float64Array( 20 ), 'float64' ); + t.strictEqual( arr2, null, 'returns expected value' ); + + typedarraypool.free( arr1 ); + + // Specify an array length: + arr2 = typedarraypool( 1e6, 'float64' ); + t.strictEqual( arr2, null, 'returns expected value' ); + + arr2 = typedarraypool.malloc( 1e6, 'float64' ); + t.strictEqual( arr2, null, 'returns expected value' ); + + arr2 = typedarraypool.calloc( 1e6, 'float64' ); + t.strictEqual( arr2, null, 'returns expected value' ); + + // Provide an array from which to copy elements: + arr2 = typedarraypool( new Float64Array( 20 ), 'float64' ); + t.strictEqual( arr2, null, 'returns expected value' ); + + arr2 = typedarraypool.malloc( new Float64Array( 20 ), 'float64' ); + t.strictEqual( arr2, null, 'returns expected value' ); + + arr2 = typedarraypool.calloc( new Float64Array( 20 ), 'float64' ); + t.strictEqual( arr2, null, 'returns expected value' ); + + // Create an array which is less than or equal to the high water mark: + arr2 = typedarraypool( 8, 'float64' ); + t.strictEqual( arr2.length, 8, 'returns expected value' ); + t.strictEqual( arr2.byteLength, 64, 'returns expected value' ); + + typedarraypool.free( arr2 ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a property which returns the total number of accumulated bytes', function test( t ) { + var typedarraypool; + var arr; + + typedarraypool = factory(); + + typedarraypool.clear(); + t.strictEqual( typedarraypool.nbytes, 0, 'returns expected value' ); + + arr = typedarraypool( 10, 'uint8' ); + t.strictEqual( typedarraypool.nbytes > 0 && typedarraypool.nbytes < typedarraypool.highWaterMark, true, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the returned function is a method for clearing a typed array pool of freed typed array buffers', function test( t ) { + var typedarraypool; + var arrs; + var i; + + typedarraypool = factory(); + + typedarraypool.clear(); + t.strictEqual( typedarraypool.nbytes, 0, 'returns expected value' ); + + arrs = new Array( 10 ); + for ( i = 0; i < arrs.length; i++ ) { + arrs[ i ] = typedarraypool( 10, 'uint8' ); + t.strictEqual( typedarraypool.nbytes > 0 && typedarraypool.nbytes < typedarraypool.highWaterMark, true, 'returns expected value' ); + } + for ( i = 0; i < arrs.length; i++ ) { + typedarraypool.free( arrs[ i ] ); + } + t.strictEqual( typedarraypool.nbytes > 0 && typedarraypool.nbytes < typedarraypool.highWaterMark, true, 'returns expected value' ); + + typedarraypool.clear(); + t.strictEqual( typedarraypool.nbytes, 0, 'returns expected value' ); + + t.end(); +}); diff --git a/pool/test/test.js b/pool/test/test.js new file mode 100644 index 00000000..bdb4e9ab --- /dev/null +++ b/pool/test/test.js @@ -0,0 +1,1531 @@ +/* eslint-disable max-lines */ + +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var Float64Array = require( '@stdlib/array/float64' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Int8Array = require( '@stdlib/array/int8' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); +var instanceOf = require( '@stdlib/assert/instance-of' ); +var randu = require( '@stdlib/random/base/randu' ); +var typedarraypool = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof typedarraypool, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error if provided an unrecognized data type (only argument)', function test( t ) { + var values; + var i; + + values = [ + '5', + 'beep', + 'typedarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarraypool( value ); + }; + } +}); + +tape( 'the function throws an error if provided an unrecognized data type (length)', function test( t ) { + var values; + var i; + + values = [ + '5', + 'beep', + 'typedarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarraypool( 10, value ); + }; + } +}); + +tape( 'the function throws an error if provided an unrecognized data type (typed array)', function test( t ) { + var values; + var i; + + values = [ + '5', + 'beep', + 'typedarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarraypool( new Float64Array( 10 ), value ); + }; + } +}); + +tape( 'the function throws an error if provided an unrecognized data type (array-like object)', function test( t ) { + var values; + var i; + + values = [ + '5', + 'beep', + 'typedarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarraypool( [ 1, 2, 3 ], value ); + }; + } +}); + +tape( 'the function throws an error if provided an invalid array length or array-like object argument (no data type argument)', function test( t ) { + var values; + var i; + + values = [ + 3.14, + -1, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarraypool( value ); + }; + } +}); + +tape( 'the function throws an error if provided an invalid array length or array-like object argument (data type argument)', function test( t ) { + var values; + var i; + + values = [ + 3.14, + -1, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarraypool( value, 'float64' ); + }; + } +}); + +tape( 'the function returns a typed array (default)', function test( t ) { + var arr = typedarraypool(); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float64)', function test( t ) { + var arr = typedarraypool( 'float64' ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float32)', function test( t ) { + var arr = typedarraypool( 'float32' ); + t.strictEqual( instanceOf( arr, Float32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int32)', function test( t ) { + var arr = typedarraypool( 'int32' ); + t.strictEqual( instanceOf( arr, Int32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint32)', function test( t ) { + var arr = typedarraypool( 'uint32' ); + t.strictEqual( instanceOf( arr, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int16)', function test( t ) { + var arr = typedarraypool( 'int16' ); + t.strictEqual( instanceOf( arr, Int16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint16)', function test( t ) { + var arr = typedarraypool( 'uint16' ); + t.strictEqual( instanceOf( arr, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int8)', function test( t ) { + var arr = typedarraypool( 'int8' ); + t.strictEqual( instanceOf( arr, Int8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8)', function test( t ) { + var arr = typedarraypool( 'uint8' ); + t.strictEqual( instanceOf( arr, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8c)', function test( t ) { + var arr = typedarraypool( 'uint8c' ); + t.strictEqual( instanceOf( arr, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (default, length)', function test( t ) { + var arr = typedarraypool( 10 ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float64, length)', function test( t ) { + var arr = typedarraypool( 10, 'float64' ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float32, length)', function test( t ) { + var arr = typedarraypool( 10, 'float32' ); + t.strictEqual( instanceOf( arr, Float32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int32, length)', function test( t ) { + var arr = typedarraypool( 10, 'int32' ); + t.strictEqual( instanceOf( arr, Int32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint32, length)', function test( t ) { + var arr = typedarraypool( 10, 'uint32' ); + t.strictEqual( instanceOf( arr, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int16, length)', function test( t ) { + var arr = typedarraypool( 10, 'int16' ); + t.strictEqual( instanceOf( arr, Int16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint16, length)', function test( t ) { + var arr = typedarraypool( 10, 'uint16' ); + t.strictEqual( instanceOf( arr, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int8, length)', function test( t ) { + var arr = typedarraypool( 10, 'int8' ); + t.strictEqual( instanceOf( arr, Int8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8, length)', function test( t ) { + var arr = typedarraypool( 10, 'uint8' ); + t.strictEqual( instanceOf( arr, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8c, length)', function test( t ) { + var arr = typedarraypool( 10, 'uint8c' ); + t.strictEqual( instanceOf( arr, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (default, array)', function test( t ) { + var arr; + var out; + + arr = []; + out = typedarraypool( arr ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float64, array)', function test( t ) { + var arr; + var out; + + arr = []; + out = typedarraypool( arr, 'float64' ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr, 'float64' ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float32, array)', function test( t ) { + var arr; + var out; + + arr = []; + out = typedarraypool( arr, 'float32' ); + t.strictEqual( instanceOf( out, Float32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr, 'float32' ); + t.strictEqual( instanceOf( out, Float32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int32, array)', function test( t ) { + var arr; + var out; + + arr = []; + out = typedarraypool( arr, 'int32' ); + t.strictEqual( instanceOf( out, Int32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr, 'int32' ); + t.strictEqual( instanceOf( out, Int32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint32, array)', function test( t ) { + var arr; + var out; + + arr = []; + out = typedarraypool( arr, 'uint32' ); + t.strictEqual( instanceOf( out, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr, 'uint32' ); + t.strictEqual( instanceOf( out, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int16, array)', function test( t ) { + var arr; + var out; + + arr = []; + out = typedarraypool( arr, 'int16' ); + t.strictEqual( instanceOf( out, Int16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr, 'int16' ); + t.strictEqual( instanceOf( out, Int16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint16, array)', function test( t ) { + var arr; + var out; + + arr = []; + out = typedarraypool( arr, 'uint16' ); + t.strictEqual( instanceOf( out, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr, 'uint16' ); + t.strictEqual( instanceOf( out, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int8, array)', function test( t ) { + var arr; + var out; + + arr = []; + out = typedarraypool( arr, 'int8' ); + t.strictEqual( instanceOf( out, Int8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr, 'int8' ); + t.strictEqual( instanceOf( out, Int8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8, array)', function test( t ) { + var arr; + var out; + + arr = []; + out = typedarraypool( arr, 'uint8' ); + t.strictEqual( instanceOf( out, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr, 'uint8' ); + t.strictEqual( instanceOf( out, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8c, array)', function test( t ) { + var arr; + var out; + + arr = []; + out = typedarraypool( arr, 'uint8c' ); + t.strictEqual( instanceOf( out, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = [ 1.0, 2.0, 3.0 ]; + out = typedarraypool( arr, 'uint8c' ); + t.strictEqual( instanceOf( out, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (default, typed array)', function test( t ) { + var arr; + var out; + + arr = new Float64Array( 0 ); + out = typedarraypool( arr ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float64, typed array)', function test( t ) { + var arr; + var out; + + arr = new Float64Array( 0 ); + out = typedarraypool( arr, 'float64' ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr, 'float64' ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float32, typed array)', function test( t ) { + var arr; + var out; + + arr = new Uint32Array( 0 ); + out = typedarraypool( arr, 'float32' ); + t.strictEqual( instanceOf( out, Float32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Uint32Array( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr, 'float32' ); + t.strictEqual( instanceOf( out, Float32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int32, typed array)', function test( t ) { + var arr; + var out; + + arr = new Float32Array( 0 ); + out = typedarraypool( arr, 'int32' ); + t.strictEqual( instanceOf( out, Int32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr, 'int32' ); + t.strictEqual( instanceOf( out, Int32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint32, typed array)', function test( t ) { + var arr; + var out; + + arr = new Uint8ClampedArray( 0 ); + out = typedarraypool( arr, 'uint32' ); + t.strictEqual( instanceOf( out, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Uint8ClampedArray( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr, 'uint32' ); + t.strictEqual( instanceOf( out, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int16, typed array)', function test( t ) { + var arr; + var out; + + arr = new Float64Array( 0 ); + out = typedarraypool( arr, 'int16' ); + t.strictEqual( instanceOf( out, Int16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr, 'int16' ); + t.strictEqual( instanceOf( out, Int16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint16, typed array)', function test( t ) { + var arr; + var out; + + arr = new Int8Array( 0 ); + out = typedarraypool( arr, 'uint16' ); + t.strictEqual( instanceOf( out, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Int8Array( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr, 'uint16' ); + t.strictEqual( instanceOf( out, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int8, typed array)', function test( t ) { + var arr; + var out; + + arr = new Int16Array( 0 ); + out = typedarraypool( arr, 'int8' ); + t.strictEqual( instanceOf( out, Int8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Int16Array( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr, 'int8' ); + t.strictEqual( instanceOf( out, Int8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8, typed array)', function test( t ) { + var arr; + var out; + + arr = new Int32Array( 0 ); + out = typedarraypool( arr, 'uint8' ); + t.strictEqual( instanceOf( out, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Int32Array( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr, 'uint8' ); + t.strictEqual( instanceOf( out, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8c, typed array)', function test( t ) { + var arr; + var out; + + arr = new Float32Array( 0 ); + out = typedarraypool( arr, 'uint8c' ); + t.strictEqual( instanceOf( out, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( out.length, 0, 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + out = typedarraypool( arr, 'uint8c' ); + t.strictEqual( instanceOf( out, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + + typedarraypool.free( out ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a `malloc` method which is a circular reference', function test( t ) { + t.strictEqual( typedarraypool, typedarraypool.malloc, 'is circular reference' ); + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (default)', function test( t ) { + var arr = typedarraypool.calloc(); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (dtype=float64)', function test( t ) { + var arr = typedarraypool.calloc( 'float64' ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (dtype=float32)', function test( t ) { + var arr = typedarraypool.calloc( 'float32' ); + t.strictEqual( instanceOf( arr, Float32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (dtype=int32)', function test( t ) { + var arr = typedarraypool.calloc( 'int32' ); + t.strictEqual( instanceOf( arr, Int32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (dtype=uint32)', function test( t ) { + var arr = typedarraypool.calloc( 'uint32' ); + t.strictEqual( instanceOf( arr, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (dtype=int16)', function test( t ) { + var arr = typedarraypool.calloc( 'int16' ); + t.strictEqual( instanceOf( arr, Int16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (dtype=uint16)', function test( t ) { + var arr = typedarraypool.calloc( 'uint16' ); + t.strictEqual( instanceOf( arr, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (dtype=int8)', function test( t ) { + var arr = typedarraypool.calloc( 'int8' ); + t.strictEqual( instanceOf( arr, Int8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (dtype=uint8)', function test( t ) { + var arr = typedarraypool.calloc( 'uint8' ); + t.strictEqual( instanceOf( arr, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (dtype=uint8c)', function test( t ) { + var arr = typedarraypool.calloc( 'uint8c' ); + t.strictEqual( instanceOf( arr, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (default, length)', function test( t ) { + var arr; + var tmp; + var i; + + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10 ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10 ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0.0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (dtype=float64, length)', function test( t ) { + var arr; + var tmp; + var i; + + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10, 'float64' ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10, 'float64' ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0.0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (dtype=float32, length)', function test( t ) { + var arr; + var tmp; + var i; + + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10, 'float32' ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10, 'float32' ); + t.strictEqual( instanceOf( arr, Float32Array ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0.0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (dtype=int32, length)', function test( t ) { + var arr; + var tmp; + var i; + + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10, 'int32' ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10, 'int32' ); + t.strictEqual( instanceOf( arr, Int32Array ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (dtype=uint32, length)', function test( t ) { + var arr; + var tmp; + var i; + + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10, 'uint32' ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10, 'uint32' ); + t.strictEqual( instanceOf( arr, Uint32Array ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (dtype=int16, length)', function test( t ) { + var arr; + var tmp; + var i; + + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10, 'int16' ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10, 'int16' ); + t.strictEqual( instanceOf( arr, Int16Array ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (dtype=uint16, length)', function test( t ) { + var arr; + var tmp; + var i; + + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10, 'uint16' ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10, 'uint16' ); + t.strictEqual( instanceOf( arr, Uint16Array ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (dtype=int8, length)', function test( t ) { + var arr; + var tmp; + var i; + + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10, 'int8' ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10, 'int8' ); + t.strictEqual( instanceOf( arr, Int8Array ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (dtype=uint8, length)', function test( t ) { + var arr; + var tmp; + var i; + + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10, 'uint8' ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10, 'uint8' ); + t.strictEqual( instanceOf( arr, Uint8Array ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method which returns a zero-initialized typed array (dtype=uint8c, length)', function test( t ) { + var arr; + var tmp; + var i; + + typedarraypool.clear(); + + tmp = typedarraypool.malloc( 10, 'uint8c' ); + for ( i = 0; i < tmp.length; i++ ) { + tmp[ i ] = randu() * 256.0; + } + typedarraypool.free( tmp ); + + arr = typedarraypool.calloc( 10, 'uint8c' ); + t.strictEqual( instanceOf( arr, Uint8ClampedArray ), true, 'returns expected value' ); + t.notEqual( arr, tmp, 'returns a new view' ); + t.strictEqual( arr.buffer, tmp.buffer, 'same array buffer' ); + + t.strictEqual( arr.length, 10, 'returns expected value' ); + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( arr[ i ], 0, 'returns expected value' ); + } + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method for "freeing" allocated typed arrays', function test( t ) { + var arr; + var buf; + var i; + + typedarraypool.clear(); + + arr = typedarraypool( 10, 'uint8c' ); + buf = arr.buffer; + typedarraypool.free( arr ); + + for ( i = 0; i < 10; i++ ) { + arr = typedarraypool( 10, 'uint8c' ); + t.strictEqual( arr.buffer, buf, 'returns expected value' ); + typedarraypool.free( arr ); + } + typedarraypool.clear(); + t.end(); +}); + +tape( 'attached to the exported function is a method for "freeing" allocated typed array buffers', function test( t ) { + var arr; + var buf; + var i; + + typedarraypool.clear(); + + arr = typedarraypool( 10, 'uint8c' ); + buf = arr.buffer; + typedarraypool.free( buf ); + + for ( i = 0; i < 10; i++ ) { + arr = typedarraypool( 10, 'uint8c' ); + t.strictEqual( arr.buffer, buf, 'returns expected value' ); + typedarraypool.free( arr.buffer ); + } + typedarraypool.clear(); + t.end(); +}); + +tape( 'attached to the exported function is a method for "freeing" allocated typed arrays which does not allow for "freeing" allocated typed arrays more than once before being reallocated', function test( t ) { + var bool; + var arr; + + typedarraypool.clear(); + + arr = typedarraypool( 10, 'uint8c' ); + bool = typedarraypool.free( arr ); + t.strictEqual( bool, true, 'returns expected value' ); + + bool = typedarraypool.free( arr ); + t.strictEqual( bool, false, 'returns expected value' ); + + typedarraypool.clear(); + t.end(); +}); + +tape( 'attached to the exported function is a method for "freeing" allocated typed array buffers which does not allow for "freeing" allocated typed array buffers more than once before being reallocated', function test( t ) { + var bool; + var arr; + var buf; + + typedarraypool.clear(); + + arr = typedarraypool( 10, 'uint8c' ); + buf = arr.buffer; + bool = typedarraypool.free( buf ); + t.strictEqual( bool, true, 'returns expected value' ); + + bool = typedarraypool.free( buf ); + t.strictEqual( bool, false, 'returns expected value' ); + + typedarraypool.clear(); + t.end(); +}); + +tape( 'attached to the exported function is a method for "freeing" allocated typed array and typed array buffers which throws if not provided either a typed array or typed array buffer', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + [], + {}, + function noop() {} + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarraypool.free( value ); + }; + } +}); + +tape( 'attached to the exported function is a property which returns the pool\'s high water mark', function test( t ) { + t.strictEqual( typeof typedarraypool.highWaterMark, 'number', 'has property' ); + t.end(); +}); + +tape( 'attached to the exported function is a property which returns the total number of accumulated bytes', function test( t ) { + var arr; + + typedarraypool.clear(); + t.strictEqual( typedarraypool.nbytes, 0, 'returns expected value' ); + + arr = typedarraypool( 10, 'uint8' ); + t.strictEqual( typedarraypool.nbytes > 0 && typedarraypool.nbytes < typedarraypool.highWaterMark, true, 'returns expected value' ); + + typedarraypool.free( arr ); + typedarraypool.clear(); + + t.end(); +}); + +tape( 'attached to the exported function is a method for clearing a typed array pool of freed typed array buffers', function test( t ) { + var arrs; + var i; + + typedarraypool.clear(); + t.strictEqual( typedarraypool.nbytes, 0, 'returns expected value' ); + + arrs = new Array( 10 ); + for ( i = 0; i < arrs.length; i++ ) { + arrs[ i ] = typedarraypool( 10, 'uint8' ); + t.strictEqual( typedarraypool.nbytes > 0 && typedarraypool.nbytes < typedarraypool.highWaterMark, true, 'returns expected value' ); + } + for ( i = 0; i < arrs.length; i++ ) { + typedarraypool.free( arrs[ i ] ); + } + t.strictEqual( typedarraypool.nbytes > 0 && typedarraypool.nbytes < typedarraypool.highWaterMark, true, 'returns expected value' ); + + typedarraypool.clear(); + t.strictEqual( typedarraypool.nbytes, 0, 'returns expected value' ); + + t.end(); +}); + +tape( 'attached to the exported function is a method for creating typed array memory pools', function test( t ) { + t.strictEqual( typeof typedarraypool.factory, 'function', 'has method' ); + t.end(); +}); diff --git a/promotion-rules/README.md b/promotion-rules/README.md new file mode 100644 index 00000000..431f71eb --- /dev/null +++ b/promotion-rules/README.md @@ -0,0 +1,141 @@ + + +# Promotion Rules + +> Return the array [data type][@stdlib/array/dtypes] with the smallest size and closest "kind" to which array [data types][@stdlib/array/dtypes] can be **safely** cast. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var promotionRules = require( '@stdlib/array/promotion-rules' ); +``` + +#### promotionRules( \[dtype1, dtype2] ) + +If provided [data types][@stdlib/array/dtypes], returns the array [data type][@stdlib/array/dtypes] with the smallest size and closest "kind" to which array [data types][@stdlib/array/dtypes] can be **safely** cast. + +```javascript +var out = promotionRules( 'float32', 'uint32' ); +// returns 'float64' +``` + +If not provided [data types][@stdlib/array/dtypes], the function returns a promotion table. + +```javascript +var out = promotionRules(); +// returns {...} + +var f32 = out[ 'float32' ]; +// returns {...} + +var rule = f32[ 'uint32' ]; +// returns 'float64' +``` + +If provided an unrecognized or unsupported `dtype`, the function returns `null`. + +```javascript +var out = promotionRules( 'foo', 'generic' ); +// returns null +``` + +
+ + + + + +
+ +## Notes + +- If a [data type][@stdlib/array/dtypes] to which [data types][@stdlib/array/dtypes] can be safely cast does **not** exist (or is not supported), the function returns `-1`. + +
+ + + + + +
+ +## Examples + + + +```javascript +var dtypes = require( '@stdlib/array/dtypes' ); +var promotionRules = require( '@stdlib/array/promotion-rules' ); + +var DTYPES; +var dt1; +var dt2; +var dt; +var i; +var j; + +// Get the list of supported array data types: +DTYPES = dtypes(); + +// Print the promotion rule for each pair of array data types... +for ( i = 0; i < DTYPES.length; i++ ) { + dt1 = DTYPES[ i ]; + for ( j = 0; j < DTYPES.length; j++ ) { + dt2 = DTYPES[ j ]; + dt = promotionRules( dt1, dt2 ); + console.log( '(%s, %s) => %s', dt1, dt2, dt ); + } +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/promotion-rules/benchmark/benchmark.js b/promotion-rules/benchmark/benchmark.js new file mode 100644 index 00000000..1d378b71 --- /dev/null +++ b/promotion-rules/benchmark/benchmark.js @@ -0,0 +1,77 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isString = require( '@stdlib/assert/is-string' ).isPrimitive; +var dtypes = require( '@stdlib/array/dtypes' ); +var pkg = require( './../package.json' ).name; +var promotionRules = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = promotionRules(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::dtypes', function benchmark( b ) { + var out; + var dt; + var N; + var i; + var j; + var k; + + dt = dtypes(); + N = dt.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + j = i % N; + k = (i+1) % N; + out = promotionRules( dt[ j ], dt[ k ] ); + if ( typeof out !== 'string' && out !== -1 ) { + b.fail( 'should return a string or -1' ); + } + } + b.toc(); + if ( !isString( out ) && out !== -1 ) { + b.fail( 'should return a string or -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/promotion-rules/docs/repl.txt b/promotion-rules/docs/repl.txt new file mode 100644 index 00000000..57fd02a3 --- /dev/null +++ b/promotion-rules/docs/repl.txt @@ -0,0 +1,33 @@ + +{{alias}}( [dtype1, dtype2] ) + Returns the array data type with the smallest size and closest "kind" to + which array data types can be safely cast. + + If not provided data types, the function returns a type promotion table. + + If a data type to which data types can be safely cast does *not* exist (or + is not supported), the function returns `-1`. + + If provided an unrecognized data type, the function returns `null`. + + Parameters + ---------- + dtype1: string (optional) + Array data type. + + dtype2: string (optional) + Array data type. + + Returns + ------- + out: Object|string|integer|null + Promotion rule(s). + + Examples + -------- + > var out = {{alias}}( 'float32', 'int32' ) + 'float64' + + See Also + -------- + diff --git a/promotion-rules/docs/types/index.d.ts b/promotion-rules/docs/types/index.d.ts new file mode 100644 index 00000000..59731d6d --- /dev/null +++ b/promotion-rules/docs/types/index.d.ts @@ -0,0 +1,60 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/** +* Interface describing a promotion table. +*/ +interface Table { + // Table properties: + [key: string]: string | number; +} + +/** +* Returns the array data type with the smallest size and closest "kind" to which array data types can be safely cast. +* +* @param dtype1 - array data type +* @param dtype2 - array data type +* @returns promotion rule(s) or null +* +* @example +* var dt = promotionRules( 'float32', 'uint32' ); +* // returns 'float64' +* +* @example +* var dt = promotionRules( 'float32', 'foo' ); +* // returns null +*/ +declare function promotionRules( dtype1: string, dtype2: string ): number | string | null; // tslint-disable-line max-line-length + +/** +* Returns a type promotion table displaying array data types with the smallest size and closest "kind" to which array data types can be safely cast. +* +* @returns promotion rule table +* +* @example +* var table = promotionRules(); +* // returns {...} +*/ +declare function promotionRules(): Table; + + +// EXPORTS // + +export = promotionRules; diff --git a/promotion-rules/docs/types/test.ts b/promotion-rules/docs/types/test.ts new file mode 100644 index 00000000..31fa0009 --- /dev/null +++ b/promotion-rules/docs/types/test.ts @@ -0,0 +1,56 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import promotionRules = require( './index' ); + + +// TESTS // + +// The function returns an object, array of strings, or null... +{ + promotionRules(); // $ExpectType Table + promotionRules( 'float32', 'uint32' ); // $ExpectType string | number | null + promotionRules( 'int32', 'generic' ); // $ExpectType string | number | null + promotionRules( 'float32', 'foo' ); // $ExpectType string | number | null +} + +// The function does not compile if provided a first argument that is not a string... +{ + promotionRules( 123, 'float64' ); // $ExpectError + promotionRules( true, 'float64' ); // $ExpectError + promotionRules( false, 'float64' ); // $ExpectError + promotionRules( null, 'float64' ); // $ExpectError + promotionRules( {}, 'float64' ); // $ExpectError + promotionRules( ( x: number ): number => x, 'float64' ); // $ExpectError +} + +// The function does not compile if provided a second argument that is not a string... +{ + promotionRules( 'int32', 123 ); // $ExpectError + promotionRules( 'int32', true ); // $ExpectError + promotionRules( 'int32', false ); // $ExpectError + promotionRules( 'int32', null ); // $ExpectError + promotionRules( 'int32', {} ); // $ExpectError + promotionRules( 'int32', ( x: number ): number => x ); // $ExpectError +} + +// The function does not compile if provided more than one argument... +{ + promotionRules( 'float32' ); // $ExpectError + promotionRules( 'float32', 'int32', {} ); // $ExpectError +} diff --git a/promotion-rules/examples/index.js b/promotion-rules/examples/index.js new file mode 100644 index 00000000..a575e877 --- /dev/null +++ b/promotion-rules/examples/index.js @@ -0,0 +1,42 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var dtypes = require( '@stdlib/array/dtypes' ); +var promotionRules = require( './../lib' ); + +var DTYPES; +var dt1; +var dt2; +var dt; +var i; +var j; + +// Get the list of supported array data types: +DTYPES = dtypes(); + +// Print the promotion rule for each pair of array data types... +for ( i = 0; i < DTYPES.length; i++ ) { + dt1 = DTYPES[ i ]; + for ( j = 0; j < DTYPES.length; j++ ) { + dt2 = DTYPES[ j ]; + dt = promotionRules( dt1, dt2 ); + console.log( '(%s, %s) => %s', dt1, dt2, dt ); + } +} diff --git a/promotion-rules/lib/index.js b/promotion-rules/lib/index.js new file mode 100644 index 00000000..3616a72f --- /dev/null +++ b/promotion-rules/lib/index.js @@ -0,0 +1,46 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Return the array data type with the smallest size and closest "kind" to which array data types can be safely cast. +* +* @module @stdlib/array/promotion-rules +* +* @example +* var promotionRules = require( '@stdlib/array/promotion-rules' ); +* +* var table = promotionRules(); +* // returns {...} +* +* var dt = promotionRules( 'float32', 'uint32' ); +* // returns 'float64' +* +* dt = promotionRules( 'float32', 'foo' ); +* // returns null +*/ + +// MODULES // + +var promotionRules = require( './main.js' ); + + +// EXPORTS // + +module.exports = promotionRules; diff --git a/promotion-rules/lib/main.js b/promotion-rules/lib/main.js new file mode 100644 index 00000000..26653d00 --- /dev/null +++ b/promotion-rules/lib/main.js @@ -0,0 +1,102 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var objectKeys = require( '@stdlib/utils/keys' ); +var hasOwnProp = require( '@stdlib/assert/has-own-property' ); +var PROMOTION_RULES = require( './promotion_rules.json' ); + + +// FUNCTIONS // + +/** +* Generates a full table of promotion rules. +* +* @private +* @returns {Object} table +*/ +function generateFullTable() { + var dtypes; + var ntypes; + var out; + var tmp; + var dt1; + var dt2; + var o; + var j; + var i; + + out = {}; + dtypes = objectKeys( PROMOTION_RULES ); + ntypes = dtypes.length; + for ( i = 0; i < ntypes; i++ ) { + dt1 = dtypes[ i ]; + o = PROMOTION_RULES[ dt1 ]; + tmp = {}; + for ( j = 0; j < ntypes; j++ ) { + dt2 = dtypes[ j ]; + tmp[ dt2 ] = o[ dt2 ]; + } + out[ dt1 ] = tmp; + } + return out; +} + + +// MAIN // + +/** +* Returns the array data type with the smallest size and closest "kind" to which array data types can be safely cast. +* +* @param {string} [dtype1] - array data type +* @param {string} [dtype2] - array data type +* @returns {(Object|integer|string|null)} promotion rule(s) or null +* +* @example +* var table = promotionRules(); +* // returns {...} +* +* @example +* var dt = promotionRules( 'float32', 'uint32' ); +* // returns 'float64' +* +* @example +* var dt = promotionRules( 'float32', 'foo' ); +* // returns null +*/ +function promotionRules( dtype1, dtype2 ) { + var o; + if ( arguments.length === 0 ) { + return generateFullTable(); + } + if ( hasOwnProp( PROMOTION_RULES, dtype1 ) ) { + o = PROMOTION_RULES[ dtype1 ]; + if ( hasOwnProp( o, dtype2 ) ) { + return o[ dtype2 ]; + } + } + return null; +} + + +// EXPORTS // + +module.exports = promotionRules; diff --git a/promotion-rules/lib/promotion_rules.json b/promotion-rules/lib/promotion_rules.json new file mode 100644 index 00000000..e95f19c0 --- /dev/null +++ b/promotion-rules/lib/promotion_rules.json @@ -0,0 +1,122 @@ +{ + "float64": { + "float64": "float64", + "float32": "float64", + "int32": "float64", + "int16": "float64", + "int8": "float64", + "uint32": "float64", + "uint16": "float64", + "uint8": "float64", + "uint8c": "float64", + "generic": "generic" + }, + "float32": { + "float64": "float64", + "float32": "float32", + "int32": "float64", + "int16": "float32", + "int8": "float32", + "uint32": "float64", + "uint16": "float32", + "uint8": "float32", + "uint8c": "float32", + "generic": "generic" + }, + "int32": { + "float64": "float64", + "float32": "float64", + "int32": "int32", + "int16": "int32", + "int8": "int32", + "uint32": "float64", + "uint16": "int32", + "uint8": "int32", + "uint8c": "int32", + "generic": "generic" + }, + "int16": { + "float64": "float64", + "float32": "float32", + "int32": "int32", + "int16": "int16", + "int8": "int16", + "uint32": "float64", + "uint16": "int32", + "uint8": "int16", + "uint8c": "int16", + "generic": "generic" + }, + "int8": { + "float64": "float64", + "float32": "float32", + "int32": "int32", + "int16": "int16", + "int8": "int8", + "uint32": "float64", + "uint16": "int32", + "uint8": "int16", + "uint8c": "int16", + "generic": "generic" + }, + "uint32": { + "float64": "float64", + "float32": "float64", + "int32": "float64", + "int16": "float64", + "int8": "float64", + "uint32": "uint32", + "uint16": "uint32", + "uint8": "uint32", + "uint8c": "uint32", + "generic": "generic" + }, + "uint16": { + "float64": "float64", + "float32": "float32", + "int32": "int32", + "int16": "int32", + "int8": "int32", + "uint32": "uint32", + "uint16": "uint16", + "uint8": "uint16", + "uint8c": "uint16", + "generic": "generic" + }, + "uint8": { + "float64": "float64", + "float32": "float32", + "int32": "int32", + "int16": "int16", + "int8": "int16", + "uint32": "uint32", + "uint16": "uint16", + "uint8": "uint8", + "uint8c": "uint8", + "generic": "generic" + }, + "uint8c": { + "float64": "float64", + "float32": "float32", + "int32": "int32", + "int16": "int16", + "int8": "int16", + "uint32": "uint32", + "uint16": "uint16", + "uint8": "uint8", + "uint8c": "uint8", + "generic": "generic" + }, + "generic": { + "float64": "generic", + "float32": "generic", + "int32": "generic", + "int16": "generic", + "int8": "generic", + "uint32": "generic", + "uint16": "generic", + "uint8": "generic", + "uint8c": "generic", + "generic": "generic" + } +} diff --git a/promotion-rules/package.json b/promotion-rules/package.json new file mode 100644 index 00000000..fd27bb24 --- /dev/null +++ b/promotion-rules/package.json @@ -0,0 +1,68 @@ +{ + "name": "@stdlib/array/promotion-rules", + "version": "0.0.0", + "description": "Return the array data type with the smallest size and closest kind to which array data types can be safely cast.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "array", + "casting", + "cast", + "convert", + "conversion", + "rules", + "promotion", + "utilities", + "utility", + "utils", + "util" + ], + "__stdlib__": {} +} diff --git a/promotion-rules/test/test.js b/promotion-rules/test/test.js new file mode 100644 index 00000000..3bccf41e --- /dev/null +++ b/promotion-rules/test/test.js @@ -0,0 +1,91 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var dtypes = require( '@stdlib/array/dtypes' ); +var isObject = require( '@stdlib/assert/is-plain-object' ); +var promotionRules = require( './../lib' ); + + +// VARIABLES // + +var DTYPES = dtypes(); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof promotionRules, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'if not provided data types, the function returns a table', function test( t ) { + var out = promotionRules(); + t.strictEqual( isObject( out ), true, 'returns an object' ); + t.strictEqual( out[ 'float32' ][ 'uint32' ], 'float64', 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns the array data type with the smallest size and closest "kind" to which array data types can be safely cast', function test( t ) { + var table; + var dt1; + var dt2; + var dt; + var j; + var i; + + table = promotionRules(); + + for ( i = 0; i < DTYPES.length; i++ ) { + dt1 = DTYPES[ i ]; + for ( j = 0; j < DTYPES.length; j++ ) { + dt2 = DTYPES[ j ]; + dt = promotionRules( dt1, dt2 ); + t.strictEqual( dt, table[ dt1 ][ dt2 ], 'returns expected value when provided ('+dt1+','+dt2+')' ); + } + } + t.end(); +}); + +tape( 'if provided an unrecognized or unsupported data type, the function returns `null`', function test( t ) { + var values; + var i; + var j; + + values = [ + 'beep', + 'boop', + 'foo', + 'bar', + true, + false + ]; + for ( i = 0; i < values.length; i++ ) { + t.strictEqual( promotionRules( values[ i ], 'generic' ), null, 'returns expected value when provided '+values[ i ] ); + t.strictEqual( promotionRules( 'generic', values[ i ] ), null, 'returns expected value when provided '+values[ i ] ); + + j = (i+1) % values.length; + t.strictEqual( promotionRules( values[ i ], values[ j ] ), null, 'returns expected value when provided ('+values[ i ]+','+values[ j ]+')' ); + } + t.end(); +}); diff --git a/reviver/README.md b/reviver/README.md new file mode 100644 index 00000000..2d65a7a4 --- /dev/null +++ b/reviver/README.md @@ -0,0 +1,117 @@ + + +# Reviver + +> Revive a JSON-serialized typed array. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var reviver = require( '@stdlib/array/reviver' ); +``` + +#### reviver( key, value ) + +Revives a JSON-serialized typed array. + +```javascript +var parseJSON = require( '@stdlib/utils/parse-json' ); + +var str = '{"type":"Float64Array","data":[5,3]}'; + +var arr = parseJSON( str, reviver ); +// returns [ 5.0, 3.0 ] +``` + +For details on the JSON serialization format, see [`toJSON()`][@stdlib/array/to-json]. + +
+ + + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var Float64Array = require( '@stdlib/array/float64' ); +var parseJSON = require( '@stdlib/utils/parse-json' ); +var toJSON = require( '@stdlib/array/to-json' ); +var reviver = require( '@stdlib/array/reviver' ); + +var arr = new Float64Array( [ 5.0, 3.0 ] ); +var str = JSON.stringify( toJSON( arr ) ); +console.log( str ); +// => '{"type":"Float64Array","data":[5,3]}' + +var out = parseJSON( str, reviver ); +if ( out instanceof Error ) { + throw out; +} +console.log( out ); +// => [ 5.0, 3.0 ] +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/reviver/benchmark/benchmark.js b/reviver/benchmark/benchmark.js new file mode 100644 index 00000000..5707a082 --- /dev/null +++ b/reviver/benchmark/benchmark.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var randu = require( '@stdlib/random/base/randu' ); +var parseJSON = require( '@stdlib/utils/parse-json' ); +var pkg = require( './../package.json' ).name; +var reviver = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var str; + var o; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + str = '{"type":"Float64Array","data":['+randu()+','+randu()+']}'; + o = parseJSON( str, reviver ); + if ( typeof o !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof o !== 'object' ) { + b.fail( 'should return an object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::no_reviver', function benchmark( b ) { + var str; + var o; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + str = '{"type":"Float64Array","data":['+randu()+','+randu()+']}'; + o = parseJSON( str ); + if ( typeof o !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof o !== 'object' ) { + b.fail( 'should return an object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::no_reviver,built-in', function benchmark( b ) { + var str; + var o; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + str = '{"type":"Float64Array","data":['+randu()+','+randu()+']}'; + o = JSON.parse( str ); + if ( typeof o !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof o !== 'object' ) { + b.fail( 'should return an object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/reviver/docs/repl.txt b/reviver/docs/repl.txt new file mode 100644 index 00000000..96aaabf7 --- /dev/null +++ b/reviver/docs/repl.txt @@ -0,0 +1,32 @@ + +{{alias}}( key, value ) + Revives a JSON-serialized typed array. + + The serialization format for typed array is an object having the following + fields: + + - type: typed array type (e.g., "Float64Array", "Int8Array") + - data: typed array data as an array of numbers + + Parameters + ---------- + key: string + Key. + + value: any + Value. + + Returns + ------- + out: any + Value or typed array. + + Examples + -------- + > var str = '{"type":"Float64Array","data":[5,3]}'; + > var arr = {{alias:@stdlib/utils/parse-json}}( str, {{alias}} ) + [ 5.0, 3.0 ] + + See Also + -------- + diff --git a/reviver/docs/types/index.d.ts b/reviver/docs/types/index.d.ts new file mode 100644 index 00000000..3d716511 --- /dev/null +++ b/reviver/docs/types/index.d.ts @@ -0,0 +1,41 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/** +* Revives a JSON-serialized typed array. +* +* @param key - key +* @param value - value +* @returns value or typed array +* +* @example +* var parseJSON = require( `@stdlib/utils/parse-json` ); +* +* var str = '{"type":"Float64Array","data":[5,3]}'; +* +* var arr = parseJSON( str, reviver ); +* // returns [ 5.0, 3.0 ] +*/ +declare function reviver( key: string, value: any ): any; + + +// EXPORTS // + +export = reviver; diff --git a/reviver/docs/types/test.ts b/reviver/docs/types/test.ts new file mode 100644 index 00000000..8f3fa8fd --- /dev/null +++ b/reviver/docs/types/test.ts @@ -0,0 +1,45 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import reviver = require( './index' ); + + +// TESTS // + +// The function can be used to revive a serialized object... +{ + JSON.parse( '{"type":"Float64Array","data":[5,3]}', reviver ); // $ExpectType any +} + +// The function does not compile if provided a first argument that is not a string... +{ + reviver( true, 1 ); // $ExpectError + reviver( false, 1 ); // $ExpectError + reviver( null, 1 ); // $ExpectError + reviver( undefined, 1 ); // $ExpectError + reviver( 5, 1 ); // $ExpectError + reviver( [], 1 ); // $ExpectError + reviver( {}, 1 ); // $ExpectError + reviver( ( x: number ): number => x, 1 ); // $ExpectError +} + +// The function does not compile if provided insufficient arguments... +{ + reviver(); // $ExpectError + reviver( 'beep' ); // $ExpectError +} diff --git a/reviver/examples/index.js b/reviver/examples/index.js new file mode 100644 index 00000000..3673c112 --- /dev/null +++ b/reviver/examples/index.js @@ -0,0 +1,36 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var Float64Array = require( '@stdlib/array/float64' ); +var parseJSON = require( '@stdlib/utils/parse-json' ); +var toJSON = require( '@stdlib/array/to-json' ); +var reviver = require( './../lib' ); + +var arr = new Float64Array( [ 5.0, 3.0 ] ); +var str = JSON.stringify( toJSON( arr ) ); +console.log( str ); +// => '{"type":"Float64Array","data":[5,3]}' + +var out = parseJSON( str, reviver ); +if ( out instanceof Error ) { + throw out; +} +console.log( out ); +// => [ 5.0, 3.0 ] diff --git a/reviver/lib/ctors.js b/reviver/lib/ctors.js new file mode 100644 index 00000000..09b9a731 --- /dev/null +++ b/reviver/lib/ctors.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var Float64Array = require( '@stdlib/array/float64' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Int8Array = require( '@stdlib/array/int8' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); + + +// MAIN // + +var ctors = { + 'Float64Array': Float64Array, + 'Float32Array': Float32Array, + 'Int32Array': Int32Array, + 'Uint32Array': Uint32Array, + 'Int16Array': Int16Array, + 'Uint16Array': Uint16Array, + 'Int8Array': Int8Array, + 'Uint8Array': Uint8Array, + 'Uint8ClampedArray': Uint8ClampedArray +}; + + +// EXPORTS // + +module.exports = ctors; diff --git a/reviver/lib/index.js b/reviver/lib/index.js new file mode 100644 index 00000000..673febde --- /dev/null +++ b/reviver/lib/index.js @@ -0,0 +1,43 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Revive a JSON-serialized typed array. +* +* @module @stdlib/array/reviver +* +* @example +* var parseJSON = require( '@stdlib/utils/parse-json' ); +* var reviver = require( '@stdlib/array/reviver' ); +* +* var str = '{"type":"Float64Array","data":[5,3]}'; +* +* var arr = parseJSON( str, reviver ); +* // returns [ 5.0, 3.0 ] +*/ + +// MODULES // + +var reviver = require( './reviver.js' ); + + +// EXPORTS // + +module.exports = reviver; diff --git a/reviver/lib/reviver.js b/reviver/lib/reviver.js new file mode 100644 index 00000000..8f16ded8 --- /dev/null +++ b/reviver/lib/reviver.js @@ -0,0 +1,62 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isArray = require( '@stdlib/assert/is-array' ); +var ctors = require( './ctors.js' ); + + +// MAIN // + +/** +* Revives a JSON-serialized typed array. +* +* @param {string} key - key +* @param {*} value - value +* @returns {(*|TypedArray)} value or typed array +* +* @example +* var parseJSON = require( '@stdlib/utils/parse-json' ); +* +* var str = '{"type":"Float64Array","data":[5,3]}'; +* +* var arr = parseJSON( str, reviver ); +* // returns [ 5.0, 3.0 ] +*/ +function reviver( key, value ) { + var ctor; + if ( + value && + value.type && + isArray( value.data ) + ) { + ctor = ctors[ value.type ]; + if ( ctor ) { + return new ctor( value.data ); + } + } + return value; +} + + +// EXPORTS // + +module.exports = reviver; diff --git a/reviver/package.json b/reviver/package.json new file mode 100644 index 00000000..50a78bcf --- /dev/null +++ b/reviver/package.json @@ -0,0 +1,73 @@ +{ + "name": "@stdlib/array/reviver", + "version": "0.0.0", + "description": "Revive a JSON-serialized typed array.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "utils", + "util", + "utilities", + "utility", + "typed", + "array", + "typed-array", + "typed array", + "json", + "reviver", + "revive", + "unmarshal", + "deserialize", + "from", + "convert", + "parse", + "object", + "obj" + ] +} diff --git a/reviver/test/test.js b/reviver/test/test.js new file mode 100644 index 00000000..37e5a334 --- /dev/null +++ b/reviver/test/test.js @@ -0,0 +1,319 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var copy = require( '@stdlib/utils/copy' ); +var parseJSON = require( '@stdlib/utils/parse-json' ); +var toJSON = require( '@stdlib/array/to-json' ); +var Float64Array = require( '@stdlib/array/float64' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Int8Array = require( '@stdlib/array/int8' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); +var reviver = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof reviver, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'values which are not recognized as serialized typed arrays are unaffected', function test( t ) { + var expected; + var actual; + + expected = { + 'beep': 'boop' + }; + actual = parseJSON( '{"beep":"boop"}', reviver ); + + t.deepEqual( actual, expected, 'deep equal' ); + + // Null edge case: + actual = parseJSON( 'null', reviver ); + t.strictEqual( actual, null, 'equals null' ); + + t.end(); +}); + +tape( 'an object must have a recognized "type" field in order to be revived', function test( t ) { + var expected; + var actual; + var json; + + json = { + 'type': 'Boop', + 'data': [ 5.0, 3.0 ] + }; + + expected = copy( json ); + actual = parseJSON( JSON.stringify( json ), reviver ); + + t.deepEqual( actual, expected, 'deep equal' ); + t.end(); +}); + +tape( 'an object must have a "data" field having an array value in order to be revived', function test( t ) { + var expected; + var actual; + var json; + + json = { + 'type': 'Float64Array' + }; + + expected = copy( json ); + actual = parseJSON( JSON.stringify( json ), reviver ); + + t.deepEqual( actual, expected, 'deep equal' ); + + json = { + 'type': 'Float64Array', + 'data': null + }; + + expected = copy( json ); + actual = parseJSON( JSON.stringify( json ), reviver ); + + t.deepEqual( actual, expected, 'deep equal' ); + + json = { + 'type': 'Float64Array', + 'data': '[1,2,3]' + }; + + expected = copy( json ); + actual = parseJSON( JSON.stringify( json ), reviver ); + + t.deepEqual( actual, expected, 'deep equal' ); + + t.end(); +}); + +tape( 'the function will revive a JSON-serialized typed array (Float64Array)', function test( t ) { + var json; + var arr; + var out; + + arr = new Float64Array( [ 5.0, 3.0 ] ); + json = JSON.stringify( toJSON( arr ) ); + + out = parseJSON( json, reviver ); + + t.strictEqual( out instanceof Float64Array, true, 'is an instance' ); + t.strictEqual( out[ 0 ], arr[ 0 ], true, 'has expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], true, 'has expected value' ); + + t.end(); +}); + +tape( 'the function will revive a JSON-serialized typed array (Float32Array)', function test( t ) { + var json; + var arr; + var out; + + arr = new Float32Array( [ 3.14, -3.14 ] ); + json = JSON.stringify( toJSON( arr ) ); + + out = parseJSON( json, reviver ); + + t.strictEqual( out instanceof Float32Array, true, 'is an instance' ); + t.strictEqual( out[ 0 ], arr[ 0 ], true, 'has expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], true, 'has expected value' ); + + t.end(); +}); + +tape( 'the function will revive a JSON-serialized typed array (Int32Array)', function test( t ) { + var json; + var arr; + var out; + + arr = new Int32Array( [ 5, -3 ] ); + json = JSON.stringify( toJSON( arr ) ); + + out = parseJSON( json, reviver ); + + t.strictEqual( out instanceof Int32Array, true, 'is an instance' ); + t.strictEqual( out[ 0 ], arr[ 0 ], true, 'has expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], true, 'has expected value' ); + + t.end(); +}); + +tape( 'the function will revive a JSON-serialized typed array (Uint32Array)', function test( t ) { + var json; + var arr; + var out; + + arr = new Uint32Array( [ 5, 3 ] ); + json = JSON.stringify( toJSON( arr ) ); + + out = parseJSON( json, reviver ); + + t.strictEqual( out instanceof Uint32Array, true, 'is an instance' ); + t.strictEqual( out[ 0 ], arr[ 0 ], true, 'has expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], true, 'has expected value' ); + + t.end(); +}); + +tape( 'the function will revive a JSON-serialized typed array (Int16Array)', function test( t ) { + var json; + var arr; + var out; + + arr = new Int16Array( [ 5, -3 ] ); + json = JSON.stringify( toJSON( arr ) ); + + out = parseJSON( json, reviver ); + + t.strictEqual( out instanceof Int16Array, true, 'is an instance' ); + t.strictEqual( out[ 0 ], arr[ 0 ], true, 'has expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], true, 'has expected value' ); + + t.end(); +}); + +tape( 'the function will revive a JSON-serialized typed array (Uint16Array)', function test( t ) { + var json; + var arr; + var out; + + arr = new Uint16Array( [ 5, 3 ] ); + json = JSON.stringify( toJSON( arr ) ); + + out = parseJSON( json, reviver ); + + t.strictEqual( out instanceof Uint16Array, true, 'is an instance' ); + t.strictEqual( out[ 0 ], arr[ 0 ], true, 'has expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], true, 'has expected value' ); + + t.end(); +}); + +tape( 'the function will revive a JSON-serialized typed array (Int8Array)', function test( t ) { + var json; + var arr; + var out; + + arr = new Int8Array( [ 5, -3 ] ); + json = JSON.stringify( toJSON( arr ) ); + + out = parseJSON( json, reviver ); + + t.strictEqual( out instanceof Int8Array, true, 'is an instance' ); + t.strictEqual( out[ 0 ], arr[ 0 ], true, 'has expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], true, 'has expected value' ); + + t.end(); +}); + +tape( 'the function will revive a JSON-serialized typed array (Uint8Array)', function test( t ) { + var json; + var arr; + var out; + + arr = new Uint8Array( [ 5, 3 ] ); + json = JSON.stringify( toJSON( arr ) ); + + out = parseJSON( json, reviver ); + + t.strictEqual( out instanceof Uint8Array, true, 'is an instance' ); + t.strictEqual( out[ 0 ], arr[ 0 ], true, 'has expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], true, 'has expected value' ); + + t.end(); +}); + +tape( 'the function will revive a JSON-serialized typed array (Uint8ClampedArray)', function test( t ) { + var json; + var arr; + var out; + + arr = new Uint8ClampedArray( [ 5, 3 ] ); + json = JSON.stringify( toJSON( arr ) ); + + out = parseJSON( json, reviver ); + + t.strictEqual( out instanceof Uint8ClampedArray, true, 'is an instance' ); + t.strictEqual( out[ 0 ], arr[ 0 ], true, 'has expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], true, 'has expected value' ); + + t.end(); +}); + +tape( 'the function will revive deeply nested serialized typed arrays (array)', function test( t ) { + var actual; + var ctors; + var arr; + var i; + + ctors = [ + Float64Array, + Int32Array + ]; + + arr = [ + toJSON( new Float64Array( [ 5.0, 3.0 ] ) ), + toJSON( new Int32Array( [ -2, -4 ] ) ) + ]; + + actual = parseJSON( JSON.stringify( arr ), reviver ); + + for ( i = 0; i < arr.length; i++ ) { + t.strictEqual( actual[i] instanceof ctors[i], true, 'is an instance' ); + t.strictEqual( actual[i][0], arr[i].data[0], 'has expected value' ); + t.strictEqual( actual[i][1], arr[i].data[1], 'has expected value' ); + } + t.end(); +}); + +tape( 'the function will revive deeply nested serialized typed arrays (object)', function test( t ) { + var actual; + var json; + + json = { + 'a': { + 'b': toJSON( new Float32Array( [ 3.14, -3.14 ] ) ), + 'c': toJSON( new Uint8Array( [ 3, 5 ] ) ) + } + }; + actual = parseJSON( JSON.stringify( json ), reviver ); + + t.strictEqual( actual.a.b instanceof Float32Array, true, 'is an instance' ); + t.strictEqual( actual.a.b[0], json.a.b.data[0], 'has expected value' ); + t.strictEqual( actual.a.b[1], json.a.b.data[1], 'has expected value' ); + + t.strictEqual( actual.a.c instanceof Uint8Array, true, 'is an instance' ); + t.strictEqual( actual.a.c[0], json.a.c.data[0], 'has expected value' ); + t.strictEqual( actual.a.c[1], json.a.c.data[1], 'has expected value' ); + + t.end(); +}); diff --git a/safe-casts/README.md b/safe-casts/README.md new file mode 100644 index 00000000..56dcf0e6 --- /dev/null +++ b/safe-casts/README.md @@ -0,0 +1,130 @@ + + +# Safe Casts + +> Return a list of array [data types][@stdlib/array/dtypes] to which a provided array [data type][@stdlib/array/dtypes] can be safely cast. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var safeCasts = require( '@stdlib/array/safe-casts' ); +``` + +#### safeCasts( \[dtype] ) + +If provided a `dtype` argument, returns a list of array [data types][@stdlib/array/dtypes] to which a provided array [data type][@stdlib/array/dtypes] can be safely cast. + +```javascript +var out = safeCasts( 'float32' ); +// e.g., returns [ 'float32', 'float64', 'generic' ] +``` + +If not provided a `dtype` argument, the function returns a casting table. + +```javascript +var out = safeCasts(); +// returns {...} + +var f32 = out[ 'float32' ]; +// returns {...} + +var v = f32[ 'float64' ]; +// returns 1 +``` + +If provided an unrecognized or unsupported `dtype`, the function returns `null`. + +```javascript +var out = safeCasts( 'foo' ); +// returns null +``` + +
+ + + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var dtypes = require( '@stdlib/array/dtypes' ); +var safeCasts = require( '@stdlib/array/safe-casts' ); + +var DTYPES; +var list; +var i; + +// Get the list of supported array data types: +DTYPES = dtypes(); + +// Print the list of array data types to which a data type can be safely cast... +for ( i = 0; i < DTYPES.length; i++ ) { + list = safeCasts( DTYPES[ i ] ); + console.log( '%s: %s', DTYPES[ i ], list.join( ', ' ) ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/safe-casts/benchmark/benchmark.js b/safe-casts/benchmark/benchmark.js new file mode 100644 index 00000000..0c33e9b0 --- /dev/null +++ b/safe-casts/benchmark/benchmark.js @@ -0,0 +1,71 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives; +var dtypes = require( '@stdlib/array/dtypes' ); +var pkg = require( './../package.json' ).name; +var safeCasts = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = safeCasts(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::dtype', function benchmark( b ) { + var out; + var dt; + var i; + + dt = dtypes(); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = safeCasts( dt[ i%dt.length ] ); + if ( out.length === 0 ) { + b.fail( 'should not be empty' ); + } + } + b.toc(); + if ( !isStringArray( out ) ) { + b.fail( 'should return an array of strings' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/safe-casts/docs/repl.txt b/safe-casts/docs/repl.txt new file mode 100644 index 00000000..79b8b8f8 --- /dev/null +++ b/safe-casts/docs/repl.txt @@ -0,0 +1,27 @@ + +{{alias}}( [dtype] ) + Returns a list of array data types to which a provided array data type can + be safely cast. + + If not provided an array data type, the function returns a casting table. + + If provided an unrecognized array data type, the function returns `null`. + + Parameters + ---------- + dtype: string (optional) + Array data type. + + Returns + ------- + out: Object|Array|null + Array data types to which a data type can be safely cast. + + Examples + -------- + > var out = {{alias}}( 'float32' ) + + + See Also + -------- + diff --git a/safe-casts/docs/types/index.d.ts b/safe-casts/docs/types/index.d.ts new file mode 100644 index 00000000..dcc99160 --- /dev/null +++ b/safe-casts/docs/types/index.d.ts @@ -0,0 +1,41 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/** +* Returns a list of array data types to which a provided array data type can be safely cast. +* +* ## Notes +* +* - If not provided an array data type, the function returns a casting table. +* - If provided an unrecognized array data type, the function returns `null`. +* +* @param dtype - array data type +* @returns list of array data types or null +* +* @example +* var list = safeCasts( 'float32' ); +* // returns [...] +*/ +declare function safeCasts( dtype?: string ): Object | Array | null; + + +// EXPORTS // + +export = safeCasts; diff --git a/safe-casts/docs/types/test.ts b/safe-casts/docs/types/test.ts new file mode 100644 index 00000000..49990983 --- /dev/null +++ b/safe-casts/docs/types/test.ts @@ -0,0 +1,42 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import safeCasts = require( './index' ); + +// TESTS // + +// The function returns a string array, object, or null.. +{ + safeCasts(); // $ExpectType Object | string[] | null + safeCasts( 'float32' ); // $ExpectType Object | string[] | null +} + +// The compiler throws an error if the function is provided a first argument which is not a string... +{ + safeCasts( 123 ); // $ExpectError + safeCasts( true ); // $ExpectError + safeCasts( false ); // $ExpectError + safeCasts( {} ); // $ExpectError + safeCasts( [] ); // $ExpectError + safeCasts( null ); // $ExpectError +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + safeCasts( 'float32', 3 ); // $ExpectError +} diff --git a/safe-casts/examples/index.js b/safe-casts/examples/index.js new file mode 100644 index 00000000..0291d854 --- /dev/null +++ b/safe-casts/examples/index.js @@ -0,0 +1,35 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var dtypes = require( '@stdlib/array/dtypes' ); +var safeCasts = require( './../lib' ); + +var DTYPES; +var list; +var i; + +// Get the list of supported array data types: +DTYPES = dtypes(); + +// Print the list of array data types to which a data type can be safely cast... +for ( i = 0; i < DTYPES.length; i++ ) { + list = safeCasts( DTYPES[ i ] ); + console.log( '%s: %s', DTYPES[ i ], list.join( ', ' ) ); +} diff --git a/safe-casts/lib/index.js b/safe-casts/lib/index.js new file mode 100644 index 00000000..d1e54c3a --- /dev/null +++ b/safe-casts/lib/index.js @@ -0,0 +1,40 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Return a list of array data types to which a provided array data type can be safely cast. +* +* @module @stdlib/array/safe-casts +* +* @example +* var safeCasts = require( '@stdlib/array/safe-casts' ); +* +* var list = safeCasts( 'float32' ); +* // returns [...] +*/ + +// MODULES // + +var safeCasts = require( './main.js' ); + + +// EXPORTS // + +module.exports = safeCasts; diff --git a/safe-casts/lib/main.js b/safe-casts/lib/main.js new file mode 100644 index 00000000..676d113a --- /dev/null +++ b/safe-casts/lib/main.js @@ -0,0 +1,133 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var objectKeys = require( '@stdlib/utils/keys' ); +var hasOwnProp = require( '@stdlib/assert/has-own-property' ); +var SAFE_CASTS = require( './safe_casts.json' ); + + +// VARIABLES // + +var TABLE; + + +// FUNCTIONS // + +/** +* Generates a full table of safe casts for each array data type. +* +* @private +* @returns {Object} table +*/ +function generateFullTable() { + var dtypes; + var ntypes; + var out; + var tmp; + var dt1; + var dt2; + var o; + var j; + var i; + + out = {}; + dtypes = objectKeys( SAFE_CASTS ); + ntypes = dtypes.length; + for ( i = 0; i < ntypes; i++ ) { + dt1 = dtypes[ i ]; + o = SAFE_CASTS[ dt1 ]; + tmp = {}; + for ( j = 0; j < ntypes; j++ ) { + dt2 = dtypes[ j ]; + tmp[ dt2 ] = o[ dt2 ]; + } + out[ dt1 ] = tmp; + } + return out; +} + +/** +* Generates a table of safe casts for each array data type. +* +* @private +* @returns {Object} table +*/ +function generateTable() { + var dtypes; + var ntypes; + var out; + var tmp; + var dt1; + var dt2; + var o; + var j; + var i; + + out = {}; + dtypes = objectKeys( SAFE_CASTS ); + ntypes = dtypes.length; + for ( i = 0; i < ntypes; i++ ) { + dt1 = dtypes[ i ]; + o = SAFE_CASTS[ dt1 ]; + tmp = []; + for ( j = 0; j < ntypes; j++ ) { + dt2 = dtypes[ j ]; + if ( o[ dt2 ] === 1 ) { + tmp.push( dt2 ); + } + } + out[ dt1 ] = tmp; + } + return out; +} + + +// MAIN // + +/** +* Returns a list of array data types to which a provided array data type can be safely cast. +* +* @param {string} [dtype] - array data type +* @returns {(Object|StringArray|null)} list of array data types or null +* +* @example +* var list = safeCasts( 'float32' ); +* // returns [...] +*/ +function safeCasts( dtype ) { + if ( arguments.length === 0 ) { + return generateFullTable(); + } + if ( TABLE === void 0 ) { + // Lazily generate table... + TABLE = generateTable(); + } + if ( hasOwnProp( TABLE, dtype ) ) { + return TABLE[ dtype ].slice(); + } + return null; +} + + +// EXPORTS // + +module.exports = safeCasts; diff --git a/safe-casts/lib/safe_casts.json b/safe-casts/lib/safe_casts.json new file mode 100644 index 00000000..e3535135 --- /dev/null +++ b/safe-casts/lib/safe_casts.json @@ -0,0 +1,122 @@ +{ + "float64": { + "float64": 1, + "float32": 0, + "int32": 0, + "int16": 0, + "int8": 0, + "uint32": 0, + "uint16": 0, + "uint8": 0, + "uint8c": 0, + "generic": 1 + }, + "float32": { + "float64": 1, + "float32": 1, + "int32": 0, + "int16": 0, + "int8": 0, + "uint32": 0, + "uint16": 0, + "uint8": 0, + "uint8c": 0, + "generic": 1 + }, + "int32": { + "float64": 1, + "float32": 0, + "int32": 1, + "int16": 0, + "int8": 0, + "uint32": 0, + "uint16": 0, + "uint8": 0, + "uint8c": 0, + "generic": 1 + }, + "int16": { + "float64": 1, + "float32": 1, + "int32": 1, + "int16": 1, + "int8": 0, + "uint32": 0, + "uint16": 0, + "uint8": 0, + "uint8c": 0, + "generic": 1 + }, + "int8": { + "float64": 1, + "float32": 1, + "int32": 1, + "int16": 1, + "int8": 1, + "uint32": 0, + "uint16": 0, + "uint8": 0, + "uint8c": 0, + "generic": 1 + }, + "uint32": { + "float64": 1, + "float32": 0, + "int32": 0, + "int16": 0, + "int8": 0, + "uint32": 1, + "uint16": 0, + "uint8": 0, + "uint8c": 0, + "generic": 1 + }, + "uint16": { + "float64": 1, + "float32": 1, + "int32": 1, + "int16": 0, + "int8": 0, + "uint32": 1, + "uint16": 1, + "uint8": 0, + "uint8c": 0, + "generic": 1 + }, + "uint8": { + "float64": 1, + "float32": 1, + "int32": 1, + "int16": 1, + "int8": 0, + "uint32": 1, + "uint16": 1, + "uint8": 1, + "uint8c": 1, + "generic": 1 + }, + "uint8c": { + "float64": 1, + "float32": 1, + "int32": 1, + "int16": 1, + "int8": 0, + "uint32": 1, + "uint16": 1, + "uint8": 1, + "uint8c": 1, + "generic": 1 + }, + "generic": { + "float64": 0, + "float32": 0, + "int32": 0, + "int16": 0, + "int8": 0, + "uint32": 0, + "uint16": 0, + "uint8": 0, + "uint8c": 0, + "generic": 1 + } +} diff --git a/safe-casts/package.json b/safe-casts/package.json new file mode 100644 index 00000000..1864b565 --- /dev/null +++ b/safe-casts/package.json @@ -0,0 +1,66 @@ +{ + "name": "@stdlib/array/safe-casts", + "version": "0.0.0", + "description": "Return a list of array data types to which a provided array data type can be safely cast.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "array", + "casting", + "cast", + "rules", + "promotion", + "utilities", + "utility", + "utils", + "util" + ], + "__stdlib__": {} +} diff --git a/safe-casts/test/test.js b/safe-casts/test/test.js new file mode 100644 index 00000000..fb234a86 --- /dev/null +++ b/safe-casts/test/test.js @@ -0,0 +1,75 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var dtypes = require( '@stdlib/array/dtypes' ); +var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives; +var safeCasts = require( './../lib' ); + + +// VARIABLES // + +var DTYPES = dtypes(); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof safeCasts, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'if not provided a data type, the function returns a table', function test( t ) { + var out = safeCasts(); + t.strictEqual( typeof out, 'object', 'returns an object' ); + t.strictEqual( out[ 'float32' ][ 'float64' ], 1, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a list of array data types to which a provided array data type can be safely cast', function test( t ) { + var list; + var i; + for ( i = 0; i < DTYPES.length; i++ ) { + list = safeCasts( DTYPES[ i ] ); + t.strictEqual( isStringArray( list ), true, 'returns an array of strings when provided '+DTYPES[ i ] ); + } + t.end(); +}); + +tape( 'if provided an unrecognized or unsupported data type, the function returns `null`', function test( t ) { + var values; + var i; + + values = [ + 'beep', + 'boop', + 'foo', + 'bar', + true, + false + ]; + for ( i = 0; i < values.length; i++ ) { + t.strictEqual( safeCasts( values[ i ] ), null, 'returns expected value when provided '+values[ i ] ); + } + t.end(); +}); diff --git a/same-kind-casts/README.md b/same-kind-casts/README.md new file mode 100644 index 00000000..b0a914e2 --- /dev/null +++ b/same-kind-casts/README.md @@ -0,0 +1,130 @@ + + +# Same Kind Casts + +> Return a list of array [data types][@stdlib/array/dtypes] to which a provided array [data type][@stdlib/array/dtypes] can be safely cast or cast within the same "kind". + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var sameKindCasts = require( '@stdlib/array/same-kind-casts' ); +``` + +#### sameKindCasts( \[dtype] ) + +If provided a `dtype` argument, returns a list of array [data types][@stdlib/array/dtypes] to which a provided array [data type][@stdlib/array/dtypes] can be safely cast or cast within the same "kind" (e.g., between signed integers or between floating-point numbers). + +```javascript +var out = sameKindCasts( 'float64' ); +// e.g., returns [ 'float64', 'float32', 'generic' ] +``` + +If not provided a `dtype` argument, the function returns a casting table. + +```javascript +var out = sameKindCasts(); +// returns {...} + +var f64 = out[ 'float64' ]; +// returns {...} + +var v = f64[ 'float32' ]; +// returns 1 +``` + +If provided an unrecognized or unsupported `dtype`, the function returns `null`. + +```javascript +var out = sameKindCasts( 'foo' ); +// returns null +``` + +
+ + + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var dtypes = require( '@stdlib/array/dtypes' ); +var sameKindCasts = require( '@stdlib/array/same-kind-casts' ); + +var DTYPES; +var list; +var i; + +// Get the list of supported array data types: +DTYPES = dtypes(); + +// Print the list of array data types to which a data type can be cast... +for ( i = 0; i < DTYPES.length; i++ ) { + list = sameKindCasts( DTYPES[ i ] ); + console.log( '%s: %s', DTYPES[ i ], list.join( ', ' ) ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/same-kind-casts/benchmark/benchmark.js b/same-kind-casts/benchmark/benchmark.js new file mode 100644 index 00000000..bc59fc33 --- /dev/null +++ b/same-kind-casts/benchmark/benchmark.js @@ -0,0 +1,71 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives; +var dtypes = require( '@stdlib/array/dtypes' ); +var pkg = require( './../package.json' ).name; +var sameKindCasts = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = sameKindCasts(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::dtype', function benchmark( b ) { + var out; + var dt; + var i; + + dt = dtypes(); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = sameKindCasts( dt[ i%dt.length ] ); + if ( out.length === 0 ) { + b.fail( 'should not be empty' ); + } + } + b.toc(); + if ( !isStringArray( out ) ) { + b.fail( 'should return an array of strings' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/same-kind-casts/docs/repl.txt b/same-kind-casts/docs/repl.txt new file mode 100644 index 00000000..b27e9b0a --- /dev/null +++ b/same-kind-casts/docs/repl.txt @@ -0,0 +1,28 @@ + +{{alias}}( [dtype] ) + Returns a list of array data types to which a provided array data type can + be safely cast or cast within the same "kind". + + If not provided an array data type, the function returns a casting table. + + If provided an unrecognized array data type, the function returns `null`. + + Parameters + ---------- + dtype: string (optional) + Array data type. + + Returns + ------- + out: Object|Array|null + Array data types to which a data type can be safely cast or cast within + the same "kind". + + Examples + -------- + > var out = {{alias}}( 'float32' ) + + + See Also + -------- + diff --git a/same-kind-casts/docs/types/index.d.ts b/same-kind-casts/docs/types/index.d.ts new file mode 100644 index 00000000..6b123bc9 --- /dev/null +++ b/same-kind-casts/docs/types/index.d.ts @@ -0,0 +1,41 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/** +* Returns a list of array data types to which a provided array data type can be safely cast or cast within the same "kind". +* +* ## Notes +* +* - If not provided an array data type, the function returns a casting table. +* - If provided an unrecognized array data type, the function returns `null`. +* +* @param dtype - array data type +* @returns list of array data types or null +* +* @example +* var list = sameKindCasts( 'float32' ); +* // returns [...] +*/ +declare function sameKindCasts( dtype?: string ): Object | Array | null; + + +// EXPORTS // + +export = sameKindCasts; diff --git a/same-kind-casts/docs/types/test.ts b/same-kind-casts/docs/types/test.ts new file mode 100644 index 00000000..91c8b9ed --- /dev/null +++ b/same-kind-casts/docs/types/test.ts @@ -0,0 +1,42 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import sameKindCasts = require( './index' ); + +// TESTS // + +// The function returns a string array, object, or null.. +{ + sameKindCasts(); // $ExpectType Object | string[] | null + sameKindCasts( 'float32' ); // $ExpectType Object | string[] | null +} + +// The compiler throws an error if the function is provided a first argument which is not a string... +{ + sameKindCasts( 123 ); // $ExpectError + sameKindCasts( true ); // $ExpectError + sameKindCasts( false ); // $ExpectError + sameKindCasts( {} ); // $ExpectError + sameKindCasts( [] ); // $ExpectError + sameKindCasts( null ); // $ExpectError +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + sameKindCasts( 'float32', 3 ); // $ExpectError +} diff --git a/same-kind-casts/examples/index.js b/same-kind-casts/examples/index.js new file mode 100644 index 00000000..8e96fa16 --- /dev/null +++ b/same-kind-casts/examples/index.js @@ -0,0 +1,35 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var dtypes = require( '@stdlib/array/dtypes' ); +var sameKindCasts = require( './../lib' ); + +var DTYPES; +var list; +var i; + +// Get the list of supported array data types: +DTYPES = dtypes(); + +// Print the list of array data types to which a data type can be cast... +for ( i = 0; i < DTYPES.length; i++ ) { + list = sameKindCasts( DTYPES[ i ] ); + console.log( '%s: %s', DTYPES[ i ], list.join( ', ' ) ); +} diff --git a/same-kind-casts/lib/index.js b/same-kind-casts/lib/index.js new file mode 100644 index 00000000..2089a580 --- /dev/null +++ b/same-kind-casts/lib/index.js @@ -0,0 +1,40 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Return a list of array data types to which a provided array data type can be safely cast or cast within the same "kind". +* +* @module @stdlib/array/same-kind-casts +* +* @example +* var sameKindCasts = require( '@stdlib/array/same-kind-casts' ); +* +* var list = sameKindCasts( 'float32' ); +* // returns [...] +*/ + +// MODULES // + +var sameKindCasts = require( './main.js' ); + + +// EXPORTS // + +module.exports = sameKindCasts; diff --git a/same-kind-casts/lib/main.js b/same-kind-casts/lib/main.js new file mode 100644 index 00000000..906e8420 --- /dev/null +++ b/same-kind-casts/lib/main.js @@ -0,0 +1,133 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var objectKeys = require( '@stdlib/utils/keys' ); +var hasOwnProp = require( '@stdlib/assert/has-own-property' ); +var SAME_KIND_CASTS = require( './same_kind_casts.json' ); + + +// VARIABLES // + +var TABLE; + + +// FUNCTIONS // + +/** +* Generates a full table of same "kind" casts for each array data type. +* +* @private +* @returns {Object} table +*/ +function generateFullTable() { + var dtypes; + var ntypes; + var out; + var tmp; + var dt1; + var dt2; + var o; + var j; + var i; + + out = {}; + dtypes = objectKeys( SAME_KIND_CASTS ); + ntypes = dtypes.length; + for ( i = 0; i < ntypes; i++ ) { + dt1 = dtypes[ i ]; + o = SAME_KIND_CASTS[ dt1 ]; + tmp = {}; + for ( j = 0; j < ntypes; j++ ) { + dt2 = dtypes[ j ]; + tmp[ dt2 ] = o[ dt2 ]; + } + out[ dt1 ] = tmp; + } + return out; +} + +/** +* Generates a table of same "kind" casts for each array data type. +* +* @private +* @returns {Object} table +*/ +function generateTable() { + var dtypes; + var ntypes; + var out; + var tmp; + var dt1; + var dt2; + var o; + var j; + var i; + + out = {}; + dtypes = objectKeys( SAME_KIND_CASTS ); + ntypes = dtypes.length; + for ( i = 0; i < ntypes; i++ ) { + dt1 = dtypes[ i ]; + o = SAME_KIND_CASTS[ dt1 ]; + tmp = []; + for ( j = 0; j < ntypes; j++ ) { + dt2 = dtypes[ j ]; + if ( o[ dt2 ] === 1 ) { + tmp.push( dt2 ); + } + } + out[ dt1 ] = tmp; + } + return out; +} + + +// MAIN // + +/** +* Returns a list of array data types to which a provided array data type can be safely cast or cast within the same "kind". +* +* @param {string} [dtype] - array data type +* @returns {(Object|StringArray|null)} list of array data types or null +* +* @example +* var list = sameKindCasts( 'float32' ); +* // returns [...] +*/ +function sameKindCasts( dtype ) { + if ( arguments.length === 0 ) { + return generateFullTable(); + } + if ( TABLE === void 0 ) { + // Lazily generate table... + TABLE = generateTable(); + } + if ( hasOwnProp( TABLE, dtype ) ) { + return TABLE[ dtype ].slice(); + } + return null; +} + + +// EXPORTS // + +module.exports = sameKindCasts; diff --git a/same-kind-casts/lib/same_kind_casts.json b/same-kind-casts/lib/same_kind_casts.json new file mode 100644 index 00000000..69f3a28e --- /dev/null +++ b/same-kind-casts/lib/same_kind_casts.json @@ -0,0 +1,122 @@ +{ + "float64": { + "float64": 1, + "float32": 1, + "int32": 0, + "int16": 0, + "int8": 0, + "uint32": 0, + "uint16": 0, + "uint8": 0, + "uint8c": 0, + "generic": 1 + }, + "float32": { + "float64": 1, + "float32": 1, + "int32": 0, + "int16": 0, + "int8": 0, + "uint32": 0, + "uint16": 0, + "uint8": 0, + "uint8c": 0, + "generic": 1 + }, + "int32": { + "float64": 1, + "float32": 0, + "int32": 1, + "int16": 1, + "int8": 1, + "uint32": 0, + "uint16": 0, + "uint8": 0, + "uint8c": 0, + "generic": 1 + }, + "int16": { + "float64": 1, + "float32": 1, + "int32": 1, + "int16": 1, + "int8": 1, + "uint32": 0, + "uint16": 0, + "uint8": 0, + "uint8c": 0, + "generic": 1 + }, + "int8": { + "float64": 1, + "float32": 1, + "int32": 1, + "int16": 1, + "int8": 1, + "uint32": 0, + "uint16": 0, + "uint8": 0, + "uint8c": 0, + "generic": 1 + }, + "uint32": { + "float64": 1, + "float32": 0, + "int32": 0, + "int16": 0, + "int8": 0, + "uint32": 1, + "uint16": 1, + "uint8": 1, + "uint8c": 1, + "generic": 1 + }, + "uint16": { + "float64": 1, + "float32": 1, + "int32": 1, + "int16": 0, + "int8": 0, + "uint32": 1, + "uint16": 1, + "uint8": 1, + "uint8c": 1, + "generic": 1 + }, + "uint8": { + "float64": 1, + "float32": 1, + "int32": 1, + "int16": 1, + "int8": 0, + "uint32": 1, + "uint16": 1, + "uint8": 1, + "uint8c": 1, + "generic": 1 + }, + "uint8c": { + "float64": 1, + "float32": 1, + "int32": 1, + "int16": 1, + "int8": 0, + "uint32": 1, + "uint16": 1, + "uint8": 1, + "uint8c": 1, + "generic": 1 + }, + "generic": { + "float64": 0, + "float32": 0, + "int32": 0, + "int16": 0, + "int8": 0, + "uint32": 0, + "uint16": 0, + "uint8": 0, + "uint8c": 0, + "generic": 1 + } +} diff --git a/same-kind-casts/package.json b/same-kind-casts/package.json new file mode 100644 index 00000000..571738c9 --- /dev/null +++ b/same-kind-casts/package.json @@ -0,0 +1,66 @@ +{ + "name": "@stdlib/array/same-kind-casts", + "version": "0.0.0", + "description": "Return a list of array data types to which a provided array data type can be safely cast or cast within the same kind.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "array", + "casting", + "cast", + "rules", + "promotion", + "utilities", + "utility", + "utils", + "util" + ], + "__stdlib__": {} +} diff --git a/same-kind-casts/test/test.js b/same-kind-casts/test/test.js new file mode 100644 index 00000000..4f69b474 --- /dev/null +++ b/same-kind-casts/test/test.js @@ -0,0 +1,76 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var dtypes = require( '@stdlib/array/dtypes' ); +var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives; +var sameKindCasts = require( './../lib' ); + + +// VARIABLES // + +var DTYPES = dtypes(); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof sameKindCasts, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'if not provided a data type, the function returns a table', function test( t ) { + var out = sameKindCasts(); + t.strictEqual( typeof out, 'object', 'returns an object' ); + t.strictEqual( out[ 'float32' ][ 'float64' ], 1, 'returns expected value' ); + t.strictEqual( out[ 'float32' ][ 'int8' ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a list of array data types to which a provided array data type can be safely cast or cast within the same "kind"', function test( t ) { + var list; + var i; + for ( i = 0; i < DTYPES.length; i++ ) { + list = sameKindCasts( DTYPES[ i ] ); + t.strictEqual( isStringArray( list ), true, 'returns an array of strings when provided '+DTYPES[ i ] ); + } + t.end(); +}); + +tape( 'if provided an unrecognized or unsupported data type, the function returns `null`', function test( t ) { + var values; + var i; + + values = [ + 'beep', + 'boop', + 'foo', + 'bar', + true, + false + ]; + for ( i = 0; i < values.length; i++ ) { + t.strictEqual( sameKindCasts( values[ i ] ), null, 'returns expected value when provided '+values[ i ] ); + } + t.end(); +}); diff --git a/shape/README.md b/shape/README.md new file mode 100644 index 00000000..eca83501 --- /dev/null +++ b/shape/README.md @@ -0,0 +1,209 @@ + + +# Array Shape + +> Determine (nested) array dimensions. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var arrayShape = require( '@stdlib/array/shape' ); +``` + +#### arrayShape( arr ) + +Returns array dimensions. + +```javascript +var arr = [ + [ 1, 2, 3 ], + [ 4, 5, 6 ], + [ 7, 8, 9 ] +]; + +var shape = arrayShape( arr ); +// returns [ 3, 3 ] +``` + +The function **ignores** inconsistent dimensions. + +```javascript +var arr = [ + [ 1, 2, 3 ], + [ 4, 5, 6 ], + [ 7, 8 ] +]; + +var shape = arrayShape( arr ); +// returns [ 3 ] +``` + +
+ + + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var arrayShape = require( '@stdlib/array/shape' ); + +var shape; +var arr; + +arr = [ 1, 2, 3 ]; +shape = arrayShape( arr ); +// returns [ 3 ] + +arr = [ + [ 1 ], + [ 2 ], + [ 3 ] +]; +shape = arrayShape( arr ); +// returns [ 3, 1 ] + +arr = [ + [], + [], + [] +]; +shape = arrayShape( arr ); +// returns [ 3, 0 ] + +arr = [ + [ 1, 2, 3 ] +]; +shape = arrayShape( arr ); +// returns [ 1, 3 ] + +arr = [ + [ [ 1 ] ], + [ [ 2 ] ], + [ [ 3 ] ] +]; +shape = arrayShape( arr ); +// returns [ 3, 1, 1 ] + +arr = [ [ [ [ 1, 2, 3 ] ] ] ]; +shape = arrayShape( arr ); +// returns [ 1, 1, 1, 3 ] + +arr = [ + [ 1, 2 ], + [ 3, 4 ] +]; +shape = arrayShape( arr ); +// returns [ 2, 2 ] + +arr = [ + [ 1, 2, 3 ], + [ 4, 5, 6 ], + [ 7, 8, 9 ] +]; +shape = arrayShape( arr ); +// returns [ 3, 3 ] + +arr = [ + [ 1, 2, 3 ], + null, + [ 7, 8, 9 ] +]; +shape = arrayShape( arr ); +// returns [ 3 ] + +arr = [ + [ 1, 2, 3 ], + [ [ 4, 5, 6 ] ], + [ [ 7, 8, 9 ] ] +]; +shape = arrayShape( arr ); +// returns [ 3 ] + +arr = [ + [ [ 1, 2, 3 ] ], + [ 4, 5, 6 ], + [ [ 7, 8, 9 ] ] +]; +shape = arrayShape( arr ); +// returns [ 3 ] + +arr = [ + [ [ 1, 2, 3 ] ], + [ [ 4, 5, 6 ] ], + [ 7, 8, 9 ] +]; +shape = arrayShape( arr ); +// returns [ 3 ] + +arr = [ + [ [ [ 1, 2, 3 ] ] ], + [ [ 4, 5, 6 ] ], + [ [ [ 7, 8, 9 ] ] ] +]; +shape = arrayShape( arr ); +// returns [ 3, 1 ] +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/shape/benchmark/benchmark.js b/shape/benchmark/benchmark.js new file mode 100644 index 00000000..8893b00a --- /dev/null +++ b/shape/benchmark/benchmark.js @@ -0,0 +1,220 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isArray = require( '@stdlib/assert/is-array' ); +var pkg = require( './../package.json' ).name; +var arrayShape = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::1d', function benchmark( b ) { + var arr; + var out; + var i; + + // 3 + arr = [ 1, 2, 3 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arrayShape( arr ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isArray( out ) || out.length !== 1 ) { + b.fail( 'should return an array of length 1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::2d', function benchmark( b ) { + var arr; + var out; + var i; + + // 3x3 + arr = [ + [ 1, 2, 3 ], + [ 4, 5, 6 ], + [ 7, 8, 9 ] + ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arrayShape( arr ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isArray( out ) || out.length !== 2 ) { + b.fail( 'should return an array of length 2' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::3d', function benchmark( b ) { + var arr; + var out; + var i; + + // 3x3x3 + arr = [ + [ [ 1, 1, 1 ], [ 2, 2, 2 ], [ 3, 3, 3 ] ], + [ [ 4, 4, 4 ], [ 5, 5, 5 ], [ 6, 6, 6 ] ], + [ [ 7, 7, 7 ], [ 8, 8, 8 ], [ 9, 9, 9 ] ] + ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arrayShape( arr ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isArray( out ) || out.length !== 3 ) { + b.fail( 'should return an array of length 3' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::4d', function benchmark( b ) { + var arr; + var out; + var i; + + // 3x3x3x3 + arr = [ + [ + [ [ 1, 1, 1 ], [ 1, 1, 1 ], [ 1, 1, 1 ] ], + [ [ 2, 2, 2 ], [ 2, 2, 2 ], [ 2, 2, 2 ] ], + [ [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ] ] + ], + [ + [ [ 4, 4, 4 ], [ 4, 4, 4 ], [ 4, 4, 4 ] ], + [ [ 5, 5, 5 ], [ 5, 5, 5 ], [ 5, 5, 5 ] ], + [ [ 6, 6, 6 ], [ 6, 6, 6 ], [ 6, 6, 6 ] ] + ], + [ + [ [ 7, 7, 7 ], [ 7, 7, 7 ], [ 7, 7, 7 ] ], + [ [ 8, 8, 8 ], [ 8, 8, 8 ], [ 8, 8, 8 ] ], + [ [ 9, 9, 9 ], [ 9, 9, 9 ], [ 9, 9, 9 ] ] + ] + ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arrayShape( arr ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isArray( out ) || out.length !== 4 ) { + b.fail( 'should return an array of length 4' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::5d', function benchmark( b ) { + var arr; + var out; + var i; + + // 3x3x3x3x3 + arr = [ + [ + [ + [ [ 1, 1, 1 ], [ 1, 1, 1 ], [ 1, 1, 1 ] ], + [ [ 2, 2, 2 ], [ 2, 2, 2 ], [ 2, 2, 2 ] ], + [ [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ] ] + ], + [ + [ [ 1, 1, 1 ], [ 1, 1, 1 ], [ 1, 1, 1 ] ], + [ [ 2, 2, 2 ], [ 2, 2, 2 ], [ 2, 2, 2 ] ], + [ [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ] ] + ], + [ + [ [ 1, 1, 1 ], [ 1, 1, 1 ], [ 1, 1, 1 ] ], + [ [ 2, 2, 2 ], [ 2, 2, 2 ], [ 2, 2, 2 ] ], + [ [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ] ] + ] + ], + [ + [ + [ [ 4, 4, 4 ], [ 4, 4, 4 ], [ 4, 4, 4 ] ], + [ [ 5, 5, 5 ], [ 5, 5, 5 ], [ 5, 5, 5 ] ], + [ [ 6, 6, 6 ], [ 6, 6, 6 ], [ 6, 6, 6 ] ] + ], + [ + [ [ 4, 4, 4 ], [ 4, 4, 4 ], [ 4, 4, 4 ] ], + [ [ 5, 5, 5 ], [ 5, 5, 5 ], [ 5, 5, 5 ] ], + [ [ 6, 6, 6 ], [ 6, 6, 6 ], [ 6, 6, 6 ] ] + ], + [ + [ [ 4, 4, 4 ], [ 4, 4, 4 ], [ 4, 4, 4 ] ], + [ [ 5, 5, 5 ], [ 5, 5, 5 ], [ 5, 5, 5 ] ], + [ [ 6, 6, 6 ], [ 6, 6, 6 ], [ 6, 6, 6 ] ] + ] + ], + [ + [ + [ [ 7, 7, 7 ], [ 7, 7, 7 ], [ 7, 7, 7 ] ], + [ [ 8, 8, 8 ], [ 8, 8, 8 ], [ 8, 8, 8 ] ], + [ [ 9, 9, 9 ], [ 9, 9, 9 ], [ 9, 9, 9 ] ] + ], + [ + [ [ 7, 7, 7 ], [ 7, 7, 7 ], [ 7, 7, 7 ] ], + [ [ 8, 8, 8 ], [ 8, 8, 8 ], [ 8, 8, 8 ] ], + [ [ 9, 9, 9 ], [ 9, 9, 9 ], [ 9, 9, 9 ] ] + ], + [ + [ [ 7, 7, 7 ], [ 7, 7, 7 ], [ 7, 7, 7 ] ], + [ [ 8, 8, 8 ], [ 8, 8, 8 ], [ 8, 8, 8 ] ], + [ [ 9, 9, 9 ], [ 9, 9, 9 ], [ 9, 9, 9 ] ] + ] + ] + ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arrayShape( arr ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isArray( out ) || out.length !== 5 ) { + b.fail( 'should return an array of length 5' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/shape/docs/repl.txt b/shape/docs/repl.txt new file mode 100644 index 00000000..01b357ae --- /dev/null +++ b/shape/docs/repl.txt @@ -0,0 +1,22 @@ + +{{alias}}( arr ) + Determines array dimensions. + + Parameters + ---------- + arr: Array + Input array. + + Returns + ------- + out: Array + Array shape. + + Examples + -------- + > var out = {{alias}}( [ [ 1, 2, 3 ], [ 4, 5, 6 ] ] ) + [ 2, 3 ] + + See Also + -------- + diff --git a/shape/docs/types/index.d.ts b/shape/docs/types/index.d.ts new file mode 100644 index 00000000..3cdfce4f --- /dev/null +++ b/shape/docs/types/index.d.ts @@ -0,0 +1,50 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/** +* Determines (nested) array dimensions. +* +* @param arr - array +* @returns array shape +* +* @example +* var arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; +* +* var shape = arrayShape( arr ); +* // returns [ 3, 3 ] +* +* @example +* var arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ] ]; +* +* var shape = arrayShape( arr ); +* // returns [ 3 ] +* +* @example +* var arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], null ]; +* +* var shape = arrayShape( arr ); +* // returns [ 3 ] +*/ +declare function arrayShape( arr: Array ): Array; + + +// EXPORTS // + +export = arrayShape; diff --git a/shape/docs/types/test.ts b/shape/docs/types/test.ts new file mode 100644 index 00000000..e00a3f0e --- /dev/null +++ b/shape/docs/types/test.ts @@ -0,0 +1,32 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import arrayShape = require( './index' ); + +// TESTS // + +// The function returns an array of numbers.. +{ + arrayShape( [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] ); // $ExpectType number[] +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + arrayShape(); // $ExpectError + arrayShape( [ 1, 2, 3 ], 3 ); // $ExpectError +} diff --git a/shape/examples/index.js b/shape/examples/index.js new file mode 100644 index 00000000..94f17cec --- /dev/null +++ b/shape/examples/index.js @@ -0,0 +1,130 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var arrayShape = require( './../lib' ); + +var shape; +var arr; + +arr = [ 1, 2, 3 ]; +shape = arrayShape( arr ); +console.log( shape.join( 'x' ) ); +// => 3 + +arr = [ + [ 1 ], + [ 2 ], + [ 3 ] +]; +shape = arrayShape( arr ); +console.log( shape.join( 'x' ) ); +// => 3x1 + +arr = [ + [], + [], + [] +]; +shape = arrayShape( arr ); +console.log( shape.join( 'x' ) ); +// => 3x0 + +arr = [ + [ 1, 2, 3 ] +]; +shape = arrayShape( arr ); +console.log( shape.join( 'x' ) ); +// => 1x3 + +arr = [ + [ [ 1 ] ], + [ [ 2 ] ], + [ [ 3 ] ] +]; +shape = arrayShape( arr ); +console.log( shape.join( 'x' ) ); +// => 3x1x1 + +arr = [ [ [ [ 1, 2, 3 ] ] ] ]; +shape = arrayShape( arr ); +console.log( shape.join( 'x' ) ); +// => 1x1x1x3 + +arr = [ + [ 1, 2 ], + [ 3, 4 ] +]; +shape = arrayShape( arr ); +console.log( shape.join( 'x' ) ); +// => 2x2 + +arr = [ + [ 1, 2, 3 ], + [ 4, 5, 6 ], + [ 7, 8, 9 ] +]; +shape = arrayShape( arr ); +console.log( shape.join( 'x' ) ); +// => 3x3 + +arr = [ + [ 1, 2, 3 ], + null, + [ 7, 8, 9 ] +]; +shape = arrayShape( arr ); +console.log( shape.join( 'x' ) ); +// => 3 + +arr = [ + [ 1, 2, 3 ], + [ [ 4, 5, 6 ] ], + [ [ 7, 8, 9 ] ] +]; +shape = arrayShape( arr ); +console.log( shape.join( 'x' ) ); +// => 3 + +arr = [ + [ [ 1, 2, 3 ] ], + [ 4, 5, 6 ], + [ [ 7, 8, 9 ] ] +]; +shape = arrayShape( arr ); +console.log( shape.join( 'x' ) ); +// => 3 + +arr = [ + [ [ 1, 2, 3 ] ], + [ [ 4, 5, 6 ] ], + [ 7, 8, 9 ] +]; +shape = arrayShape( arr ); +console.log( shape.join( 'x' ) ); +// => 3 + +arr = [ + [ [ [ 1, 2, 3 ] ] ], + [ [ 4, 5, 6 ] ], + [ [ [ 7, 8, 9 ] ] ] +]; +shape = arrayShape( arr ); +console.log( shape.join( 'x' ) ); +// => 3x1 diff --git a/shape/lib/index.js b/shape/lib/index.js new file mode 100644 index 00000000..eecec41c --- /dev/null +++ b/shape/lib/index.js @@ -0,0 +1,58 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Determine (nested) array dimensions. +* +* @module @stdlib/array/shape +* +* @example +* var arrayShape = require( '@stdlib/array/shape' ); +* +* var arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; +* +* var shape = arrayShape( arr ); +* // returns [ 3, 3 ] +* +* @example +* var arrayShape = require( '@stdlib/array/shape' ); +* +* var arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ] ]; +* +* var shape = arrayShape( arr ); +* // returns [ 3 ] +* +* @example +* var arrayShape = require( '@stdlib/array/shape' ); +* +* var arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], null ]; +* +* var shape = arrayShape( arr ); +* // returns [ 3 ] +*/ + +// MODULES // + +var arrayShape = require( './main.js' ); + + +// EXPORTS // + +module.exports = arrayShape; diff --git a/shape/lib/main.js b/shape/lib/main.js new file mode 100644 index 00000000..477af465 --- /dev/null +++ b/shape/lib/main.js @@ -0,0 +1,138 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isArray = require( '@stdlib/assert/is-array' ); + + +// FUNCTIONS // + +/** +* Recursively (and eagerly) attempts to resolve nested array dimensions. +* +* @private +* @param {Array} shape - output array +* @param {Array} arr - array +* @returns {Array} shape array +*/ +function recurse( shape, arr ) { + var v = arr[ 0 ]; + if ( isArray( v ) ) { + shape.push( v.length ); + recurse( shape, v ); + } + return shape; +} + +/** +* Recursively verifies that all nested arrays have consistent dimensions. +* +* @private +* @param {PositiveInteger} ndims - number of dimensions +* @param {Array} shape - shape array +* @param {NonNegativeInteger} d - dimension +* @param {Array} arr - array element to verify +* @param {boolean} flg - boolean indicating whether to continue recursing +* @returns {NonNegativeInteger} number of consistent dimensions +*/ +function check( ndims, shape, d, arr, flg ) { + var len; + var v; + var i; + + // Get the size of the current dimension: + len = shape[ d ]; + + // Ensure that each array element is an array of the same size: + for ( i = 0; i < arr.length; i++ ) { + v = arr[ i ]; + + // If the array element is not an array or is not the same size, we have found an inconsistent dimension: + if ( !isArray( v ) || v.length !== len ) { + // `d` is one more than the index of the last consistent dimension and thus equal to the number of consistent dimensions: + return d; + } + // Recursively examine nested elements: + if ( flg ) { + v = check( ndims, shape, d+1, v, d+1 < ndims-1 ); + if ( v < ndims ) { + // Propagate the number of consistent dimensions up the recursion chain... + return v; + } + } + } + return ndims; +} + + +// MAIN // + +/** +* Determines (nested) array dimensions. +* +* @param {Array} arr - array +* @throws {TypeError} must provide an array +* @returns {Array} array shape +* +* @example +* var arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; +* +* var shape = arrayShape( arr ); +* // returns [ 3, 3 ] +* +* @example +* var arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ] ]; +* +* var shape = arrayShape( arr ); +* // returns [ 3 ] +* +* @example +* var arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], null ]; +* +* var shape = arrayShape( arr ); +* // returns [ 3 ] +*/ +function arrayShape( arr ) { + var shape; + var ndims; + + if ( !isArray( arr ) ) { + throw new TypeError( 'invalid argument. Must provide an array. Value: `' + arr + '`.' ); + } + // Initialize the shape/dimensions array: + shape = [ arr.length ]; + + // Eagerly determine array dimensions: + recurse( shape, arr ); + ndims = shape.length; + + // Check that all array element dimensions are consistent: + if ( ndims > 1 ) { + // If `check()` returns a value less than `ndims`, trim off the inconsistent dimensions: + shape.length = check( ndims, shape, 1, arr, ndims > 2 ); + } + return shape; +} + + +// EXPORTS // + +module.exports = arrayShape; diff --git a/shape/package.json b/shape/package.json new file mode 100644 index 00000000..bc213367 --- /dev/null +++ b/shape/package.json @@ -0,0 +1,63 @@ +{ + "name": "@stdlib/array/shape", + "version": "0.0.0", + "description": "Determine (nested) array dimensions.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "utils", + "util", + "utilities", + "utility", + "array", + "dims", + "dimensions", + "shape" + ] +} diff --git a/shape/test/test.js b/shape/test/test.js new file mode 100644 index 00000000..122b484f --- /dev/null +++ b/shape/test/test.js @@ -0,0 +1,290 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var arrayShape = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof arrayShape, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error if not provided an array', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[ i ] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayShape( value ); + }; + } +}); + +tape( 'the function returns array dimensions (0d)', function test( t ) { + var arr; + + arr = []; + t.deepEqual( arrayShape( arr ), [ 0 ], 'returns expected value' ); + + arr = [ [] ]; + t.deepEqual( arrayShape( arr ), [ 1, 0 ], 'returns expected value' ); + + arr = [ [ [] ] ]; + t.deepEqual( arrayShape( arr ), [ 1, 1, 0 ], 'returns expected value' ); + + arr = [ [], [] ]; + t.deepEqual( arrayShape( arr ), [ 2, 0 ], 'returns expected value' ); + + arr = [ [ [] ], [ [] ] ]; + t.deepEqual( arrayShape( arr ), [ 2, 1, 0 ], 'returns expected value' ); + + arr = [ [], [], [] ]; + t.deepEqual( arrayShape( arr ), [ 3, 0 ], 'returns expected value' ); + + arr = [ [ [ [] ] ], [ [ [] ] ], [ [ [] ] ] ]; + t.deepEqual( arrayShape( arr ), [ 3, 1, 1, 0 ], 'returns expected value' ); + + arr = [ [ [ [ [] ] ] ], [ [ [ [] ] ] ], [ [ [ [] ] ] ] ]; + t.deepEqual( arrayShape( arr ), [ 3, 1, 1, 1, 0 ], 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns array dimensions (1d)', function test( t ) { + var arr; + + arr = [ 1 ]; + t.deepEqual( arrayShape( arr ), [ 1 ], 'returns expected value' ); + + arr = [ 'beep' ]; + t.deepEqual( arrayShape( arr ), [ 1 ], 'returns expected value' ); + + arr = [ 1, 2 ]; + t.deepEqual( arrayShape( arr ), [ 2 ], 'returns expected value' ); + + arr = [ 1, 2, 3 ]; + t.deepEqual( arrayShape( arr ), [ 3 ], 'returns expected value' ); + + arr = [ [ 1 ], [ 2 ], 3 ]; + t.deepEqual( arrayShape( arr ), [ 3 ], 'returns expected value' ); + + arr = [ [ 1 ], [ 2 ], null ]; + t.deepEqual( arrayShape( arr ), [ 3 ], 'returns expected value' ); + + arr = [ [ [ 1 ] ], [ [ 2 ] ], null ]; + t.deepEqual( arrayShape( arr ), [ 3 ], 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns array dimensions (2d)', function test( t ) { + var arr; + + arr = [ [ 1 ] ]; + t.deepEqual( arrayShape( arr ), [ 1, 1 ], 'returns expected value' ); + + arr = [ [ 1 ], [ 2 ] ]; + t.deepEqual( arrayShape( arr ), [ 2, 1 ], 'returns expected value' ); + + arr = [ [ 1 ], [ 2 ], [ 3 ] ]; + t.deepEqual( arrayShape( arr ), [ 3, 1 ], 'returns expected value' ); + + arr = [ [ [ 1 ] ], [ [ 2 ] ], [ 3 ] ]; + t.deepEqual( arrayShape( arr ), [ 3, 1 ], 'returns expected value' ); + + arr = [ [ [ 1 ] ], [ [ 2 ] ], [ null ] ]; + t.deepEqual( arrayShape( arr ), [ 3, 1 ], 'returns expected value' ); + + arr = [ + [ 1, 2, 3 ], + [ 4, 5, 6 ], + [ 7, 8, 9 ] + ]; + t.deepEqual( arrayShape( arr ), [ 3, 3 ], 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns array dimensions (3d)', function test( t ) { + var arr; + + arr = [ [ [ 1 ] ] ]; + t.deepEqual( arrayShape( arr ), [ 1, 1, 1 ], 'returns expected value' ); + + arr = [ [ [ 1 ] ], [ [ 2 ] ] ]; + t.deepEqual( arrayShape( arr ), [ 2, 1, 1 ], 'returns expected value' ); + + arr = [ [ [ 1 ] ], [ [ 2 ] ], [ [ 3 ] ] ]; + t.deepEqual( arrayShape( arr ), [ 3, 1, 1 ], 'returns expected value' ); + + arr = [ [ [ [ 1 ] ] ], [ [ [ 2 ] ] ], [ [ 3 ] ] ]; + t.deepEqual( arrayShape( arr ), [ 3, 1, 1 ], 'returns expected value' ); + + arr = [ [ [ [ 1 ] ] ], [ [ [ 2 ] ] ], [ [ null ] ] ]; + t.deepEqual( arrayShape( arr ), [ 3, 1, 1 ], 'returns expected value' ); + + arr = [ + [ [ 1, 1, 1 ], [ 2, 2, 2 ], [ 3, 3, 3 ] ], + [ [ 4, 4, 4 ], [ 5, 5, 5 ], [ 6, 6, 6 ] ], + [ [ 7, 7, 7 ], [ 8, 8, 8 ], [ 9, 9, 9 ] ] + ]; + t.deepEqual( arrayShape( arr ), [ 3, 3, 3 ], 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns array dimensions (4d)', function test( t ) { + var arr; + + arr = [ [ [ [ 1 ] ] ] ]; + t.deepEqual( arrayShape( arr ), [ 1, 1, 1, 1 ], 'returns expected value' ); + + arr = [ [ [ [ 1 ] ] ], [ [ [ 2 ] ] ] ]; + t.deepEqual( arrayShape( arr ), [ 2, 1, 1, 1 ], 'returns expected value' ); + + arr = [ [ [ [ 1 ] ] ], [ [ [ 2 ] ] ], [ [ [ 3 ] ] ] ]; + t.deepEqual( arrayShape( arr ), [ 3, 1, 1, 1 ], 'returns expected value' ); + + arr = [ [ [ [ [ 1 ] ] ] ], [ [ [ [ 2 ] ] ] ], [ [ [ 3 ] ] ] ]; + t.deepEqual( arrayShape( arr ), [ 3, 1, 1, 1 ], 'returns expected value' ); + + arr = [ [ [ [ [ 1 ] ] ] ], [ [ [ [ 2 ] ] ] ], [ [ [ null ] ] ] ]; + t.deepEqual( arrayShape( arr ), [ 3, 1, 1, 1 ], 'returns expected value' ); + + arr = [ + [ + [ [ 1, 1, 1 ], [ 1, 1, 1 ], [ 1, 1, 1 ] ], + [ [ 2, 2, 2 ], [ 2, 2, 2 ], [ 2, 2, 2 ] ], + [ [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ] ] + ], + [ + [ [ 4, 4, 4 ], [ 4, 4, 4 ], [ 4, 4, 4 ] ], + [ [ 5, 5, 5 ], [ 5, 5, 5 ], [ 5, 5, 5 ] ], + [ [ 6, 6, 6 ], [ 6, 6, 6 ], [ 6, 6, 6 ] ] + ], + [ + [ [ 7, 7, 7 ], [ 7, 7, 7 ], [ 7, 7, 7 ] ], + [ [ 8, 8, 8 ], [ 8, 8, 8 ], [ 8, 8, 8 ] ], + [ [ 9, 9, 9 ], [ 9, 9, 9 ], [ 9, 9, 9 ] ] + ] + ]; + t.deepEqual( arrayShape( arr ), [ 3, 3, 3, 3 ], 'returns expected value' ); + + t.end(); +}); + +tape( 'the function returns array dimensions (5d)', function test( t ) { + var arr; + + arr = [ [ [ [ [ 1 ] ] ] ] ]; + t.deepEqual( arrayShape( arr ), [ 1, 1, 1, 1, 1 ], 'returns expected value' ); + + arr = [ [ [ [ [ 1 ] ] ] ], [ [ [ [ 2 ] ] ] ] ]; + t.deepEqual( arrayShape( arr ), [ 2, 1, 1, 1, 1 ], 'returns expected value' ); + + arr = [ [ [ [ [ 1 ] ] ] ], [ [ [ [ 2 ] ] ] ], [ [ [ [ 3 ] ] ] ] ]; + t.deepEqual( arrayShape( arr ), [ 3, 1, 1, 1, 1 ], 'returns expected value' ); + + arr = [ [ [ [ [ [ 1 ] ] ] ] ], [ [ [ [ [ 2 ] ] ] ] ], [ [ [ [ 3 ] ] ] ] ]; + t.deepEqual( arrayShape( arr ), [ 3, 1, 1, 1, 1 ], 'returns expected value' ); + + arr = [ [ [ [ [ [ 1 ] ] ] ] ], [ [ [ [ [ 2 ] ] ] ] ], [ [ [ [ null ] ] ] ] ]; // eslint-disable-line max-len + t.deepEqual( arrayShape( arr ), [ 3, 1, 1, 1, 1 ], 'returns expected value' ); + + arr = [ + [ + [ + [ [ 1, 1, 1 ], [ 1, 1, 1 ], [ 1, 1, 1 ] ], + [ [ 2, 2, 2 ], [ 2, 2, 2 ], [ 2, 2, 2 ] ], + [ [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ] ] + ], + [ + [ [ 1, 1, 1 ], [ 1, 1, 1 ], [ 1, 1, 1 ] ], + [ [ 2, 2, 2 ], [ 2, 2, 2 ], [ 2, 2, 2 ] ], + [ [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ] ] + ], + [ + [ [ 1, 1, 1 ], [ 1, 1, 1 ], [ 1, 1, 1 ] ], + [ [ 2, 2, 2 ], [ 2, 2, 2 ], [ 2, 2, 2 ] ], + [ [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ] ] + ] + ], + [ + [ + [ [ 4, 4, 4 ], [ 4, 4, 4 ], [ 4, 4, 4 ] ], + [ [ 5, 5, 5 ], [ 5, 5, 5 ], [ 5, 5, 5 ] ], + [ [ 6, 6, 6 ], [ 6, 6, 6 ], [ 6, 6, 6 ] ] + ], + [ + [ [ 4, 4, 4 ], [ 4, 4, 4 ], [ 4, 4, 4 ] ], + [ [ 5, 5, 5 ], [ 5, 5, 5 ], [ 5, 5, 5 ] ], + [ [ 6, 6, 6 ], [ 6, 6, 6 ], [ 6, 6, 6 ] ] + ], + [ + [ [ 4, 4, 4 ], [ 4, 4, 4 ], [ 4, 4, 4 ] ], + [ [ 5, 5, 5 ], [ 5, 5, 5 ], [ 5, 5, 5 ] ], + [ [ 6, 6, 6 ], [ 6, 6, 6 ], [ 6, 6, 6 ] ] + ] + ], + [ + [ + [ [ 7, 7, 7 ], [ 7, 7, 7 ], [ 7, 7, 7 ] ], + [ [ 8, 8, 8 ], [ 8, 8, 8 ], [ 8, 8, 8 ] ], + [ [ 9, 9, 9 ], [ 9, 9, 9 ], [ 9, 9, 9 ] ] + ], + [ + [ [ 7, 7, 7 ], [ 7, 7, 7 ], [ 7, 7, 7 ] ], + [ [ 8, 8, 8 ], [ 8, 8, 8 ], [ 8, 8, 8 ] ], + [ [ 9, 9, 9 ], [ 9, 9, 9 ], [ 9, 9, 9 ] ] + ], + [ + [ [ 7, 7, 7 ], [ 7, 7, 7 ], [ 7, 7, 7 ] ], + [ [ 8, 8, 8 ], [ 8, 8, 8 ], [ 8, 8, 8 ] ], + [ [ 9, 9, 9 ], [ 9, 9, 9 ], [ 9, 9, 9 ] ] + ] + ] + ]; + t.deepEqual( arrayShape( arr ), [ 3, 3, 3, 3, 3 ], 'returns expected value' ); + + t.end(); +}); diff --git a/shared-buffer/README.md b/shared-buffer/README.md new file mode 100644 index 00000000..a7d3e3e8 --- /dev/null +++ b/shared-buffer/README.md @@ -0,0 +1,261 @@ + + +# SharedArrayBuffer + +> [Constructor][mdn-sharedarraybuffer] returning an object used to represent a generic, fixed-length raw binary data buffer which can be used to create views of shared memory. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var SharedArrayBuffer = require( '@stdlib/array/shared-buffer' ); +``` + +#### SharedArrayBuffer( size ) + +Returns a [`SharedArrayBuffer`][mdn-sharedarraybuffer] having a specified number of bytes. + + + +```javascript +try { + var buf = new SharedArrayBuffer( 5 ); + // returns +} catch ( err ) { + console.log( 'Environment does not support SharedArrayBuffers.' ); +} +``` + +* * * + +### Properties + +#### SharedArrayBuffer.length + +Number of input arguments the constructor accepts. + + + +```javascript +var len = SharedArrayBuffer.length; +// returns 1 +``` + +#### SharedArrayBuffer.prototype.byteLength + +**Read-only** property which returns the length (in bytes) of the [`SharedArrayBuffer`][mdn-sharedarraybuffer]. + + + +```javascript +try { + var buf = new SharedArrayBuffer( 5 ); + var byteLength = buf.byteLength; + // returns 5 +} catch ( err ) { + console.log( 'Environment does not support SharedArrayBuffers.' ); +} +``` + +* * * + +### Methods + +#### SharedArrayBuffer.prototype.slice( \[start\[, end]] ) + +Copies the bytes of a [`SharedArrayBuffer`][mdn-sharedarraybuffer] to a new [`SharedArrayBuffer`][mdn-sharedarraybuffer]. + + + +```javascript +try { + var b1 = new SharedArrayBuffer( 10 ); + + var b2 = b1.slice(); + // returns + + var bool = ( b2 === b1 ); + // returns false +} catch ( err ) { + console.log( 'Environment does not support SharedArrayBuffers.' ); +} +``` + +By default, the method copies from the beginning of the [`SharedArrayBuffer`][mdn-sharedarraybuffer]. To beginning copying from a different byte index, provide a `start` argument, specifying the starting byte index (inclusive). + + + +```javascript +try { + var b1 = new SharedArrayBuffer( 10 ); + var b2 = b1.slice( 2 ); + + var nbytes = b2.byteLength; + // returns 8 +} catch ( err ) { + console.log( 'Environment does not support SharedArrayBuffers.' ); +} +``` + +If `start < 0`, the index is relative to the end of the [`SharedArrayBuffer`][mdn-sharedarraybuffer]. + + + +```javascript +try { + var b1 = new SharedArrayBuffer( 10 ); + var b2 = b1.slice( -2 ); + + var nbytes = b2.byteLength; + // returns 2 +} catch ( err ) { + console.log( 'Environment does not support SharedArrayBuffers.' ); +} +``` + +By default, the method copies to the end of the [`SharedArrayBuffer`][mdn-sharedarraybuffer]. To copy until a particular byte index, provide an `end` index, specifying the ending byte index (exclusive). + + + +```javascript +try { + var b1 = new SharedArrayBuffer( 10 ); + var b2 = b1.slice( 2, 6 ); + + var nbytes = b2.byteLength; + // returns 4 +} catch ( err ) { + console.log( 'Environment does not support SharedArrayBuffers.' ); +} +``` + +If `end < 0`, the index is relative to the end of the [`SharedArrayBuffer`][mdn-sharedarraybuffer]. + + + +```javascript +try { + var b1 = new SharedArrayBuffer( 10 ); + var b2 = b1.slice( 2, -2 ); + + var nbytes = b2.byteLength; + // returns 6 +} catch ( err ) { + console.log( 'Environment does not support SharedArrayBuffers.' ); +} +``` + +
+ + + +* * * + + + +
+ +
+ + + + + +
+ +## Examples + + + + + + + +```javascript +var randu = require( '@stdlib/random/base/randu' ); +var Float64Array = require( '@stdlib/array/float64' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var toBinaryString = require( '@stdlib/number/uint8/base/to-binary-string' ); +var SharedArrayBuffer = require( '@stdlib/array/shared-buffer' ); + +function main() { + var bytes; + var buf; + var arr; + var i; + + // Create a new SharedArrayBuffer: + buf = new SharedArrayBuffer( 64 ); + + // Create a Float64 array buffer view: + arr = new Float64Array( buf.byteLength/8 ); + for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = randu() * 100.0; + } + + // Create a "bytes" view of the array buffer: + bytes = new Uint8Array( arr.buffer ); + + // Print the bytes: + for ( i = 0; i < bytes.length; i++ ) { + console.log( 'byte %d: %s', i, toBinaryString( bytes[ i ] ) ); + } +} + +try { + main(); +} catch ( err ) { + console.error( 'Environment does not provide SharedArrayBuffer support.' ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/shared-buffer/benchmark/benchmark.js b/shared-buffer/benchmark/benchmark.js new file mode 100644 index 00000000..35788a63 --- /dev/null +++ b/shared-buffer/benchmark/benchmark.js @@ -0,0 +1,55 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var hasSharedArrayBufferSupport = require( '@stdlib/assert/has-sharedarraybuffer-support' ); // eslint-disable-line id-length +var isSharedArrayBuffer = require( '@stdlib/assert/is-sharedarraybuffer' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// VARIABLES // + +var opts = { + 'skip': !hasSharedArrayBufferSupport() +}; + + +// MAIN // + +bench( pkg, opts, function benchmark( b ) { + var buf; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf = new ctor( 0 ); + if ( buf.byteLength !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isSharedArrayBuffer( buf ) ) { + b.fail( 'should return a SharedArrayBuffer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/shared-buffer/benchmark/benchmark.length.js b/shared-buffer/benchmark/benchmark.length.js new file mode 100644 index 00000000..1a546a89 --- /dev/null +++ b/shared-buffer/benchmark/benchmark.length.js @@ -0,0 +1,101 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var hasSharedArrayBufferSupport = require( '@stdlib/assert/has-sharedarraybuffer-support' ); // eslint-disable-line id-length +var pow = require( '@stdlib/math/base/special/pow' ); +var isSharedArrayBuffer = require( '@stdlib/assert/is-sharedarraybuffer' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// VARIABLES // + +var opts = { + 'skip': !hasSharedArrayBufferSupport() +}; + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array buffer length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var buf; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf = new ctor( len ); + if ( buf.byteLength !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isSharedArrayBuffer( buf ) ) { + b.fail( 'should return a SharedArrayBuffer' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':len='+len, opts, f ); + } +} + +main(); diff --git a/shared-buffer/docs/repl.txt b/shared-buffer/docs/repl.txt new file mode 100644 index 00000000..82eed3ed --- /dev/null +++ b/shared-buffer/docs/repl.txt @@ -0,0 +1,82 @@ + +{{alias}}( size ) + Returns a shared array buffer having a specified number of bytes. + + A shared array buffer behaves similarly to a non-shared array buffer, except + that a shared array buffer allows creating views of memory shared between + threads. + + Buffer contents are initialized to 0. + + If an environment does not support shared array buffers, the function throws + an error. + + Parameters + ---------- + size: integer + Number of bytes. + + Returns + ------- + out: SharedArrayBuffer + A shared array buffer. + + Examples + -------- + // Assuming an environment supports SharedArrayBuffers... + > var buf = new {{alias}}( 5 ) + + + +{{alias}}.length + Number of input arguments the constructor accepts. + + Examples + -------- + > {{alias}}.length + 1 + + +{{alias}}.prototype.byteLength + Read-only property which returns the length (in bytes) of the array buffer. + + Examples + -------- + // Assuming an environment supports SharedArrayBuffers... + > var buf = new {{alias}}( 5 ); + > buf.byteLength + 5 + + +{{alias}}.prototype.slice( [start[, end]] ) + Copies the bytes of a shared array buffer to a new shared array buffer. + + Parameters + ---------- + start: integer (optional) + Index at which to start copying buffer contents (inclusive). If + negative, the index is relative to the end of the buffer. + + end: integer (optional) + Index at which to stop copying buffer contents (exclusive). If negative, + the index is relative to the end of the buffer. + + Returns + ------- + out: SharedArrayBuffer + A new shared array buffer whose contents have been copied from the + calling shared array buffer. + + Examples + -------- + // Assuming an environment supports SharedArrayBuffers... + > var b1 = new {{alias}}( 10 ); + > var b2 = b1.slice( 2, 6 ); + > var bool = ( b1 === b2 ) + false + > b2.byteLength + 4 + + See Also + -------- + diff --git a/shared-buffer/docs/types/index.d.ts b/shared-buffer/docs/types/index.d.ts new file mode 100644 index 00000000..ed15c12f --- /dev/null +++ b/shared-buffer/docs/types/index.d.ts @@ -0,0 +1,28 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +// EXPORTS // + +/** +* Constructor returning an object used to represent a generic, fixed-length raw binary data buffer which can be used to create views of shared memory. +*/ +export = SharedArrayBuffer; // tslint:disable-line + +// FIXME: need to address TSLint errors regarding ES version diff --git a/shared-buffer/docs/types/test.ts b/shared-buffer/docs/types/test.ts new file mode 100644 index 00000000..59cc92c0 --- /dev/null +++ b/shared-buffer/docs/types/test.ts @@ -0,0 +1,31 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// tslint:disable: no-construct +// tslint:disable: no-unused-expression +// tslint:disable: no-unsafe-any + +import SharedArrayBuffer = require( './index' ); + + +// TESTS // + +// The function returns a shared array buffer instance... +{ + new SharedArrayBuffer( 10 ); // $ExpectType any +} diff --git a/shared-buffer/examples/index.js b/shared-buffer/examples/index.js new file mode 100644 index 00000000..5721b215 --- /dev/null +++ b/shared-buffer/examples/index.js @@ -0,0 +1,55 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var randu = require( '@stdlib/random/base/randu' ); +var Float64Array = require( '@stdlib/array/float64' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var toBinaryString = require( '@stdlib/number/uint8/base/to-binary-string' ); +var SharedArrayBuffer = require( './../lib' ); + +function main() { + var bytes; + var buf; + var arr; + var i; + + // Create a new SharedArrayBuffer: + buf = new SharedArrayBuffer( 64 ); + + // Create a Float64 array buffer view: + arr = new Float64Array( buf.byteLength/8 ); + for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = randu() * 100.0; + } + + // Create a "bytes" view of the array buffer: + bytes = new Uint8Array( arr.buffer ); + + // Print the bytes: + for ( i = 0; i < bytes.length; i++ ) { + console.log( 'byte %d: %s', i, toBinaryString( bytes[ i ] ) ); + } +} + +try { + main(); +} catch ( err ) { // eslint-disable-line no-unused-vars + console.error( 'Environment does not provide SharedArrayBuffer support.' ); +} diff --git a/shared-buffer/lib/index.js b/shared-buffer/lib/index.js new file mode 100644 index 00000000..c454029b --- /dev/null +++ b/shared-buffer/lib/index.js @@ -0,0 +1,57 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Constructor returning an object used to represent a generic, fixed-length raw binary data buffer which can be used to create views of shared memory. +* +* @module @stdlib/array/shared-buffer +* +* @example +* var ctor = require( '@stdlib/array/shared-buffer' ); +* +* var buf; +* try { +* buf = new ctor( 10 ); +* // returns +* } catch ( err ) { +* console.log( 'Environment does not support SharedArrayBuffers.' ); +* } +*/ + +// MODULES // + +var hasSharedArrayBufferSupport = require( '@stdlib/assert/has-sharedarraybuffer-support' ); // eslint-disable-line id-length +var builtin = require( './sharedarraybuffer.js' ); +var polyfill = require( './polyfill.js' ); + + +// MAIN // + +var ctor; +if ( hasSharedArrayBufferSupport() ) { + ctor = builtin; +} else { + ctor = polyfill; +} + + +// EXPORTS // + +module.exports = ctor; diff --git a/shared-buffer/lib/polyfill.js b/shared-buffer/lib/polyfill.js new file mode 100644 index 00000000..7cb1cca1 --- /dev/null +++ b/shared-buffer/lib/polyfill.js @@ -0,0 +1,36 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MAIN // + +/** +* Constructor returning an object used to represent a generic, fixed-length raw binary data buffer which can be used to create views of shared memory. +* +* @param {NonNegativeInteger} size - number of bytes +* @throws {Error} not implemented +*/ +function polyfill( size ) { // eslint-disable-line no-unused-vars + throw new Error( 'The current environment does not support SharedArrayBuffers, and, unfortunately, SharedArrayBuffers cannot be polyfilled. For shared memory applications, upgrade your runtime environment to one which supports SharedArrayBuffers.' ); +} + + +// EXPORTS // + +module.exports = polyfill; diff --git a/shared-buffer/lib/sharedarraybuffer.js b/shared-buffer/lib/sharedarraybuffer.js new file mode 100644 index 00000000..fa86dd95 --- /dev/null +++ b/shared-buffer/lib/sharedarraybuffer.js @@ -0,0 +1,28 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MAIN // + +var ctor = ( typeof SharedArrayBuffer === 'function' ) ? SharedArrayBuffer : null; // eslint-disable-line stdlib/require-globals, no-undef + + +// EXPORTS // + +module.exports = ctor; diff --git a/shared-buffer/package.json b/shared-buffer/package.json new file mode 100644 index 00000000..17a31bed --- /dev/null +++ b/shared-buffer/package.json @@ -0,0 +1,71 @@ +{ + "name": "@stdlib/array/shared-buffer", + "version": "0.0.0", + "description": "SharedArrayBuffer.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structure", + "array", + "typed", + "typed array", + "typed-array", + "arraybuffer", + "shared", + "memory", + "concurrency", + "parallelism", + "threading", + "buffer", + "buf", + "binary" + ] +} diff --git a/shared-buffer/test/test.js b/shared-buffer/test/test.js new file mode 100644 index 00000000..14355978 --- /dev/null +++ b/shared-buffer/test/test.js @@ -0,0 +1,182 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var hasSharedArrayBufferSupport = require( '@stdlib/assert/has-sharedarraybuffer-support' ); // eslint-disable-line id-length +var isFunction = require( '@stdlib/assert/is-function' ); +var instanceOf = require( '@stdlib/assert/instance-of' ); +var MAX_SAFE_INTEGER = require( '@stdlib/constants/float64/max-safe-integer' ); +var hasOwnProp = require( '@stdlib/assert/has-own-property' ); +var hasProp = require( '@stdlib/assert/has-property' ); +var polyfill = require( './../lib/polyfill.js' ); +var Ctor = require( './../lib' ); + + +// VARIABLES // + +var opts = { + 'skip': !hasSharedArrayBufferSupport() +}; + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof Ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'if an environment supports `SharedArrayBuffer`, the export is an alias for `SharedArrayBuffer`', function test( t ) { + var Foo = proxyquire( './../lib', { + '@stdlib/assert/has-sharedarraybuffer-support': isTrue, + './sharedarraybuffer.js': Mock + }); + t.strictEqual( Foo, Mock, 'returns built-in' ); + + if ( !opts.skip ) { + t.strictEqual( Ctor, SharedArrayBuffer, 'is alias' ); // eslint-disable-line stdlib/require-globals, no-undef + } + + t.end(); + + function Mock() { + return this; + } + + function isTrue() { + return true; + } +}); + +tape( 'if an environment does not support `SharedArrayBuffer`, the export is a polyfill', function test( t ) { + var Foo = proxyquire( './../lib', { + '@stdlib/assert/has-sharedarraybuffer-support': isFalse + }); + + t.strictEqual( Foo, polyfill, 'returns polyfill' ); + t.end(); + + function isFalse() { + return false; + } +}); + +tape( 'the main export is a constructor', opts, function test( t ) { + var buf = new Ctor( 10 ); + t.strictEqual( instanceOf( buf, Ctor ), true, 'returns an instance' ); + t.end(); +}); + +tape( 'the constructor length is equal to `1`', opts, function test( t ) { + t.strictEqual( Ctor.length, 1, 'returns expected value' ); + t.end(); +}); + +tape( 'the constructor throws an error if provided a value exceeding `2^53-1`', opts, function test( t ) { + t.throws( badValue, RangeError, 'throws an error' ); + t.end(); + + function badValue() { + return new Ctor( MAX_SAFE_INTEGER+1 ); + } +}); + +tape( 'the constructor returns a `SharedArrayBuffer` instance having a `byteLength` property, which returns the number of bytes in a `SharedArrayBuffer`', opts, function test( t ) { + var buf; + + t.strictEqual( hasOwnProp( Ctor.prototype, 'byteLength' ), true, 'has prototype property' ); + + buf = new Ctor( 10 ); + t.strictEqual( hasOwnProp( buf, 'byteLength' ), false, 'does not have own property' ); + t.strictEqual( hasProp( buf, 'byteLength' ), true, 'has property' ); + t.strictEqual( buf.byteLength, 10, 'returns expected value' ); + + t.end(); +}); + +tape( 'the constructor returns a `SharedArrayBuffer` instance having a `slice` method, which copies the bytes of a `SharedArrayBuffer` to a new `SharedArrayBuffer`', opts, function test( t ) { + var b1; + var b2; + + t.strictEqual( hasOwnProp( Ctor.prototype, 'slice' ), true, 'has prototype property' ); + t.strictEqual( isFunction( Ctor.prototype.slice ), true, 'has method' ); + + b1 = new Ctor( 10 ); + t.strictEqual( hasOwnProp( b1, 'slice' ), false, 'does not have own property' ); + t.strictEqual( hasProp( b1, 'slice' ), true, 'has property' ); + + b2 = b1.slice(); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, b1.byteLength, 'has same number of bytes' ); + + b2 = b1.slice( 2 ); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, 8, 'has expected number of bytes' ); + + b2 = b1.slice( b1.byteLength + 10 ); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, 0, 'has expected number of bytes' ); + + b2 = b1.slice( -2 ); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, 2, 'has expected number of bytes' ); + + b2 = b1.slice( -100 ); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, 10, 'has expected number of bytes' ); + + b2 = b1.slice( 0, 6 ); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, 6, 'has expected number of bytes' ); + + b2 = b1.slice( 2, 6 ); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, 4, 'has expected number of bytes' ); + + b2 = b1.slice( 0, -2 ); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, 8, 'has expected number of bytes' ); + + b2 = b1.slice( 0, -100 ); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, 0, 'has expected number of bytes' ); + + b2 = b1.slice( -4, -2 ); + t.strictEqual( instanceOf( b2, Ctor ), true, 'returns an instance' ); + t.notEqual( b2, b1, 'returns a new reference' ); + t.strictEqual( b2.byteLength, 2, 'has expected number of bytes' ); + + t.end(); +}); + +// TODO: add tests testing shared memory semantics/behavior diff --git a/shared-buffer/test/test.polyfill.js b/shared-buffer/test/test.polyfill.js new file mode 100644 index 00000000..3cc5d542 --- /dev/null +++ b/shared-buffer/test/test.polyfill.js @@ -0,0 +1,42 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var ctor = require( './../lib/polyfill.js' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error when invoked', function test( t ) { + t.throws( foo, Error, 'throws an error' ); + t.end(); + + function foo() { + var f = new ctor(); // eslint-disable-line no-unused-vars + } +}); diff --git a/test/test.js b/test/test.js new file mode 100644 index 00000000..14dda1f7 --- /dev/null +++ b/test/test.js @@ -0,0 +1,40 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var objectKeys = require( '@stdlib/utils/keys' ); +var ns = require( './../lib' ); + + +// TESTS // + +tape( 'main export is an object', function test( t ) { + t.ok( true, __filename ); + t.equal( typeof ns, 'object', 'main export is an object' ); + t.end(); +}); + +tape( 'the exported object contains key-value pairs', function test( t ) { + var keys = objectKeys( ns ); + t.equal( keys.length > 0, true, 'has keys' ); + t.end(); +}); diff --git a/to-circular-iterator/README.md b/to-circular-iterator/README.md new file mode 100644 index 00000000..02ef6752 --- /dev/null +++ b/to-circular-iterator/README.md @@ -0,0 +1,298 @@ + + +# circarray2iterator + +> Create an iterator which repeatedly iterates over the elements of an array-like object. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var circarray2iterator = require( '@stdlib/array/to-circular-iterator' ); +``` + +#### circarray2iterator( src\[, options]\[, mapFcn\[, thisArg]] ) + +Returns an iterator which repeatedly iterates over each element in an array-like `object`. + +```javascript +var it = circarray2iterator( [ 1, 2, 3, 4 ] ); +// returns + +var v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 2 + +v = it.next().value; +// returns 3 + +v = it.next().value; +// returns 4 + +v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 2 + +v = it.next().value; +// returns 3 + +v = it.next().value; +// returns 4 + +// ... +``` + +The returned iterator protocol-compliant object has the following properties: + +- **next**: function which returns an iterator protocol-compliant object containing the next iterated value (if one exists) assigned to a `value` property and a `done` property having a `boolean` value indicating whether the iterator is finished. +- **return**: function which closes an iterator and returns a single (optional) argument in an iterator protocol-compliant object. + +The function accepts the following `options`: + +- **iter**: number of iterations. Default: `1e308`. +- **dir**: iteration direction. If set to `-1`, the iterator iterates over elements from right-to-left. Default: `1`. + +To limit the number of iterations, set the `iter` option. + +```javascript +var opts = { + 'iter': 5 +}; +var it = circarray2iterator( [ 1, 2, 3, 4 ], opts ); +// returns + +var v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 2 + +v = it.next().value; +// returns 3 + +v = it.next().value; +// returns 4 + +v = it.next().value; +// returns 1 + +var bool = it.next().done; +// returns true +``` + +To iterate over elements from right to left, set the `dir` option to `-1`. + +```javascript +var opts = { + 'dir': -1 +}; +var it = circarray2iterator( [ 1, 2, 3, 4 ], opts ); +// returns + +var v = it.next().value; +// returns 4 + +v = it.next().value; +// returns 3 + +v = it.next().value; +// returns 2 + +v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 4 + +v = it.next().value; +// returns 3 + +// ... +``` + +To invoke a function for each `src` value, provide a callback function. + +```javascript +function fcn( v ) { + return v * 10.0; +} + +var it = circarray2iterator( [ 1, 2, 3, 4 ], fcn ); +// returns + +var v = it.next().value; +// returns 10.0 + +v = it.next().value; +// returns 20.0 + +v = it.next().value; +// returns 30.0 + +// ... +``` + +The invoked function is provided four arguments: + +- `value`: iterated value +- `index`: iterated value index +- `n`: iteration count +- `src`: source array-like object + +```javascript +function fcn( v, i ) { + return v * (i+1); +} + +var it = circarray2iterator( [ 1, 2, 3, 4 ], fcn ); +// returns + +var v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 4 + +v = it.next().value; +// returns 9 + +// ... +``` + +To set the callback function execution context, provide a `thisArg`. + +```javascript +function fcn( v ) { + this.count += 1; + return v * 10.0; +} + +var ctx = { + 'count': 0 +}; + +var it = circarray2iterator( [ 1, 2, 3, 4 ], fcn, ctx ); +// returns + +var v = it.next().value; +// returns 10.0 + +v = it.next().value; +// returns 20.0 + +v = it.next().value; +// returns 30.0 + +var count = ctx.count; +// returns 3 +``` + + + + + + + +
+ +## Notes + +- If an environment supports `Symbol.iterator`, the returned iterator is iterable. +- If provided a generic `array`, the returned iterator does **not** ignore holes. To achieve greater performance for sparse arrays, use a custom iterator. +- A returned iterator does **not** copy a provided array-like `object`. To ensure iterable reproducibility, copy a provided array-like `object` **before** creating an iterator. Otherwise, any changes to the contents of an array-like `object` will be reflected in the returned iterator. +- In environments supporting `Symbol.iterator`, the function **explicitly** does **not** invoke an array's `@@iterator` method, regardless of whether this method is defined. To convert an array to an implementation defined iterator, invoke this method directly. + +
+ + + + + +
+ +## Examples + + + +```javascript +var Float64Array = require( '@stdlib/array/float64' ); +var inmap = require( '@stdlib/utils/inmap' ); +var randu = require( '@stdlib/random/base/randu' ); +var circarray2iterator = require( '@stdlib/array/to-circular-iterator' ); + +function scale( v, i, n ) { + return v * n; +} + +// Create an array filled with random numbers: +var arr = inmap( new Float64Array( 10 ), randu ); + +// Create an iterator from the array which scales iterated values: +var opts = { + 'iter': arr.length * 10 +}; +var it = circarray2iterator( arr, opts, scale ); + +// Perform manual iteration... +var v; +while ( true ) { + v = it.next(); + if ( v.done ) { + break; + } + console.log( v.value ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/to-circular-iterator/benchmark/benchmark.js b/to-circular-iterator/benchmark/benchmark.js new file mode 100644 index 00000000..71c93103 --- /dev/null +++ b/to-circular-iterator/benchmark/benchmark.js @@ -0,0 +1,107 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isnan = require( '@stdlib/math/base/assert/is-nan' ); +var isIteratorLike = require( '@stdlib/assert/is-iterator-like' ); +var pkg = require( './../package.json' ).name; +var circarray2iterator = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var values; + var iter; + var i; + + values = [ 1, 2, 3, 4 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + values[ 0 ] = i; + iter = circarray2iterator( values ); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isIteratorLike( iter ) ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::iteration', function benchmark( b ) { + var values; + var iter; + var z; + var i; + + values = [ 1, 2, 3, 4 ]; + + iter = circarray2iterator( values ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + z = iter.next().value; + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::iteration,map', function benchmark( b ) { + var values; + var iter; + var z; + var i; + + values = [ 1, 2, 3, 4 ]; + + iter = circarray2iterator( values, transform ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + z = iter.next().value; + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function transform( v, i ) { + return v * i; + } +}); diff --git a/to-circular-iterator/docs/repl.txt b/to-circular-iterator/docs/repl.txt new file mode 100644 index 00000000..332568ff --- /dev/null +++ b/to-circular-iterator/docs/repl.txt @@ -0,0 +1,65 @@ + +{{alias}}( src[, options][, mapFcn[, thisArg]] ) + Returns an iterator which repeatedly iterates over the elements of an array- + like object. + + When invoked, an input function is provided four arguments: + + - value: iterated value + - index: iterated value index + - n: iteration count + - src: source array-like object + + If an environment supports Symbol.iterator, the returned iterator is + iterable. + + If an environment supports Symbol.iterator, the function explicitly does not + not invoke an array's `@@iterator` method, regardless of whether this method + is defined. To convert an array to an implementation defined iterator, + invoke this method directly. + + Parameters + ---------- + src: ArrayLikeObject + Array-like object from which to create the iterator. + + options: Object (optional) + Function options. + + options.iter: integer (optional) + Number of iterations. Default: 1e308. + + options.dir: integer (optional) + Iteration direction. If set to `-1`, an iterator iterates over elements + from right-to-left. Default: 1. + + mapFcn: Function (optional) + Function to invoke for each iterated value. + + thisArg: any (optional) + Execution context. + + Returns + ------- + iterator: Object + Iterator. + + iterator.next(): Function + Returns an iterator protocol-compliant object containing the next + iterated value (if one exists) and a boolean flag indicating whether the + iterator is finished. + + iterator.return( [value] ): Function + Finishes an iterator and returns a provided value. + + Examples + -------- + > var it = {{alias}}( [ 1, 2, 3, 4 ] ); + > var v = it.next().value + 1 + > v = it.next().value + 2 + + See Also + -------- + diff --git a/to-circular-iterator/docs/types/index.d.ts b/to-circular-iterator/docs/types/index.d.ts new file mode 100644 index 00000000..55dbb81d --- /dev/null +++ b/to-circular-iterator/docs/types/index.d.ts @@ -0,0 +1,158 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/// + +import { Iterator as Iter, IterableIterator } from '@stdlib/types/iter'; +import { ArrayLike } from '@stdlib/types/array'; + +// Define a union type representing both iterable and non-iterable iterators: +type Iterator = Iter | IterableIterator; + +/** +* Interface defining function options. +*/ +interface Options { + /** + * Number of iterations. + */ + iter?: number; + + /** + * Iteration direction (default: 1). + */ + dir?: number; +} + +/** +* Map function invoked for each iterated value. +* +* @returns iterator value +*/ +type Nullary = () => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @returns iterator value +*/ +type Unary = ( value: any ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @returns iterator value +*/ +type Binary = ( value: any, index: number ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @param n - iteration count +* @returns iterator value +*/ +type Tertiary = ( value: any, index: number, n: number ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @param n - iteration count +* @param src - source array-like object +* @returns iterator value +*/ +type Quaternary = ( value: any, index: number, n: number, src: ArrayLike ) => any; // tslint-disable-line max-line-length + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @param n - iteration count +* @param src - source array-like object +* @returns iterator value +*/ +type MapFunction = Nullary | Unary | Binary | Tertiary | Quaternary; + +/** +* Returns an iterator which repeatedly iterates over each element in an array-like object. +* +* @param src - input value +* @param mapFcn - function to invoke for each iterated value +* @param thisArg - execution context +* @throws must provide valid options +* @returns iterator +* +* @example +* var iter = circarray2iterator( [ 1, 2, 3, 4 ] ); +* +* var v = iter.next().value; +* // returns 1 +* +* v = iter.next().value; +* // returns 2 +* +* v = iter.next().value; +* // returns 3 +* +* // ... +*/ +declare function circarray2iterator( src: ArrayLike, mapFcn?: MapFunction, thisArg?: any ): Iterator; // tslint:disable-line:max-line-length + +/** +* Returns an iterator which repeatedly iterates over each element in an array-like object. +* +* @param src - input value +* @param options - function options +* @param options.iter - number of iterations +* @param options.dir - iteration direction +* @param mapFcn - function to invoke for each iterated value +* @param thisArg - execution context +* @throws must provide valid options +* @returns iterator +* +* @example +* var opts = { +* 'dir': -1 +* }; +* var it = circarray2iterator( [ 1, 2, 3, 4 ], opts ); +* // returns +* +* var v = it.next().value; +* // returns 4 +* +* v = it.next().value; +* // returns 3 +* +* v = it.next().value; +* // returns 2 +*/ +declare function circarray2iterator( src: ArrayLike, options: Options, mapFcn?: MapFunction, thisArg?: any ): Iterator; // tslint:disable-line:max-line-length + + +// EXPORTS // + +export = circarray2iterator; diff --git a/to-circular-iterator/docs/types/test.ts b/to-circular-iterator/docs/types/test.ts new file mode 100644 index 00000000..8252de59 --- /dev/null +++ b/to-circular-iterator/docs/types/test.ts @@ -0,0 +1,87 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import circarray2iterator = require( './index' ); + +/** +* Multiplies a value by 10. +* +* @param v - iterated value +* @returns new value +*/ +function times10( v: number ): number { + return v * 10.0; +} + + +// TESTS // + +// The function returns an iterator... +{ + circarray2iterator( [ 1, 2, 3, 4 ] ); // $ExpectType Iterator + circarray2iterator( [ 1, 2, 3, 4 ], times10 ); // $ExpectType Iterator + circarray2iterator( [ 1, 2, 3, 4 ], times10, {} ); // $ExpectType Iterator +} + +// The compiler throws an error if the function is provided a first argument which is not array-like... +{ + circarray2iterator( 123 ); // $ExpectError + circarray2iterator( true ); // $ExpectError + circarray2iterator( false ); // $ExpectError + circarray2iterator( {} ); // $ExpectError + circarray2iterator( null ); // $ExpectError + circarray2iterator( undefined ); // $ExpectError +} + +// The compiler throws an error if the function is provided a second argument which is not an options object or function... +{ + circarray2iterator( [ 1, 2, 3, 4 ], 'abc' ); // $ExpectError + circarray2iterator( [ 1, 2, 3, 4 ], 123 ); // $ExpectError + circarray2iterator( [ 1, 2, 3, 4 ], [] ); // $ExpectError + circarray2iterator( [ 1, 2, 3, 4 ], true ); // $ExpectError + circarray2iterator( [ 1, 2, 3, 4 ], false ); // $ExpectError + circarray2iterator( [ 1, 2, 3, 4 ], null ); // $ExpectError +} + +// The compiler throws an error if the function is provided a `dir` option which is not a number... +{ + circarray2iterator( [ 1, 2, 3, 4 ], { 'dir': 'abc' } ); // $ExpectError + circarray2iterator( [ 1, 2, 3, 4 ], { 'dir': true } ); // $ExpectError + circarray2iterator( [ 1, 2, 3, 4 ], { 'dir': false } ); // $ExpectError + circarray2iterator( [ 1, 2, 3, 4 ], { 'dir': null } ); // $ExpectError + circarray2iterator( [ 1, 2, 3, 4 ], { 'dir': [] } ); // $ExpectError + circarray2iterator( [ 1, 2, 3, 4 ], { 'dir': {} } ); // $ExpectError + circarray2iterator( [ 1, 2, 3, 4 ], { 'dir': ( x: number ): number => x } ); // $ExpectError +} + +// The compiler throws an error if the function is provided an `iter` option which is not a number... +{ + circarray2iterator( [ 1, 2, 3, 4 ], { 'iter': 'abc' } ); // $ExpectError + circarray2iterator( [ 1, 2, 3, 4 ], { 'iter': true } ); // $ExpectError + circarray2iterator( [ 1, 2, 3, 4 ], { 'iter': false } ); // $ExpectError + circarray2iterator( [ 1, 2, 3, 4 ], { 'iter': null } ); // $ExpectError + circarray2iterator( [ 1, 2, 3, 4 ], { 'iter': [] } ); // $ExpectError + circarray2iterator( [ 1, 2, 3, 4 ], { 'iter': {} } ); // $ExpectError + circarray2iterator( [ 1, 2, 3, 4 ], { 'iter': ( x: number ): number => x } ); // $ExpectError +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + circarray2iterator(); // $ExpectError + circarray2iterator( [ 1, 2, 3, 4 ], times10, {}, 123 ); // $ExpectError +} diff --git a/to-circular-iterator/examples/index.js b/to-circular-iterator/examples/index.js new file mode 100644 index 00000000..81ba6df9 --- /dev/null +++ b/to-circular-iterator/examples/index.js @@ -0,0 +1,47 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var Float64Array = require( '@stdlib/array/float64' ); +var inmap = require( '@stdlib/utils/inmap' ); +var randu = require( '@stdlib/random/base/randu' ); +var circarray2iterator = require( './../lib' ); + +function scale( v, i, n ) { + return v * n; +} + +// Create an array filled with random numbers: +var arr = inmap( new Float64Array( 10 ), randu ); + +// Create an iterator from the array which scales iterated values: +var opts = { + 'iter': arr.length * 10 +}; +var it = circarray2iterator( arr, opts, scale ); + +// Perform manual iteration... +var v; +while ( true ) { + v = it.next(); + if ( v.done ) { + break; + } + console.log( v.value ); +} diff --git a/to-circular-iterator/lib/index.js b/to-circular-iterator/lib/index.js new file mode 100644 index 00000000..c28ac1ae --- /dev/null +++ b/to-circular-iterator/lib/index.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Create an iterator which repeatedly iterates over the elements of an array-like object. +* +* @module @stdlib/array/to-circular-iterator +* +* @example +* var circarray2iterator = require( '@stdlib/array/to-circular-iterator' ); +* +* var iter = circarray2iterator( [ 1, 2, 3, 4 ] ); +* +* var v = iter.next().value; +* // returns 1 +* +* v = iter.next().value; +* // returns 2 +* +* v = iter.next().value; +* // returns 3 +* +* // ... +*/ + +// MODULES // + +var iterator = require( './main.js' ); + + +// EXPORTS // + +module.exports = iterator; diff --git a/to-circular-iterator/lib/main.js b/to-circular-iterator/lib/main.js new file mode 100644 index 00000000..72adb47b --- /dev/null +++ b/to-circular-iterator/lib/main.js @@ -0,0 +1,259 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); +var hasOwnProp = require( '@stdlib/assert/has-own-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var isCollection = require( '@stdlib/assert/is-collection' ); +var isObject = require( '@stdlib/assert/is-plain-object' ); +var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; +var iteratorSymbol = require( '@stdlib/symbol/iterator' ); + + +// MAIN // + +/** +* Returns an iterator which repeatedly iterates over each element in an array-like object. +* +* @param {Collection} src - input value +* @param {Options} [options] - function options +* @param {NonNegativeInteger} [options.iter] - number of iterations +* @param {integer} [options.dir=1] - iteration direction +* @param {Function} [mapFcn] - function to invoke for each iterated value +* @param {*} [thisArg] - execution context +* @throws {TypeError} first argument must be an array-like object +* @throws {TypeError} options argument must be an object +* @throws {TypeError} must provide valid options +* @throws {TypeError} callback argument must be a function +* @returns {Iterator} iterator +* +* @example +* var iter = circarray2iterator( [ 1, 2, 3, 4 ] ); +* +* var v = iter.next().value; +* // returns 1 +* +* v = iter.next().value; +* // returns 2 +* +* v = iter.next().value; +* // returns 3 +* +* // ... +*/ +function circarray2iterator( src ) { + var thisArg; + var options; + var count; + var opts; + var iter; + var FLG; + var fcn; + var i; + if ( !isCollection( src ) ) { + throw new TypeError( 'invalid argument. First argument must be an array-like object. Value: `' + src + '`.' ); + } + opts = { + 'iter': 1e308, // ~infinity + 'dir': 1 // left to right iteration + }; + if ( arguments.length > 1 ) { + if ( isObject( arguments[ 1 ] ) ) { + options = arguments[ 1 ]; + if ( arguments.length > 2 ) { + fcn = arguments[ 2 ]; + if ( !isFunction( fcn ) ) { + throw new TypeError( 'invalid argument. Callback argument must be a function. Value: `' + fcn + '`.' ); + } + thisArg = arguments[ 3 ]; + } + if ( hasOwnProp( options, 'iter' ) ) { + opts.iter = options.iter; + if ( !isNonNegativeInteger( options.iter ) ) { + throw new TypeError( 'invalid option. `iter` option must be a nonnegative integer. Option: `' + options.iter + '`.' ); + } + } + if ( hasOwnProp( options, 'dir' ) ) { + opts.dir = options.dir; + if ( options.dir !== 1 && options.dir !== -1 ) { + throw new TypeError( 'invalid option. `dir` option must be either `1` or `-1`. Option: `' + options.dir + '`.' ); + } + } + } else { + fcn = arguments[ 1 ]; + if ( !isFunction( fcn ) ) { + throw new TypeError( 'invalid argument. Second argument must be either a function or an options object. Value: `' + fcn + '`.' ); + } + thisArg = arguments[ 2 ]; + } + } + count = 0; + + // Create an iterator protocol-compliant object: + iter = {}; + if ( fcn ) { + if ( opts.dir === 1 ) { + i = -1; + setReadOnly( iter, 'next', next1a ); + } else { + i = src.length; + setReadOnly( iter, 'next', next1b ); + } + } else if ( opts.dir === 1 ) { + i = -1; + setReadOnly( iter, 'next', next2a ); + } else { + i = src.length; + setReadOnly( iter, 'next', next2b ); + } + setReadOnly( iter, 'return', end ); + + // If an environment supports `Symbol.iterator`, make the iterator iterable: + if ( iteratorSymbol ) { + setReadOnly( iter, iteratorSymbol, factory ); + } + return iter; + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next1a() { + i = (i+1) % src.length; + count += 1; + if ( FLG || count > opts.iter || src.length === 0 ) { + return { + 'done': true + }; + } + return { + 'value': fcn.call( thisArg, src[ i ], i, count, src ), + 'done': false + }; + } + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next1b() { + i -= 1; + if ( i < 0 ) { + i += src.length; + } + count += 1; + if ( FLG || count > opts.iter || src.length === 0 ) { + return { + 'done': true + }; + } + return { + 'value': fcn.call( thisArg, src[ i ], i, count, src ), + 'done': false + }; + } + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next2a() { + i = (i+1) % src.length; + count += 1; + if ( FLG || count > opts.iter || src.length === 0 ) { + return { + 'done': true + }; + } + return { + 'value': src[ i ], + 'done': false + }; + } + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next2b() { + i -= 1; + if ( i < 0 ) { + i += src.length; + } + count += 1; + if ( FLG || count > opts.iter || src.length === 0 ) { + return { + 'done': true + }; + } + return { + 'value': src[ i ], + 'done': false + }; + } + + /** + * Finishes an iterator. + * + * @private + * @param {*} [value] - value to return + * @returns {Object} iterator protocol-compliant object + */ + function end( value ) { + FLG = true; + if ( arguments.length ) { + return { + 'value': value, + 'done': true + }; + } + return { + 'done': true + }; + } + + /** + * Returns a new iterator. + * + * @private + * @returns {Iterator} iterator + */ + function factory() { + if ( fcn ) { + return circarray2iterator( src, opts, fcn, thisArg ); + } + return circarray2iterator( src, opts ); + } +} + + +// EXPORTS // + +module.exports = circarray2iterator; diff --git a/to-circular-iterator/package.json b/to-circular-iterator/package.json new file mode 100644 index 00000000..051f67bc --- /dev/null +++ b/to-circular-iterator/package.json @@ -0,0 +1,75 @@ +{ + "name": "@stdlib/array/to-circular-iterator", + "version": "0.0.0", + "description": "Create an iterator which repeatedly iterates over the elements of an array-like object.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "utils", + "util", + "utilities", + "utility", + "typed", + "array", + "arr", + "typed-array", + "typed array", + "iterator", + "iterate", + "iteration", + "iter", + "to", + "convert", + "circular", + "circ", + "infinite", + "loop", + "repeat" + ] +} diff --git a/to-circular-iterator/test/test.js b/to-circular-iterator/test/test.js new file mode 100644 index 00000000..07c6afc2 --- /dev/null +++ b/to-circular-iterator/test/test.js @@ -0,0 +1,1067 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var iteratorSymbol = require( '@stdlib/symbol/iterator' ); +var noop = require( '@stdlib/utils/noop' ); +var circarray2iterator = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.equal( typeof circarray2iterator, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + circarray2iterator( value ); + }; + } +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object (options)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + circarray2iterator( value, {} ); + }; + } +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object (callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + circarray2iterator( value, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a callback argument which is not a function (no options)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + [] + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + circarray2iterator( [ 1, 2, 3, 4 ], value ); + }; + } +}); + +tape( 'the function throws an error if provided a callback argument which is not a function (options)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + [], + {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + circarray2iterator( [ 1, 2, 3, 4 ], {}, value ); + }; + } +}); + +tape( 'the function throws an error if provided an `iter` option which is not a nonnegative integer (no callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + -5, + 3.14, + NaN, + true, + false, + null, + void 0, + [], + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + circarray2iterator( [ 1, 2, 3, 4 ], { + 'iter': value + }); + }; + } +}); + +tape( 'the function throws an error if provided an `iter` option which is not a nonnegative integer (callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + -5, + 3.14, + NaN, + true, + false, + null, + void 0, + [], + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + var opts = { + 'iter': value + }; + circarray2iterator( [ 1, 2, 3, 4 ], opts, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a `dir` option which is neither `1` nor `-1` (no callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + 0, + -5, + NaN, + true, + false, + null, + void 0, + [], + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + circarray2iterator( [ 1, 2, 3, 4 ], { + 'dir': value + }); + }; + } +}); + +tape( 'the function throws an error if provided a `dir` option which is neither `1` nor `-1` (callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + 0, + -5, + NaN, + true, + false, + null, + void 0, + [], + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + var opts = { + 'dir': value + }; + circarray2iterator( [ 1, 2, 3, 4 ], opts, noop ); + }; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which repeatedly iterates over elements of an array-like object (array)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 1, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'value': 1, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + } + ]; + + it = circarray2iterator( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length*2; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object which repeatedly iterates over elements of an array-like object (array; options)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 1, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'value': 1, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + } + ]; + + it = circarray2iterator( values, {} ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length*2; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object which repeatedly iterates over the elements of an array-like object (array-like object)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = { + 'length': 4, + '0': 1, + '1': 2, + '2': 3, + '3': 4 + }; + expected = [ + { + 'value': 1, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'value': 1, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + } + ]; + + it = circarray2iterator( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length*2; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object which repeatedly iterates over elements of an array-like object (empty)', function test( t ) { + var expected; + var actual; + var values; + var it; + + values = []; + expected = [ + { + 'done': true + } + ]; + + it = circarray2iterator( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = [ it.next() ]; + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + + it = circarray2iterator( values, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length, 'has expected length' ); + + r = it.next(); + t.equal( r.done, false, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (array-like)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = { + 'length': 4, + '0': 1, + '1': 2, + '2': 3, + '3': 4 + }; + + it = circarray2iterator( values, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length, 'has expected length' ); + + r = it.next(); + t.equal( r.done, false, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (empty)', function test( t ) { + var expected; + var actual; + var values; + var it; + + values = []; + + it = circarray2iterator( values, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = [ + { + 'done': true + } + ]; + actual = [ it.next() ]; + t.deepEqual( actual, expected, 'returns expected values' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + return v; + } +}); + +tape( 'the function supports limiting the number of iterations', function test( t ) { + var expected; + var actual; + var values; + var opts; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 1, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'value': 1, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'done': true + } + ]; + + opts = { + 'iter': 7 + }; + it = circarray2iterator( values, opts ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < opts.iter; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function supports limiting the number of iterations (callback)', function test( t ) { + var expected; + var actual; + var values; + var opts; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 1, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'value': 9, + 'done': false + }, + { + 'value': 16, + 'done': false + }, + { + 'value': 5, + 'done': false + }, + { + 'value': 12, + 'done': false + }, + { + 'value': 21, + 'done': false + }, + { + 'done': true + } + ]; + + opts = { + 'iter': 7 + }; + it = circarray2iterator( values, opts, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < opts.iter; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); + + function scale( v, i, n ) { + return v * n; + } +}); + +tape( 'the function supports specifying the iteration direction', function test( t ) { + var expected; + var actual; + var values; + var opts; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 4, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 1, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'done': true + } + ]; + + opts = { + 'iter': 7, + 'dir': -1 + }; + it = circarray2iterator( values, opts ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < opts.iter; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function supports specifying the iteration direction (callback)', function test( t ) { + var expected; + var actual; + var values; + var opts; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 4, + 'done': false + }, + { + 'value': 6, + 'done': false + }, + { + 'value': 6, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'value': 20, + 'done': false + }, + { + 'value': 18, + 'done': false + }, + { + 'value': 14, + 'done': false + }, + { + 'done': true + } + ]; + + opts = { + 'iter': 7, + 'dir': -1 + }; + it = circarray2iterator( values, opts, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < opts.iter; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); + + function scale( v, i, n ) { + return v * n; + } +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (no argument)', function test( t ) { + var it; + var r; + + it = circarray2iterator( [ 1, 2, 3, 4 ] ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (no argument; callback)', function test( t ) { + var it; + var r; + + it = circarray2iterator( [ 1, 2, 3, 4 ], scale ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (argument)', function test( t ) { + var it; + var r; + + it = circarray2iterator( [ 1, 2, 3, 4 ] ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return( 'finished' ); + t.equal( r.value, 'finished', 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (argument; callback)', function test( t ) { + var it; + var r; + + it = circarray2iterator( [ 1, 2, 3, 4 ], scale ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return( 'finished' ); + t.equal( r.value, 'finished', 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable', function test( t ) { + var circarray2iterator; + var values; + var it1; + var it2; + var i; + + circarray2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = circarray2iterator( values ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable (callback)', function test( t ) { + var circarray2iterator; + var values; + var it1; + var it2; + var i; + + circarray2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = circarray2iterator( values, scale ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); + + function scale( v ) { + return v * 10.0; + } +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable"', function test( t ) { + var circarray2iterator; + var it; + + circarray2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = circarray2iterator( [ 1, 2, 3, 4 ] ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable" (callback)', function test( t ) { + var circarray2iterator; + var it; + + circarray2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = circarray2iterator( [ 1, 2, 3, 4 ], scale ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); diff --git a/to-iterator-right/README.md b/to-iterator-right/README.md new file mode 100644 index 00000000..80f25a8d --- /dev/null +++ b/to-iterator-right/README.md @@ -0,0 +1,218 @@ + + +# array2iteratorRight + +> Create an iterator from an array-like object, iterating from right to left. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var array2iteratorRight = require( '@stdlib/array/to-iterator-right' ); +``` + +#### array2iteratorRight( src\[, mapFcn\[, thisArg]] ) + +Returns an iterator which iterates from right to left over each element in an array-like `object`. + +```javascript +var it = array2iteratorRight( [ 1, 2, 3, 4 ] ); +// returns + +var v = it.next().value; +// returns 4 + +v = it.next().value; +// returns 3 + +v = it.next().value; +// returns 2 + +// ... +``` + +The returned iterator protocol-compliant object has the following properties: + +- **next**: function which returns an iterator protocol-compliant object containing the next iterated value (if one exists) assigned to a `value` property and a `done` property having a `boolean` value indicating whether the iterator is finished. +- **return**: function which closes an iterator and returns a single (optional) argument in an iterator protocol-compliant object. + +To invoke a function for each `src` value, provide a callback function. + +```javascript +function fcn( v ) { + return v * 10.0; +} + +var it = array2iteratorRight( [ 1, 2, 3, 4 ], fcn ); +// returns + +var v = it.next().value; +// returns 40.0 + +v = it.next().value; +// returns 30.0 + +v = it.next().value; +// returns 20.0 + +// ... +``` + +The invoked function is provided three arguments: + +- `value`: iterated value +- `index`: iterated value index +- `src`: source array-like object + +```javascript +function fcn( v, i ) { + return v * (i+1); +} + +var it = array2iteratorRight( [ 1, 2, 3, 4 ], fcn ); +// returns + +var v = it.next().value; +// returns 16 + +v = it.next().value; +// returns 9 + +v = it.next().value; +// returns 4 + +// ... +``` + +To set the callback function execution context, provide a `thisArg`. + +```javascript +function fcn( v ) { + this.count += 1; + return v * 10.0; +} + +var ctx = { + 'count': 0 +}; + +var it = array2iteratorRight( [ 1, 2, 3, 4 ], fcn, ctx ); +// returns + +var v = it.next().value; +// returns 40.0 + +v = it.next().value; +// returns 30.0 + +v = it.next().value; +// returns 20.0 + +var count = ctx.count; +// returns 3 +``` + + + + + + + +
+ +## Notes + +- If an environment supports `Symbol.iterator`, the returned iterator is iterable. +- If provided a generic `array`, the returned iterator does **not** ignore holes. To achieve greater performance for sparse arrays, use [`@stdlib/array/to-sparse-iterator-right`][@stdlib/array/to-sparse-iterator-right]. +- A returned iterator does **not** copy a provided array-like `object`. To ensure iterable reproducibility, copy a provided array-like `object` **before** creating an iterator. Otherwise, any changes to the contents of an array-like `object` will be reflected in the returned iterator. +- In environments supporting `Symbol.iterator`, the function **explicitly** does **not** invoke an array's `@@iterator` method, regardless of whether this method is defined. To convert an array to an implementation defined iterator, invoke this method directly. + +
+ + + + + +
+ +## Examples + + + +```javascript +var Float64Array = require( '@stdlib/array/float64' ); +var inmap = require( '@stdlib/utils/inmap' ); +var randu = require( '@stdlib/random/base/randu' ); +var array2iteratorRight = require( '@stdlib/array/to-iterator-right' ); + +function scale( v, i ) { + return v * (i+1); +} + +// Create an array filled with random numbers: +var arr = inmap( new Float64Array( 100 ), randu ); + +// Create an iterator from the array which scales iterated values: +var it = array2iteratorRight( arr, scale ); + +// Perform manual iteration... +var v; +while ( true ) { + v = it.next(); + if ( v.done ) { + break; + } + console.log( v.value ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/to-iterator-right/benchmark/benchmark.js b/to-iterator-right/benchmark/benchmark.js new file mode 100644 index 00000000..43f2ca35 --- /dev/null +++ b/to-iterator-right/benchmark/benchmark.js @@ -0,0 +1,109 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isnan = require( '@stdlib/math/base/assert/is-nan' ); +var isIteratorLike = require( '@stdlib/assert/is-iterator-like' ); +var pkg = require( './../package.json' ).name; +var array2iteratorRight = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var values; + var iter; + var i; + + values = [ 1, 2, 3, 4 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + values[ 0 ] = i; + iter = array2iteratorRight( values ); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isIteratorLike( iter ) ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::iteration', function benchmark( b ) { + var values; + var iter; + var z; + var i; + + values = []; + values.length = b.iterations; + + iter = array2iteratorRight( values ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + z = iter.next().value; + if ( z !== void 0 ) { + b.fail( 'should be undefined' ); + } + } + b.toc(); + if ( z !== void 0 ) { + b.fail( 'should be undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::iteration,map', function benchmark( b ) { + var values; + var iter; + var z; + var i; + + values = []; + values.length = b.iterations; + + iter = array2iteratorRight( values, transform ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + z = iter.next().value; + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function transform( v, i ) { + return i; + } +}); diff --git a/to-iterator-right/docs/repl.txt b/to-iterator-right/docs/repl.txt new file mode 100644 index 00000000..e0d1f198 --- /dev/null +++ b/to-iterator-right/docs/repl.txt @@ -0,0 +1,54 @@ + +{{alias}}( src[, mapFcn[, thisArg]] ) + Returns an iterator which iterates from right to left over the elements of + an array-like object. + + When invoked, an input function is provided three arguments: + + - value: iterated value + - index: iterated value index + - src: source array-like object + + If an environment supports Symbol.iterator, the returned iterator is + iterable. + + If an environment supports Symbol.iterator, the function explicitly does not + not invoke an array's `@@iterator` method, regardless of whether this method + is defined. To convert an array to an implementation defined iterator, + invoke this method directly. + + Parameters + ---------- + src: ArrayLikeObject + Array-like object from which to create the iterator. + + mapFcn: Function (optional) + Function to invoke for each iterated value. + + thisArg: any (optional) + Execution context. + + Returns + ------- + iterator: Object + Iterator. + + iterator.next(): Function + Returns an iterator protocol-compliant object containing the next + iterated value (if one exists) and a boolean flag indicating whether the + iterator is finished. + + iterator.return( [value] ): Function + Finishes an iterator and returns a provided value. + + Examples + -------- + > var it = {{alias}}( [ 1, 2, 3, 4 ] ); + > var v = it.next().value + 4 + > v = it.next().value + 3 + + See Also + -------- + diff --git a/to-iterator-right/docs/types/index.d.ts b/to-iterator-right/docs/types/index.d.ts new file mode 100644 index 00000000..a8047d7d --- /dev/null +++ b/to-iterator-right/docs/types/index.d.ts @@ -0,0 +1,104 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/// + +import { Iterator as Iter, IterableIterator } from '@stdlib/types/iter'; +import { ArrayLike } from '@stdlib/types/array'; + +// Define a union type representing both iterable and non-iterable iterators: +type Iterator = Iter | IterableIterator; + +/** +* Map function invoked for each iterated value. +* +* @returns iterator value +*/ +type Nullary = () => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @returns iterator value +*/ +type Unary = ( value: any ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @returns iterator value +*/ +type Binary = ( value: any, index: number ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @param src - source array-like object +* @returns iterator value +*/ +type Tertiary = ( value: any, index: number, src: ArrayLike ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @param src - source array-like object +* @returns iterator value +*/ +type MapFunction = Nullary | Unary | Binary | Tertiary; + +/** +* Returns an iterator which iterates from right to left over each element in an array-like object. +* +* ## Notes +* +* - For dynamic array resizing, the only behavior made intentionally consistent with iterating from left to right is when elements are pushed onto the beginning (end) of an array. In other words, iterating from left to right combined with `[].push()` is consistent with iterating from right to left combined with `[].unshift()`. +* +* @param src - input value +* @param mapFcn - function to invoke for each iterated value +* @param thisArg - execution context +* @returns iterator +* +* @example +* var iter = array2iteratorRight( [ 1, 2, 3, 4 ] ); +* +* var v = iter.next().value; +* // returns 4 +* +* v = iter.next().value; +* // returns 3 +* +* v = iter.next().value; +* // returns 2 +* +* // ... +*/ +declare function array2iteratorRight( src: ArrayLike, mapFcn?: MapFunction, thisArg?: any ): Iterator; // tslint:disable-line:max-line-length + + +// EXPORTS // + +export = array2iteratorRight; diff --git a/to-iterator-right/docs/types/test.ts b/to-iterator-right/docs/types/test.ts new file mode 100644 index 00000000..a1fa0cf7 --- /dev/null +++ b/to-iterator-right/docs/types/test.ts @@ -0,0 +1,66 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import array2iteratorRight = require( './index' ); + +/** +* Multiplies a value by 10. +* +* @param v - iterated value +* @returns new value +*/ +function times10( v: number ): number { + return v * 10.0; +} + + +// TESTS // + +// The function returns an iterator... +{ + array2iteratorRight( [ 1, 2, 3, 4 ] ); // $ExpectType Iterator + array2iteratorRight( [ 1, 2, 3, 4 ], times10 ); // $ExpectType Iterator + array2iteratorRight( [ 1, 2, 3, 4 ], times10, {} ); // $ExpectType Iterator +} + +// The compiler throws an error if the function is provided a first argument which is not array-like... +{ + array2iteratorRight( 123 ); // $ExpectError + array2iteratorRight( true ); // $ExpectError + array2iteratorRight( false ); // $ExpectError + array2iteratorRight( {} ); // $ExpectError + array2iteratorRight( null ); // $ExpectError + array2iteratorRight( undefined ); // $ExpectError +} + +// The compiler throws an error if the function is provided a second argument which is not a map function... +{ + array2iteratorRight( [ 1, 2, 3, 4 ], 'abc' ); // $ExpectError + array2iteratorRight( [ 1, 2, 3, 4 ], 123 ); // $ExpectError + array2iteratorRight( [ 1, 2, 3, 4 ], [] ); // $ExpectError + array2iteratorRight( [ 1, 2, 3, 4 ], {} ); // $ExpectError + array2iteratorRight( [ 1, 2, 3, 4 ], true ); // $ExpectError + array2iteratorRight( [ 1, 2, 3, 4 ], false ); // $ExpectError + array2iteratorRight( [ 1, 2, 3, 4 ], null ); // $ExpectError +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + array2iteratorRight(); // $ExpectError + array2iteratorRight( [ 1, 2, 3, 4 ], times10, {}, 123 ); // $ExpectError +} diff --git a/to-iterator-right/examples/index.js b/to-iterator-right/examples/index.js new file mode 100644 index 00000000..546435ea --- /dev/null +++ b/to-iterator-right/examples/index.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var Float64Array = require( '@stdlib/array/float64' ); +var inmap = require( '@stdlib/utils/inmap' ); +var randu = require( '@stdlib/random/base/randu' ); +var array2iteratorRight = require( './../lib' ); + +function scale( v, i ) { + return v * (i+1); +} + +// Create an array filled with random numbers: +var arr = inmap( new Float64Array( 100 ), randu ); + +// Create an iterator from the array which scales iterated values: +var it = array2iteratorRight( arr, scale ); + +// Perform manual iteration... +var v; +while ( true ) { + v = it.next(); + if ( v.done ) { + break; + } + console.log( v.value ); +} diff --git a/to-iterator-right/lib/index.js b/to-iterator-right/lib/index.js new file mode 100644 index 00000000..e03f558c --- /dev/null +++ b/to-iterator-right/lib/index.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Create an iterator from an array-like object, iterating from right to left. +* +* @module @stdlib/array/to-iterator-right +* +* @example +* var array2iteratorRight = require( '@stdlib/array/to-iterator-right' ); +* +* var iter = array2iteratorRight( [ 1, 2, 3, 4 ] ); +* +* var v = iter.next().value; +* // returns 4 +* +* v = iter.next().value; +* // returns 3 +* +* v = iter.next().value; +* // returns 2 +* +* // ... +*/ + +// MODULES // + +var iterator = require( './main.js' ); + + +// EXPORTS // + +module.exports = iterator; diff --git a/to-iterator-right/lib/main.js b/to-iterator-right/lib/main.js new file mode 100644 index 00000000..6f87a3fa --- /dev/null +++ b/to-iterator-right/lib/main.js @@ -0,0 +1,173 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var isCollection = require( '@stdlib/assert/is-collection' ); +var iteratorSymbol = require( '@stdlib/symbol/iterator' ); + + +// MAIN // + +/** +* Returns an iterator which iterates from right to left over each element in an array-like object. +* +* ## Notes +* +* - For dynamic array resizing, the only behavior made intentionally consistent with iterating from left to right is when elements are pushed onto the beginning (end) of an array. In other words, iterating from left to right combined with `[].push()` is consistent with iterating from right to left combined with `[].unshift()`. +* +* @param {Collection} src - input value +* @param {Function} [mapFcn] - function to invoke for each iterated value +* @param {*} [thisArg] - execution context +* @throws {TypeError} first argument must be an array-like object +* @throws {TypeError} second argument must be a function +* @returns {Iterator} iterator +* +* @example +* var iter = array2iteratorRight( [ 1, 2, 3, 4 ] ); +* +* var v = iter.next().value; +* // returns 4 +* +* v = iter.next().value; +* // returns 3 +* +* v = iter.next().value; +* // returns 2 +* +* // ... +*/ +function array2iteratorRight( src ) { + var thisArg; + var iter; + var FLG; + var fcn; + var len; + var i; + if ( !isCollection( src ) ) { + throw new TypeError( 'invalid argument. First argument must be an array-like object. Value: `' + src + '`.' ); + } + if ( arguments.length > 1 ) { + fcn = arguments[ 1 ]; + if ( !isFunction( fcn ) ) { + throw new TypeError( 'invalid argument. Second argument must be a function. Value: `' + fcn + '`.' ); + } + thisArg = arguments[ 2 ]; + } + len = src.length; + i = len; + + // Create an iterator protocol-compliant object: + iter = {}; + if ( fcn ) { + setReadOnly( iter, 'next', next1 ); + } else { + setReadOnly( iter, 'next', next2 ); + } + setReadOnly( iter, 'return', end ); + + // If an environment supports `Symbol.iterator`, make the iterator iterable: + if ( iteratorSymbol ) { + setReadOnly( iter, iteratorSymbol, factory ); + } + return iter; + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next1() { + i += src.length - len - 1; // accounts for a dynamic array + len = src.length; + if ( FLG || i < 0 ) { + FLG = true; + return { + 'done': true + }; + } + return { + 'value': fcn.call( thisArg, src[ i ], i, src ), + 'done': false + }; + } + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next2() { + i += src.length - len - 1; // accounts for a dynamic array + len = src.length; + if ( FLG || i < 0 ) { + FLG = true; + return { + 'done': true + }; + } + return { + 'value': src[ i ], + 'done': false + }; + } + + /** + * Finishes an iterator. + * + * @private + * @param {*} [value] - value to return + * @returns {Object} iterator protocol-compliant object + */ + function end( value ) { + FLG = true; + if ( arguments.length ) { + return { + 'value': value, + 'done': true + }; + } + return { + 'done': true + }; + } + + /** + * Returns a new iterator. + * + * @private + * @returns {Iterator} iterator + */ + function factory() { + if ( fcn ) { + return array2iteratorRight( src, fcn, thisArg ); + } + return array2iteratorRight( src ); + } +} + + +// EXPORTS // + +module.exports = array2iteratorRight; diff --git a/to-iterator-right/package.json b/to-iterator-right/package.json new file mode 100644 index 00000000..b869dd85 --- /dev/null +++ b/to-iterator-right/package.json @@ -0,0 +1,70 @@ +{ + "name": "@stdlib/array/to-iterator-right", + "version": "0.0.0", + "description": "Create an iterator from an array-like object, iterating from right to left.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "utils", + "util", + "utilities", + "utility", + "typed", + "array", + "arr", + "typed-array", + "typed array", + "iterator", + "iterate", + "iteration", + "iter", + "to", + "convert" + ] +} diff --git a/to-iterator-right/test/test.js b/to-iterator-right/test/test.js new file mode 100644 index 00000000..e764c0a5 --- /dev/null +++ b/to-iterator-right/test/test.js @@ -0,0 +1,492 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var iteratorSymbol = require( '@stdlib/symbol/iterator' ); +var noop = require( '@stdlib/utils/noop' ); +var array2iteratorRight = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.equal( typeof array2iteratorRight, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + array2iteratorRight( value ); + }; + } +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object (callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + array2iteratorRight( value, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a second argument which is not a function', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + [], + {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + array2iteratorRight( [ 1, 2, 3, 4 ], value ); + }; + } +}); + +tape( 'the function returns an iterator protocol-compliant object, iterating from right to left', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 4, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 1, + 'done': false + }, + { + 'done': true + } + ]; + + it = array2iteratorRight( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object, iterating from right to left (array-like object)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = { + 'length': 4, + '0': 1, + '1': 2, + '2': 3, + '3': 4 + }; + expected = [ + { + 'value': 4, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 1, + 'done': false + }, + { + 'done': true + } + ]; + + it = array2iteratorRight( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + + it = array2iteratorRight( values, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (array-like)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = { + 'length': 4, + '0': 1, + '1': 2, + '2': 3, + '3': 4 + }; + + it = array2iteratorRight( values, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (no argument)', function test( t ) { + var it; + var r; + + it = array2iteratorRight( [ 1, 2, 3, 4 ] ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (no argument; callback)', function test( t ) { + var it; + var r; + + it = array2iteratorRight( [ 1, 2, 3, 4 ], scale ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (argument)', function test( t ) { + var it; + var r; + + it = array2iteratorRight( [ 1, 2, 3, 4 ] ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return( 'finished' ); + t.equal( r.value, 'finished', 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (argument; callback)', function test( t ) { + var it; + var r; + + it = array2iteratorRight( [ 1, 2, 3, 4 ], scale ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return( 'finished' ); + t.equal( r.value, 'finished', 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable', function test( t ) { + var array2iteratorRight; + var values; + var it1; + var it2; + var i; + + array2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = array2iteratorRight( values ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable (callback)', function test( t ) { + var array2iteratorRight; + var values; + var it1; + var it2; + var i; + + array2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = array2iteratorRight( values, scale ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); + + function scale( v ) { + return v * 10.0; + } +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable"', function test( t ) { + var array2iteratorRight; + var it; + + array2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = array2iteratorRight( [ 1, 2, 3, 4 ] ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable" (callback)', function test( t ) { + var array2iteratorRight; + var it; + + array2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = array2iteratorRight( [ 1, 2, 3, 4 ], scale ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); diff --git a/to-iterator/README.md b/to-iterator/README.md new file mode 100644 index 00000000..fe8c9e05 --- /dev/null +++ b/to-iterator/README.md @@ -0,0 +1,218 @@ + + +# array2iterator + +> Create an iterator from an array-like object. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var array2iterator = require( '@stdlib/array/to-iterator' ); +``` + +#### array2iterator( src\[, mapFcn\[, thisArg]] ) + +Returns an iterator which iterates over each element in an array-like `object`. + +```javascript +var it = array2iterator( [ 1, 2, 3, 4 ] ); +// returns + +var v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 2 + +v = it.next().value; +// returns 3 + +// ... +``` + +The returned iterator protocol-compliant object has the following properties: + +- **next**: function which returns an iterator protocol-compliant object containing the next iterated value (if one exists) assigned to a `value` property and a `done` property having a `boolean` value indicating whether the iterator is finished. +- **return**: function which closes an iterator and returns a single (optional) argument in an iterator protocol-compliant object. + +To invoke a function for each `src` value, provide a callback function. + +```javascript +function fcn( v ) { + return v * 10.0; +} + +var it = array2iterator( [ 1, 2, 3, 4 ], fcn ); +// returns + +var v = it.next().value; +// returns 10.0 + +v = it.next().value; +// returns 20.0 + +v = it.next().value; +// returns 30.0 + +// ... +``` + +The invoked function is provided three arguments: + +- `value`: iterated value +- `index`: iterated value index +- `src`: source array-like object + +```javascript +function fcn( v, i ) { + return v * (i+1); +} + +var it = array2iterator( [ 1, 2, 3, 4 ], fcn ); +// returns + +var v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 4 + +v = it.next().value; +// returns 9 + +// ... +``` + +To set the callback function execution context, provide a `thisArg`. + +```javascript +function fcn( v ) { + this.count += 1; + return v * 10.0; +} + +var ctx = { + 'count': 0 +}; + +var it = array2iterator( [ 1, 2, 3, 4 ], fcn, ctx ); +// returns + +var v = it.next().value; +// returns 10.0 + +v = it.next().value; +// returns 20.0 + +v = it.next().value; +// returns 30.0 + +var count = ctx.count; +// returns 3 +``` + + + + + + + +
+ +## Notes + +- If an environment supports `Symbol.iterator`, the returned iterator is iterable. +- If provided a generic `array`, the returned iterator does **not** ignore holes. To achieve greater performance for sparse arrays, use [`@stdlib/array/to-sparse-iterator`][@stdlib/array/to-sparse-iterator]. +- A returned iterator does **not** copy a provided array-like `object`. To ensure iterable reproducibility, copy a provided array-like `object` **before** creating an iterator. Otherwise, any changes to the contents of an array-like `object` will be reflected in the returned iterator. +- In environments supporting `Symbol.iterator`, the function **explicitly** does **not** invoke an array's `@@iterator` method, regardless of whether this method is defined. To convert an array to an implementation defined iterator, invoke this method directly. + +
+ + + + + +
+ +## Examples + + + +```javascript +var Float64Array = require( '@stdlib/array/float64' ); +var inmap = require( '@stdlib/utils/inmap' ); +var randu = require( '@stdlib/random/base/randu' ); +var array2iterator = require( '@stdlib/array/to-iterator' ); + +function scale( v, i ) { + return v * (i+1); +} + +// Create an array filled with random numbers: +var arr = inmap( new Float64Array( 100 ), randu ); + +// Create an iterator from the array which scales iterated values: +var it = array2iterator( arr, scale ); + +// Perform manual iteration... +var v; +while ( true ) { + v = it.next(); + if ( v.done ) { + break; + } + console.log( v.value ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/to-iterator/benchmark/benchmark.js b/to-iterator/benchmark/benchmark.js new file mode 100644 index 00000000..e59e77b1 --- /dev/null +++ b/to-iterator/benchmark/benchmark.js @@ -0,0 +1,109 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isnan = require( '@stdlib/math/base/assert/is-nan' ); +var isIteratorLike = require( '@stdlib/assert/is-iterator-like' ); +var pkg = require( './../package.json' ).name; +var array2iterator = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var values; + var iter; + var i; + + values = [ 1, 2, 3, 4 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + values[ 0 ] = i; + iter = array2iterator( values ); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isIteratorLike( iter ) ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::iteration', function benchmark( b ) { + var values; + var iter; + var z; + var i; + + values = []; + values.length = b.iterations; + + iter = array2iterator( values ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + z = iter.next().value; + if ( z !== void 0 ) { + b.fail( 'should be undefined' ); + } + } + b.toc(); + if ( z !== void 0 ) { + b.fail( 'should be undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::iteration,map', function benchmark( b ) { + var values; + var iter; + var z; + var i; + + values = []; + values.length = b.iterations; + + iter = array2iterator( values, transform ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + z = iter.next().value; + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function transform( v, i ) { + return i; + } +}); diff --git a/to-iterator/docs/repl.txt b/to-iterator/docs/repl.txt new file mode 100644 index 00000000..cbea1f5f --- /dev/null +++ b/to-iterator/docs/repl.txt @@ -0,0 +1,54 @@ + +{{alias}}( src[, mapFcn[, thisArg]] ) + Returns an iterator which iterates over the elements of an array-like + object. + + When invoked, an input function is provided three arguments: + + - value: iterated value + - index: iterated value index + - src: source array-like object + + If an environment supports Symbol.iterator, the returned iterator is + iterable. + + If an environment supports Symbol.iterator, the function explicitly does not + not invoke an array's `@@iterator` method, regardless of whether this method + is defined. To convert an array to an implementation defined iterator, + invoke this method directly. + + Parameters + ---------- + src: ArrayLikeObject + Array-like object from which to create the iterator. + + mapFcn: Function (optional) + Function to invoke for each iterated value. + + thisArg: any (optional) + Execution context. + + Returns + ------- + iterator: Object + Iterator. + + iterator.next(): Function + Returns an iterator protocol-compliant object containing the next + iterated value (if one exists) and a boolean flag indicating whether the + iterator is finished. + + iterator.return( [value] ): Function + Finishes an iterator and returns a provided value. + + Examples + -------- + > var it = {{alias}}( [ 1, 2, 3, 4 ] ); + > var v = it.next().value + 1 + > v = it.next().value + 2 + + See Also + -------- + diff --git a/to-iterator/docs/types/index.d.ts b/to-iterator/docs/types/index.d.ts new file mode 100644 index 00000000..60c101f9 --- /dev/null +++ b/to-iterator/docs/types/index.d.ts @@ -0,0 +1,100 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/// + +import { Iterator as Iter, IterableIterator } from '@stdlib/types/iter'; +import { ArrayLike } from '@stdlib/types/array'; + +// Define a union type representing both iterable and non-iterable iterators: +type Iterator = Iter | IterableIterator; + +/** +* Map function invoked for each iterated value. +* +* @returns iterator value +*/ +type Nullary = () => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @returns iterator value +*/ +type Unary = ( value: any ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @returns iterator value +*/ +type Binary = ( value: any, index: number ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @param src - source array-like object +* @returns iterator value +*/ +type Tertiary = ( value: any, index: number, src: ArrayLike ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @param src - source array-like object +* @returns iterator value +*/ +type MapFunction = Nullary | Unary | Binary | Tertiary; + +/** +* Returns an iterator which iterates over each element in an array-like object. +* +* @param src - input value +* @param mapFc - function to invoke for each iterated value +* @param thisArg - execution context +* @returns iterator +* +* @example +* var iter = array2iterator( [ 1, 2, 3, 4 ] ); +* +* var v = iter.next().value; +* // returns 1 +* +* v = iter.next().value; +* // returns 2 +* +* v = iter.next().value; +* // returns 3 +* +* // ... +*/ +declare function array2iterator( src: ArrayLike, mapFcn?: MapFunction, thisArg?: any ): Iterator; // tslint:disable-line:max-line-length + + +// EXPORTS // + +export = array2iterator; diff --git a/to-iterator/docs/types/test.ts b/to-iterator/docs/types/test.ts new file mode 100644 index 00000000..561feb71 --- /dev/null +++ b/to-iterator/docs/types/test.ts @@ -0,0 +1,66 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import array2iterator = require( './index' ); + +/** +* Multiplies a value by 10. +* +* @param v - iterated value +* @returns new value +*/ +function times10( v: number ): number { + return v * 10.0; +} + + +// TESTS // + +// The function returns an iterator... +{ + array2iterator( [ 1, 2, 3, 4 ] ); // $ExpectType Iterator + array2iterator( [ 1, 2, 3, 4 ], times10 ); // $ExpectType Iterator + array2iterator( [ 1, 2, 3, 4 ], times10, {} ); // $ExpectType Iterator +} + +// The compiler throws an error if the function is provided a first argument which is not array-like... +{ + array2iterator( 123 ); // $ExpectError + array2iterator( true ); // $ExpectError + array2iterator( false ); // $ExpectError + array2iterator( {} ); // $ExpectError + array2iterator( null ); // $ExpectError + array2iterator( undefined ); // $ExpectError +} + +// The compiler throws an error if the function is provided a second argument which is not a map function... +{ + array2iterator( [ 1, 2, 3, 4 ], 'abc' ); // $ExpectError + array2iterator( [ 1, 2, 3, 4 ], 123 ); // $ExpectError + array2iterator( [ 1, 2, 3, 4 ], [] ); // $ExpectError + array2iterator( [ 1, 2, 3, 4 ], {} ); // $ExpectError + array2iterator( [ 1, 2, 3, 4 ], true ); // $ExpectError + array2iterator( [ 1, 2, 3, 4 ], false ); // $ExpectError + array2iterator( [ 1, 2, 3, 4 ], null ); // $ExpectError +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + array2iterator(); // $ExpectError + array2iterator( [ 1, 2, 3, 4 ], times10, {}, 123 ); // $ExpectError +} diff --git a/to-iterator/examples/index.js b/to-iterator/examples/index.js new file mode 100644 index 00000000..5d7a511c --- /dev/null +++ b/to-iterator/examples/index.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var Float64Array = require( '@stdlib/array/float64' ); +var inmap = require( '@stdlib/utils/inmap' ); +var randu = require( '@stdlib/random/base/randu' ); +var array2iterator = require( './../lib' ); + +function scale( v, i ) { + return v * (i+1); +} + +// Create an array filled with random numbers: +var arr = inmap( new Float64Array( 100 ), randu ); + +// Create an iterator from the array which scales iterated values: +var it = array2iterator( arr, scale ); + +// Perform manual iteration... +var v; +while ( true ) { + v = it.next(); + if ( v.done ) { + break; + } + console.log( v.value ); +} diff --git a/to-iterator/lib/index.js b/to-iterator/lib/index.js new file mode 100644 index 00000000..cf927c72 --- /dev/null +++ b/to-iterator/lib/index.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Create an iterator from an array-like object. +* +* @module @stdlib/array/to-iterator +* +* @example +* var array2iterator = require( '@stdlib/array/to-iterator' ); +* +* var iter = array2iterator( [ 1, 2, 3, 4 ] ); +* +* var v = iter.next().value; +* // returns 1 +* +* v = iter.next().value; +* // returns 2 +* +* v = iter.next().value; +* // returns 3 +* +* // ... +*/ + +// MODULES // + +var iterator = require( './main.js' ); + + +// EXPORTS // + +module.exports = iterator; diff --git a/to-iterator/lib/main.js b/to-iterator/lib/main.js new file mode 100644 index 00000000..62fef648 --- /dev/null +++ b/to-iterator/lib/main.js @@ -0,0 +1,163 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var isCollection = require( '@stdlib/assert/is-collection' ); +var iteratorSymbol = require( '@stdlib/symbol/iterator' ); + + +// MAIN // + +/** +* Returns an iterator which iterates over each element in an array-like object. +* +* @param {Collection} src - input value +* @param {Function} [mapFcn] - function to invoke for each iterated value +* @param {*} [thisArg] - execution context +* @throws {TypeError} first argument must be an array-like object +* @throws {TypeError} second argument must be a function +* @returns {Iterator} iterator +* +* @example +* var iter = array2iterator( [ 1, 2, 3, 4 ] ); +* +* var v = iter.next().value; +* // returns 1 +* +* v = iter.next().value; +* // returns 2 +* +* v = iter.next().value; +* // returns 3 +* +* // ... +*/ +function array2iterator( src ) { + var thisArg; + var iter; + var FLG; + var fcn; + var i; + if ( !isCollection( src ) ) { + throw new TypeError( 'invalid argument. First argument must be an array-like object. Value: `' + src + '`.' ); + } + if ( arguments.length > 1 ) { + fcn = arguments[ 1 ]; + if ( !isFunction( fcn ) ) { + throw new TypeError( 'invalid argument. Second argument must be a function. Value: `' + fcn + '`.' ); + } + thisArg = arguments[ 2 ]; + } + i = -1; + + // Create an iterator protocol-compliant object: + iter = {}; + if ( fcn ) { + setReadOnly( iter, 'next', next1 ); + } else { + setReadOnly( iter, 'next', next2 ); + } + setReadOnly( iter, 'return', end ); + + // If an environment supports `Symbol.iterator`, make the iterator iterable: + if ( iteratorSymbol ) { + setReadOnly( iter, iteratorSymbol, factory ); + } + return iter; + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next1() { + i += 1; + if ( FLG || i >= src.length ) { + return { + 'done': true + }; + } + return { + 'value': fcn.call( thisArg, src[ i ], i, src ), + 'done': false + }; + } + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next2() { + i += 1; + if ( FLG || i >= src.length ) { + return { + 'done': true + }; + } + return { + 'value': src[ i ], + 'done': false + }; + } + + /** + * Finishes an iterator. + * + * @private + * @param {*} [value] - value to return + * @returns {Object} iterator protocol-compliant object + */ + function end( value ) { + FLG = true; + if ( arguments.length ) { + return { + 'value': value, + 'done': true + }; + } + return { + 'done': true + }; + } + + /** + * Returns a new iterator. + * + * @private + * @returns {Iterator} iterator + */ + function factory() { + if ( fcn ) { + return array2iterator( src, fcn, thisArg ); + } + return array2iterator( src ); + } +} + + +// EXPORTS // + +module.exports = array2iterator; diff --git a/to-iterator/package.json b/to-iterator/package.json new file mode 100644 index 00000000..b2b4d6a7 --- /dev/null +++ b/to-iterator/package.json @@ -0,0 +1,70 @@ +{ + "name": "@stdlib/array/to-iterator", + "version": "0.0.0", + "description": "Create an iterator from an array-like object.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "utils", + "util", + "utilities", + "utility", + "typed", + "array", + "arr", + "typed-array", + "typed array", + "iterator", + "iterate", + "iteration", + "iter", + "to", + "convert" + ] +} diff --git a/to-iterator/test/test.js b/to-iterator/test/test.js new file mode 100644 index 00000000..e1c57eb0 --- /dev/null +++ b/to-iterator/test/test.js @@ -0,0 +1,492 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var iteratorSymbol = require( '@stdlib/symbol/iterator' ); +var noop = require( '@stdlib/utils/noop' ); +var array2iterator = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.equal( typeof array2iterator, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + array2iterator( value ); + }; + } +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object (callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + array2iterator( value, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a second argument which is not a function', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + [], + {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + array2iterator( [ 1, 2, 3, 4 ], value ); + }; + } +}); + +tape( 'the function returns an iterator protocol-compliant object', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 1, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'done': true + } + ]; + + it = array2iterator( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (array-like object)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = { + 'length': 4, + '0': 1, + '1': 2, + '2': 3, + '3': 4 + }; + expected = [ + { + 'value': 1, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'done': true + } + ]; + + it = array2iterator( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + + it = array2iterator( values, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (array-like)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = { + 'length': 4, + '0': 1, + '1': 2, + '2': 3, + '3': 4 + }; + + it = array2iterator( values, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (no argument)', function test( t ) { + var it; + var r; + + it = array2iterator( [ 1, 2, 3, 4 ] ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (no argument; callback)', function test( t ) { + var it; + var r; + + it = array2iterator( [ 1, 2, 3, 4 ], scale ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (argument)', function test( t ) { + var it; + var r; + + it = array2iterator( [ 1, 2, 3, 4 ] ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return( 'finished' ); + t.equal( r.value, 'finished', 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (argument; callback)', function test( t ) { + var it; + var r; + + it = array2iterator( [ 1, 2, 3, 4 ], scale ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return( 'finished' ); + t.equal( r.value, 'finished', 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable', function test( t ) { + var array2iterator; + var values; + var it1; + var it2; + var i; + + array2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = array2iterator( values ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable (callback)', function test( t ) { + var array2iterator; + var values; + var it1; + var it2; + var i; + + array2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = array2iterator( values, scale ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); + + function scale( v ) { + return v * 10.0; + } +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable"', function test( t ) { + var array2iterator; + var it; + + array2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = array2iterator( [ 1, 2, 3, 4 ] ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable" (callback)', function test( t ) { + var array2iterator; + var it; + + array2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = array2iterator( [ 1, 2, 3, 4 ], scale ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); diff --git a/to-json/README.md b/to-json/README.md new file mode 100644 index 00000000..e1775f6d --- /dev/null +++ b/to-json/README.md @@ -0,0 +1,253 @@ + + +# toJSON + +> Return a [JSON][json] representation of a typed array. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var toJSON = require( '@stdlib/array/to-json' ); +``` + +#### toJSON( typedarray ) + +Returns a [JSON][json] representation of a typed array. + +```javascript +var Float64Array = require( '@stdlib/array/float64' ); + +var arr = new Float64Array( [ 5.0, 3.0 ] ); + +var json = toJSON( arr ); +/* returns + { + 'type': 'Float64Array', + 'data': [ 5.0, 3.0 ] + } +*/ +``` + +For guidance on reviving a JSON-serialized typed array, see [`reviver()`][@stdlib/array/reviver]. + +
+ + + + + +
+ +## Notes + +- Supported typed array types: + + - [`Float64Array`][@stdlib/array/float64] + - [`Float32Array`][@stdlib/array/float32] + - [`Int32Array`][@stdlib/array/int32] + - [`Uint32Array`][@stdlib/array/uint32] + - [`Int16Array`][@stdlib/array/int16] + - [`Uint16Array`][@stdlib/array/uint16] + - [`Int8Array`][@stdlib/array/int8] + - [`Uint8Array`][@stdlib/array/uint8] + - [`Uint8ClampedArray`][@stdlib/array/uint8c] + +- The implementation provides basic support for custom typed arrays and sets the `type` field to the closest known typed array type. + + + + ```javascript + class CustomArray extends Float64Array() { + constructor( data ) { + super( data ); + } + } + + var arr = new CustomArray( [ 5.0, 3.0 ] ); + + var json = toJSON( arr ); + /* returns + { + 'type': 'Float64Array', + 'data': [ 5.0, 3.0 ] + } + */ + ``` + +
+ + + + + +
+ +## Examples + + + +```javascript +var Float64Array = require( '@stdlib/array/float64' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Int8Array = require( '@stdlib/array/int8' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); +var toJSON = require( '@stdlib/array/to-json' ); + +var arr = new Float64Array( [ 5.0, 3.0 ] ); +var json = toJSON( arr ); +/* returns + { + 'type': 'Float64Array', + 'data': [ 5.0, 3.0 ] + } +*/ + +arr = new Float32Array( [ 5.0, -3.0 ] ); +json = toJSON( arr ); +/* returns + { + 'type': 'Float32Array', + 'data': [ 5.0, -3.0 ] + } +*/ + +arr = new Int32Array( [ -5, 3 ] ); +json = toJSON( arr ); +/* returns + { + 'type': 'Int32Array', + 'data': [ -5, 3 ] + } +*/ + +arr = new Uint32Array( [ 5, 3 ] ); +json = toJSON( arr ); +/* returns + { + 'type': 'Uint32Array', + 'data': [ 5, 3 ] + } +*/ + +arr = new Int16Array( [ -5, 3 ] ); +json = toJSON( arr ); +/* returns + { + 'type': 'Int16Array', + 'data': [ -5, 3 ] + } +*/ + +arr = new Uint16Array( [ 5, 3 ] ); +json = toJSON( arr ); +/* returns + { + 'type': 'Uint16Array', + 'data': [ 5, 3 ] + } +*/ + +arr = new Int8Array( [ -5, 3 ] ); +json = toJSON( arr ); +/* returns + { + 'type': 'Int8Array', + 'data': [ -5, 3 ] + } +*/ + +arr = new Uint8Array( [ 5, 3 ] ); +json = toJSON( arr ); +/* returns + { + 'type': 'Uint8Array', + 'data': [ 5, 3 ] + } +*/ + +arr = new Uint8ClampedArray( [ 5, 3 ] ); +json = toJSON( arr ); +/* returns + { + 'type': 'Uint8ClampedArray', + 'data': [ 5, 3 ] + } +*/ +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/to-json/benchmark/benchmark.js b/to-json/benchmark/benchmark.js new file mode 100644 index 00000000..3fa631cc --- /dev/null +++ b/to-json/benchmark/benchmark.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var Float64Array = require( '@stdlib/array/float64' ); +var randu = require( '@stdlib/random/base/randu' ); +var pkg = require( './../package.json' ).name; +var toJSON = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var arr; + var o; + var i; + + arr = new Float64Array( [ randu(), randu() ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = randu(); + o = toJSON( arr ); + if ( typeof o !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof o !== 'object' ) { + b.fail( 'should return an object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/to-json/benchmark/benchmark.length.js b/to-json/benchmark/benchmark.length.js new file mode 100644 index 00000000..cb0555d0 --- /dev/null +++ b/to-json/benchmark/benchmark.length.js @@ -0,0 +1,102 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randu = require( '@stdlib/random/base/randu' ); +var Float64Array = require( '@stdlib/array/float64' ); +var pkg = require( './../package.json' ).name; +var toJSON = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr; + var i; + + arr = new Float64Array( len ); + for ( i = 0; i < len; i++ ) { + arr[ i ] = randu(); + } + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var o; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = randu(); + o = toJSON( arr ); + if ( typeof o !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof o !== 'object' ) { + b.fail( 'should return an object' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':len='+len, f ); + } +} + +main(); diff --git a/to-json/docs/repl.txt b/to-json/docs/repl.txt new file mode 100644 index 00000000..075edade --- /dev/null +++ b/to-json/docs/repl.txt @@ -0,0 +1,45 @@ + +{{alias}}( arr ) + Returns a JSON representation of a typed array. + + The following typed array types are supported: + + - Float64Array + - Float32Array + - Int32Array + - Uint32Array + - Int16Array + - Uint16Array + - Int8Array + - Uint8Array + - Uint8ClampedArray + + The returned JSON object has the following properties: + + - type: typed array type + - data: typed array data as a generic array + + The implementation supports custom typed arrays and sets the `type` field to + the closest known typed array type. + + Parameters + ---------- + arr: TypedArray + Typed array to serialize. + + Returns + ------- + out: Object + JSON representation. + + Examples + -------- + > var arr = new {{alias:@stdlib/array/float64}}( 2 ); + > arr[ 0 ] = 5.0; + > arr[ 1 ] = 3.0; + > var json = {{alias}}( arr ) + { 'type': 'Float64Array', 'data': [ 5.0, 3.0 ] } + + See Also + -------- + diff --git a/to-json/docs/types/index.d.ts b/to-json/docs/types/index.d.ts new file mode 100644 index 00000000..3c033403 --- /dev/null +++ b/to-json/docs/types/index.d.ts @@ -0,0 +1,64 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/// + +import { TypedArray } from '@stdlib/types/array'; + +/** +* JSON representation of typed array. +*/ +interface JSONRepresentation { + /** + * Typed array type. + */ + type: 'Float64Array' | 'Float32Array' | 'Int32Array' | 'Uint32Array' | 'Int16Array' | 'Uint16Array' | 'Int8Array' | 'Uint8Array' | 'Uint8ClampedArray'; // tslint:disable-line:max-line-length + + /** + * Typed array data as a generic array. + */ + data: Array; +} + +/** +* Returns a JSON representation of a typed array. +* +* ## Notes +* +* - We build a JSON object representing a typed array similar to how Node.js `Buffer` objects are represented. See [Buffer][1]. +* +* [1]: https://nodejs.org/api/buffer.html#buffer_buf_tojson +* +* @param arr - typed array to serialize +* @returns JSON representation +* +* @example +* var Float64Array = require( `@stdlib/array/float64` ); +* +* var arr = new Float64Array( [ 5.0, 3.0 ] ); +* var json = toJSON( arr ); +* // returns { 'type': 'Float64Array', 'data': [ 5.0, 3.0 ] } +*/ +declare function toJSON( arr: TypedArray ): JSONRepresentation; + + +// EXPORTS // + +export = toJSON; diff --git a/to-json/docs/types/test.ts b/to-json/docs/types/test.ts new file mode 100644 index 00000000..d1bb1f91 --- /dev/null +++ b/to-json/docs/types/test.ts @@ -0,0 +1,49 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import toJSON = require( './index' ); + + +// TESTS // + +// The function returns a JSON representation... +{ + const x = new Float64Array( 10 ); + + toJSON( x ); // $ExpectType JSONRepresentation +} + +// The compiler throws an error if the function is provided a first argument which is not array-like... +{ + toJSON( 'abc' ); // $ExpectError + toJSON( 123 ); // $ExpectError + toJSON( true ); // $ExpectError + toJSON( false ); // $ExpectError + toJSON( {} ); // $ExpectError + toJSON( [] ); // $ExpectError + toJSON( null ); // $ExpectError + toJSON( undefined ); // $ExpectError +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + const x = new Float64Array( 10 ); + + toJSON(); // $ExpectError + toJSON( x, 3 ); // $ExpectError +} diff --git a/to-json/examples/index.js b/to-json/examples/index.js new file mode 100644 index 00000000..58619727 --- /dev/null +++ b/to-json/examples/index.js @@ -0,0 +1,111 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var Float64Array = require( '@stdlib/array/float64' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Int8Array = require( '@stdlib/array/int8' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); +var toJSON = require( './../lib' ); + +var arr = new Float64Array( [ 5.0, 3.0 ] ); +console.log( toJSON( arr ) ); +/* => + { + 'type': 'Float64Array', + 'data': [ 5.0, 3.0 ] + } +*/ + +arr = new Float32Array( [ 5.0, -3.0 ] ); +console.log( toJSON( arr ) ); +/* => + { + 'type': 'Float32Array', + 'data': [ 5.0, -3.0 ] + } +*/ + +arr = new Int32Array( [ -5, 3 ] ); +console.log( toJSON( arr ) ); +/* => + { + 'type': 'Int32Array', + 'data': [ -5, 3 ] + } +*/ + +arr = new Uint32Array( [ 5, 3 ] ); +console.log( toJSON( arr ) ); +/* => + { + 'type': 'Uint32Array', + 'data': [ 5, 3 ] + } +*/ + +arr = new Int16Array( [ -5, 3 ] ); +console.log( toJSON( arr ) ); +/* => + { + 'type': 'Int16Array', + 'data': [ -5, 3 ] + } +*/ + +arr = new Uint16Array( [ 5, 3 ] ); +console.log( toJSON( arr ) ); +/* => + { + 'type': 'Uint16Array', + 'data': [ 5, 3 ] + } +*/ + +arr = new Int8Array( [ -5, 3 ] ); +console.log( toJSON( arr ) ); +/* => + { + 'type': 'Int8Array', + 'data': [ -5, 3 ] + } +*/ + +arr = new Uint8Array( [ 5, 3 ] ); +console.log( toJSON( arr ) ); +/* => + { + 'type': 'Uint8Array', + 'data': [ 5, 3 ] + } +*/ + +arr = new Uint8ClampedArray( [ 5, 3 ] ); +console.log( toJSON( arr ) ); +/* => + { + 'type': 'Uint8ClampedArray', + 'data': [ 5, 3 ] + } +*/ diff --git a/to-json/lib/ctors.js b/to-json/lib/ctors.js new file mode 100644 index 00000000..193a8624 --- /dev/null +++ b/to-json/lib/ctors.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var Int8Array = require( '@stdlib/array/int8' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Float64Array = require( '@stdlib/array/float64' ); + + +// MAIN // + +var CTORS = [ + [ Float64Array, 'Float64Array' ], + [ Float32Array, 'Float32Array' ], + [ Int32Array, 'Int32Array' ], + [ Uint32Array, 'Uint32Array' ], + [ Int16Array, 'Int16Array' ], + [ Uint16Array, 'Uint16Array' ], + [ Int8Array, 'Int8Array' ], + [ Uint8Array, 'Uint8Array' ], + [ Uint8ClampedArray, 'Uint8ClampedArray' ] +]; + + +// EXPORTS // + +module.exports = CTORS; diff --git a/to-json/lib/index.js b/to-json/lib/index.js new file mode 100644 index 00000000..e3f2c014 --- /dev/null +++ b/to-json/lib/index.js @@ -0,0 +1,42 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Return a JSON representation of a typed array. +* +* @module @stdlib/array/to-json +* +* @example +* var Float64Array = require( '@stdlib/array/float64' ); +* var toJSON = require( '@stdlib/array/to-json' ); +* +* var arr = new Float64Array( [ 5.0, 3.0 ] ); +* var json = toJSON( arr ); +* // returns { 'type': 'Float64Array', 'data': [ 5.0, 3.0 ] } +*/ + +// MODULES // + +var toJSON = require( './to_json.js' ); + + +// EXPORTS // + +module.exports = toJSON; diff --git a/to-json/lib/to_json.js b/to-json/lib/to_json.js new file mode 100644 index 00000000..3a789c3c --- /dev/null +++ b/to-json/lib/to_json.js @@ -0,0 +1,67 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var typeName = require( './type.js' ); + + +// MAIN // + +/** +* Returns a JSON representation of a typed array. +* +* ## Notes +* +* - We build a JSON object representing a typed array similar to how Node.js `Buffer` objects are represented. See [Buffer][1]. +* +* [1]: https://nodejs.org/api/buffer.html#buffer_buf_tojson +* +* @param {TypedArray} arr - typed array to serialize +* @throws {TypeError} first argument must be a typed array +* @returns {Object} JSON representation +* +* @example +* var Float64Array = require( '@stdlib/array/float64' ); +* +* var arr = new Float64Array( [ 5.0, 3.0 ] ); +* var json = toJSON( arr ); +* // returns { 'type': 'Float64Array', 'data': [ 5.0, 3.0 ] } +*/ +function toJSON( arr ) { + var out; + var i; + if ( !isTypedArray( arr ) ) { + throw new TypeError( 'invalid argument. Must provide a typed array. Value: `' + arr + '`.' ); + } + out = {}; + out.type = typeName( arr ); + out.data = []; + for ( i = 0; i < arr.length; i++ ) { + out.data.push( arr[ i ] ); + } + return out; +} + + +// EXPORTS // + +module.exports = toJSON; diff --git a/to-json/lib/type.js b/to-json/lib/type.js new file mode 100644 index 00000000..23e3d1ba --- /dev/null +++ b/to-json/lib/type.js @@ -0,0 +1,70 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var instanceOf = require( '@stdlib/assert/instance-of' ); +var ctorName = require( '@stdlib/utils/constructor-name' ); +var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' ); +var CTORS = require( './ctors.js' ); + + +// MAIN // + +/** +* Returns the typed array type. +* +* @private +* @param {TypedArray} arr - typed array +* @returns {(string|void)} typed array type +* +* @example +* var Float64Array = require( '@stdlib/array/float64' ); +* +* var arr = new Float64Array( 5 ); +* var str = typeName( arr ); +* // returns 'Float64Array' +*/ +function typeName( arr ) { + var v; + var i; + + // Check for typed array objects from the same realm (same Node.js `vm` or same `Window` object)... + for ( i = 0; i < CTORS.length; i++ ) { + if ( instanceOf( arr, CTORS[ i ][ 0 ] ) ) { + return CTORS[ i ][ 1 ]; + } + } + // Walk the prototype tree until we find an object having a desired native class... + while ( arr ) { + v = ctorName( arr ); + for ( i = 0; i < CTORS.length; i++ ) { + if ( v === CTORS[ i ][ 1 ] ) { + return CTORS[ i ][ 1 ]; + } + } + arr = getPrototypeOf( arr ); + } +} + + +// EXPORTS // + +module.exports = typeName; diff --git a/to-json/package.json b/to-json/package.json new file mode 100644 index 00000000..b7150966 --- /dev/null +++ b/to-json/package.json @@ -0,0 +1,70 @@ +{ + "name": "@stdlib/array/to-json", + "version": "0.0.0", + "description": "Return a JSON representation of a typed array.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "utils", + "util", + "utilities", + "utility", + "typed", + "array", + "arr", + "typed-array", + "typed array", + "serialize", + "marshal", + "tojson", + "json", + "to", + "convert" + ] +} diff --git a/to-json/test/fixtures/custom.proto.js b/to-json/test/fixtures/custom.proto.js new file mode 100644 index 00000000..b8c2fa83 --- /dev/null +++ b/to-json/test/fixtures/custom.proto.js @@ -0,0 +1,78 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var Float64Array = require( '@stdlib/array/float64' ); +var defineProperty = require( '@stdlib/utils/define-property' ); + + +// MAIN // + +/** +* Creates a CustomTypedArray class. +* +* @private +* @param {TypedArray} ctor - typed array constructor +* @returns {CustomTypedArray} constructor +*/ +function createClass( ctor ) { + if ( !ctor ) { + ctor = Float64Array; + } + /** + * Create a new object which prototypically inherits from a typed array constructor. + * + * @private + * @constructor + * @param {Array} data - array data + * @returns {CustomTypedArray} custom typed array instance + */ + function CustomTypedArray( data ) { + var i; + for ( i = 0; i < data.length; i++ ) { + this[ i ] = data[ i ]; + } + defineProperty( this, 'length', { + 'configurable': false, + 'enumerable': true, + 'writable': false, + 'value': data.length + }); + return this; + } + + /** + * Create a prototype which inherits from the parent prototype. + */ + CustomTypedArray.prototype = Object.create( ctor.prototype ); + + /** + * Set the constructor. + */ + CustomTypedArray.prototype.constructor = CustomTypedArray; + + return CustomTypedArray; +} + + +// EXPORTS // + +module.exports = createClass; diff --git a/to-json/test/fixtures/custom.subclass.js b/to-json/test/fixtures/custom.subclass.js new file mode 100644 index 00000000..0bc23190 --- /dev/null +++ b/to-json/test/fixtures/custom.subclass.js @@ -0,0 +1,47 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Creates a CustomTypedArray class constructor. Note that we use function generation so that tests may be run in browsers not supporting ES2015 classes. This function may be loaded in non-ES2015 environments, but should only be invoked when ES2015 classes are supported. +* +* @private +* @param {string} ctor - typed array constructor name +* @returns {Function} constructor +*/ +function createClass( ctor ) { + var str = ''; + if ( !ctor ) { + ctor = 'Float64Array'; + } + str += '(function create() {'; + str += 'class CustomTypedArray extends '+ctor+' {'; + str += 'constructor( data ) {'; + str += 'super( data );'; + str += '}'; + str += '}'; + str += 'return CustomTypedArray;'; + str += '})()'; + return eval( str ); // eslint-disable-line no-eval +} + + +// EXPORTS // + +module.exports = createClass; diff --git a/to-json/test/test.ctors.js b/to-json/test/test.ctors.js new file mode 100644 index 00000000..7e3bca94 --- /dev/null +++ b/to-json/test/test.ctors.js @@ -0,0 +1,35 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var isArray = require( '@stdlib/assert/is-array' ); +var CTORS = require( './../lib/ctors.js' ); + + +// TESTS // + +tape( 'typed array constructors are exposed via an exported array', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( isArray( CTORS ), true, 'export is an array' ); + t.ok( CTORS.length > 0, 'has length > 0' ); + t.end(); +}); diff --git a/to-json/test/test.js b/to-json/test/test.js new file mode 100644 index 00000000..2bd9b6ba --- /dev/null +++ b/to-json/test/test.js @@ -0,0 +1,279 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var vm = require( 'vm' ); // TODO: handle in-browser tests +var tape = require( 'tape' ); +var IS_BROWSER = require( '@stdlib/assert/is-browser' ); +var hasClassSupport = require( '@stdlib/assert/has-class-support' ); +var isPlainObject = require( '@stdlib/assert/is-plain-object' ); +var Int8Array = require( '@stdlib/array/int8' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Float64Array = require( '@stdlib/array/float64' ); +var toJSON = require( './../lib' ); + + +// FIXTURES // + +var createClass1 = require( './fixtures/custom.proto.js' ); +var createClass2 = require( './fixtures/custom.subclass.js' ); + + +// VARIABLES // + +var hasClasses = hasClassSupport(); +var opts = { + 'skip': false +}; + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof toJSON, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'if provided anything other than a typed array instance, the function will throw an error', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + null, + undefined, + true, + false, + [], + {}, + function noop() {}, + new Date(), + /.*/ + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), Error, 'throws when provided a ' + (typeof values[i]) ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + toJSON( value ); + }; + } +}); + +tape( 'the function returns a JSON object', function test( t ) { + var json; + var arr; + + arr = new Float64Array( [ 5.0, 3.0 ] ); + json = toJSON( arr ); + t.strictEqual( isPlainObject( json ), true, 'returns an object' ); + t.end(); +}); + +tape( 'the JSON object includes a typed array type', function test( t ) { + var expected; + var values; + var json; + var i; + + values = [ + new Float64Array( 1 ), + new Float32Array( 1 ), + new Int32Array( 1 ), + new Uint32Array( 1 ), + new Int16Array( 1 ), + new Uint16Array( 1 ), + new Int8Array( 1 ), + new Uint8Array( 1 ), + new Uint8ClampedArray( 1 ) + ]; + + expected = [ + 'Float64Array', + 'Float32Array', + 'Int32Array', + 'Uint32Array', + 'Int16Array', + 'Uint16Array', + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray' + ]; + + for ( i = 0; i < values.length; i++ ) { + json = toJSON( values[ i ] ); + t.strictEqual( json.type, expected[ i ], 'type equal to ' + expected[ i ] ); + } + t.end(); +}); + +tape( 'the JSON object includes a data property', function test( t ) { + var expected; + var values; + var json; + var i; + + values = [ + new Float64Array( [ 1.0 ] ), + new Float32Array( [ 2.0 ] ), + new Int32Array( [ 3.0 ] ), + new Uint32Array( [ 4.0 ] ), + new Int16Array( [ 5.0 ] ), + new Uint16Array( [ 6.0 ] ), + new Int8Array( [ 7.0 ] ), + new Uint8Array( [ 8.0 ] ), + new Uint8ClampedArray( [ 9.0 ] ) + ]; + + expected = [ + [ 1.0 ], + [ 2.0 ], + [ 3.0 ], + [ 4.0 ], + [ 5.0 ], + [ 6.0 ], + [ 7.0 ], + [ 8.0 ], + [ 9.0 ] + ]; + + for ( i = 0; i < values.length; i++ ) { + json = toJSON( values[ i ] ); + t.deepEqual( json.data, expected[ i ], 'has expected property value' ); + } + t.end(); +}); + +tape( 'custom typed arrays are supported (proto)', function test( t ) { + var CustomTypedArray; + var types; + var ctors; + var json; + var arr; + var i; + + ctors = [ + Float64Array, + Float32Array, + Int32Array, + Uint32Array, + Int16Array, + Uint16Array, + Int8Array, + Uint8Array, + Uint8ClampedArray + ]; + + types = [ + 'Float64Array', + 'Float32Array', + 'Int32Array', + 'Uint32Array', + 'Int16Array', + 'Uint16Array', + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray' + ]; + + for ( i = 0; i < ctors.length; i++ ) { + CustomTypedArray = createClass1( ctors[ i ] ); + arr = new CustomTypedArray( [ 5.0, 3.0 ] ); + json = toJSON( arr ); + t.strictEqual( json.type, types[ i ], 'type equal to ' + types[ i ] ); + t.deepEqual( json.data, [ 5.0, 3.0 ], 'has expected value' ); + } + t.end(); +}); + +opts.skip = !hasClasses; +tape( 'custom typed arrays are supported (subclass; ES2015)', opts, function test( t ) { + var CustomTypedArray; + var ctors; + var json; + var arr; + var i; + + ctors = [ + 'Float64Array', + 'Float32Array', + 'Int32Array', + 'Uint32Array', + 'Int16Array', + 'Uint16Array', + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray' + ]; + + for ( i = 0; i < ctors.length; i++ ) { + CustomTypedArray = createClass2( ctors[ i ] ); + arr = new CustomTypedArray( [ 5.0, 3.0 ] ); + json = toJSON( arr ); + t.strictEqual( json.type, ctors[ i ], 'type equal to ' + ctors[ i ] ); + t.deepEqual( json.data, [ 5.0, 3.0 ], 'has expected value' ); + } + t.end(); +}); + +opts.skip = IS_BROWSER; +tape( 'the function supports serializing a typed array from a different realm', opts, function test( t ) { + var json; + var arr; + + arr = vm.runInNewContext( 'new Float64Array( [ 5.0, 3.0 ] )', { + 'Float64Array': Float64Array + }); + json = toJSON( arr ); + + t.strictEqual( json.type, 'Float64Array', 'returns expected value' ); + t.deepEqual( json.data, [ 5.0, 3.0 ], 'returns expected value' ); + + t.end(); +}); + +opts.skip = IS_BROWSER; +tape( 'the function supports serializing an object from a different realm which inherits from a typed array', opts, function test( t ) { + var json; + var arr; + + arr = vm.runInNewContext( 'function Arr( data ) { Object.defineProperty( this, "length", {"configurable":false,"enumerable":true,"writable":false,"value":data.length}); for ( var i = 0; i < data.length; i++ ) { this[ i ] = data[ i ]; }; return this; }; Arr.prototype = Object.create( Float64Array.prototype ); Arr.prototype.constructor = Arr; new Arr( [ 5.0, 3.0 ] );', { + 'Float64Array': Float64Array + }); + json = toJSON( arr ); + + t.strictEqual( json.type, 'Float64Array', 'returns expected value' ); + t.deepEqual( json.data, [ 5.0, 3.0 ], 'returns expected value' ); + + t.end(); +}); diff --git a/to-json/test/test.type.js b/to-json/test/test.type.js new file mode 100644 index 00000000..876e9684 --- /dev/null +++ b/to-json/test/test.type.js @@ -0,0 +1,147 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var Int8Array = require( '@stdlib/array/int8' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Float64Array = require( '@stdlib/array/float64' ); +var typeName = require( './../lib/type.js' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof typeName, 'function', 'export is a function' ); + t.end(); +}); + +tape( 'if provided a typed array, the function returns the closest typed array type', function test( t ) { + var expected; + var values; + var i; + + values = [ + new Float64Array( [ 5.0, 3.0 ] ), + new Float32Array( [ 5.0, 3.0 ] ), + new Int32Array( [ 5, 3 ] ), + new Uint32Array( [ 5, 3 ] ), + new Int16Array( [ 5, 3 ] ), + new Uint16Array( [ 5, 3 ] ), + new Int8Array( [ 5, 3 ] ), + new Uint8Array( [ 5, 3 ] ), + new Uint8ClampedArray( [ 5, 3 ] ) + ]; + + expected = [ + 'Float64Array', + 'Float32Array', + 'Int32Array', + 'Uint32Array', + 'Int16Array', + 'Uint16Array', + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.strictEqual( typeName( values[i] ), expected[ i ], 'returns the constructor name: ' + expected[ i ] ); + } + t.end(); +}); + +tape( 'if provided a typed array from a different realm, the function returns the closest typed array type', function test( t ) { + var typeName; + var expected; + var values; + var i; + + typeName = proxyquire( './../lib/type.js', { + '@stdlib/assert/instance-of': instanceOf + }); + + values = [ + new Float64Array( [ 5.0, 3.0 ] ), + new Float32Array( [ 5.0, 3.0 ] ), + new Int32Array( [ 5, 3 ] ), + new Uint32Array( [ 5, 3 ] ), + new Int16Array( [ 5, 3 ] ), + new Uint16Array( [ 5, 3 ] ), + new Int8Array( [ 5, 3 ] ), + new Uint8Array( [ 5, 3 ] ), + new Uint8ClampedArray( [ 5, 3 ] ) + ]; + + expected = [ + 'Float64Array', + 'Float32Array', + 'Int32Array', + 'Uint32Array', + 'Int16Array', + 'Uint16Array', + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.strictEqual( typeName( values[i] ), expected[ i ], 'returns the constructor name: ' + expected[ i ] ); + } + t.end(); + + function instanceOf() { + // Mocks comparing values from different realms... + return false; + } +}); + +tape( 'if not provided a typed array, the function returns `undefined`', function test( t ) { + var values; + var i; + + values = [ + '5', + NaN, + 5, + true, + false, + null, + void 0, + [], + {}, + function noop() {}, + function typedarray() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.strictEqual( typeName( values[i] ), void 0, 'returns expected value' ); + } + t.end(); +}); diff --git a/to-sparse-iterator-right/README.md b/to-sparse-iterator-right/README.md new file mode 100644 index 00000000..4b161fc1 --- /dev/null +++ b/to-sparse-iterator-right/README.md @@ -0,0 +1,220 @@ + + +# sparsearray2iteratorRight + +> Create an iterator from a sparse array-like object, iterating from right to left. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var sparsearray2iteratorRight = require( '@stdlib/array/to-sparse-iterator-right' ); +``` + +#### sparsearray2iteratorRight( src\[, mapFcn\[, thisArg]] ) + +Returns an iterator which iterates from right to left over each element in a sparse array-like `object`. + + + +```javascript +var it = sparsearray2iteratorRight( [ 1, , , 4 ] ); +// returns + +var v = it.next().value; +// returns 4 + +v = it.next().value; +// returns 1 + +var bool = it.next().done; +// returns true +``` + +The returned iterator protocol-compliant object has the following properties: + +- **next**: function which returns an iterator protocol-compliant object containing the next iterated value (if one exists) assigned to a `value` property and a `done` property having a `boolean` value indicating whether the iterator is finished. +- **return**: function which closes an iterator and returns a single (optional) argument in an iterator protocol-compliant object. + +To invoke a function for each `src` value, provide a callback function. + + + +```javascript +function fcn( v ) { + return v * 10.0; +} + +var it = sparsearray2iteratorRight( [ 1, 2, , 4 ], fcn ); +// returns + +var v = it.next().value; +// returns 40.0 + +v = it.next().value; +// returns 20.0 + +// ... +``` + +The invoked function is provided three arguments: + +- `value`: iterated value +- `index`: iterated value index +- `src`: source array-like object + + + +```javascript +function fcn( v, i ) { + return v * (i+1); +} + +var it = sparsearray2iteratorRight( [ 1, 2, , 4 ], fcn ); +// returns + +var v = it.next().value; +// returns 16 + +v = it.next().value; +// returns 4 + +v = it.next().value; +// returns 1 +``` + +To set the callback function execution context, provide a `thisArg`. + + + +```javascript +function fcn( v ) { + this.count += 1; + return v * 10.0; +} + +var ctx = { + 'count': 0 +}; + +var it = sparsearray2iteratorRight( [ 1, 2, , 4 ], fcn, ctx ); +// returns + +var v = it.next().value; +// returns 40.0 + +v = it.next().value; +// returns 20.0 + +var count = ctx.count; +// returns 2 +``` + + + + + + + +
+ +## Notes + +- If an environment supports `Symbol.iterator`, the returned iterator is iterable. +- If provided a generic `array`, the returned iterator **ignores** holes (i.e., `undefined` values). To iterate over all generic `array` elements, use [`@stdlib/array/to-iterator-right`][@stdlib/array/to-iterator-right]. +- A returned iterator does **not** copy a provided array-like `object`. To ensure iterable reproducibility, copy a provided array-like `object` **before** creating an iterator. Otherwise, any changes to the contents of an array-like `object` will be reflected in the returned iterator. +- In environments supporting `Symbol.iterator`, the function **explicitly** does **not** invoke an array's `@@iterator` method, regardless of whether this method is defined. To convert an array to an implementation defined iterator, invoke this method directly. + +
+ + + + + +
+ +## Examples + + + +```javascript +var Float64Array = require( '@stdlib/array/float64' ); +var inmap = require( '@stdlib/utils/inmap' ); +var randu = require( '@stdlib/random/base/randu' ); +var sparsearray2iteratorRight = require( '@stdlib/array/to-sparse-iterator-right' ); + +function scale( v, i ) { + return v * (i+1); +} + +// Create an array partially filled with random numbers: +var arr = new Array( 100 ); +var i; +for ( i = 0; i < arr.length; i += 2 ) { + arr[ i ] = randu(); +} + +// Create an iterator from the array which scales iterated values: +var it = sparsearray2iteratorRight( arr, scale ); + +// Perform manual iteration... +var v; +while ( true ) { + v = it.next(); + if ( v.done ) { + break; + } + console.log( v.value ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/to-sparse-iterator-right/benchmark/benchmark.js b/to-sparse-iterator-right/benchmark/benchmark.js new file mode 100644 index 00000000..3cbe2222 --- /dev/null +++ b/to-sparse-iterator-right/benchmark/benchmark.js @@ -0,0 +1,113 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isnan = require( '@stdlib/math/base/assert/is-nan' ); +var isIteratorLike = require( '@stdlib/assert/is-iterator-like' ); +var pkg = require( './../package.json' ).name; +var sparsearray2iteratorRight = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var values; + var iter; + var i; + + values = [ 1, 2, 3, 4 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + values[ 0 ] = i; + iter = sparsearray2iteratorRight( values ); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isIteratorLike( iter ) ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::iteration', function benchmark( b ) { + var values; + var iter; + var z; + var i; + + values = []; + for ( i = 0; i < b.iterations; i++ ) { + values.push( i ); + } + + iter = sparsearray2iteratorRight( values ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + z = iter.next().value; + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::iteration,map', function benchmark( b ) { + var values; + var iter; + var z; + var i; + + values = []; + for ( i = 0; i < b.iterations; i++ ) { + values.push( i ); + } + + iter = sparsearray2iteratorRight( values, transform ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + z = iter.next().value; + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function transform( v, i ) { + return i; + } +}); diff --git a/to-sparse-iterator-right/docs/repl.txt b/to-sparse-iterator-right/docs/repl.txt new file mode 100644 index 00000000..1952c7f2 --- /dev/null +++ b/to-sparse-iterator-right/docs/repl.txt @@ -0,0 +1,56 @@ + +{{alias}}( src[, mapFcn[, thisArg]] ) + Returns an iterator which iterates from right to left over the elements of a + sparse array-like object. + + The returned iterator skips elements which are undefined. + + When invoked, an input function is provided three arguments: + + - value: iterated value + - index: iterated value index + - src: source array-like object + + If an environment supports Symbol.iterator, the returned iterator is + iterable. + + If an environment supports Symbol.iterator, the function explicitly does not + not invoke an array's `@@iterator` method, regardless of whether this method + is defined. To convert an array to an implementation defined iterator, + invoke this method directly. + + Parameters + ---------- + src: ArrayLikeObject + Sparse array-like object from which to create the iterator. + + mapFcn: Function (optional) + Function to invoke for each iterated value. + + thisArg: any (optional) + Execution context. + + Returns + ------- + iterator: Object + Iterator. + + iterator.next(): Function + Returns an iterator protocol-compliant object containing the next + iterated value (if one exists) and a boolean flag indicating whether the + iterator is finished. + + iterator.return( [value] ): Function + Finishes an iterator and returns a provided value. + + Examples + -------- + > var it = {{alias}}( [ 1, 2, , 4 ] ); + > var v = it.next().value + 4 + > v = it.next().value + 2 + + See Also + -------- + diff --git a/to-sparse-iterator-right/docs/types/index.d.ts b/to-sparse-iterator-right/docs/types/index.d.ts new file mode 100644 index 00000000..58f72638 --- /dev/null +++ b/to-sparse-iterator-right/docs/types/index.d.ts @@ -0,0 +1,102 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/// + +import { Iterator as Iter, IterableIterator } from '@stdlib/types/iter'; +import { ArrayLike } from '@stdlib/types/array'; + +// Define a union type representing both iterable and non-iterable iterators: +type Iterator = Iter | IterableIterator; + +/** +* Map function invoked for each iterated value. +* +* @returns iterator value +*/ +type Nullary = () => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @returns iterator value +*/ +type Unary = ( value: any ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @returns iterator value +*/ +type Binary = ( value: any, index: number ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @param src - source array-like object +* @returns iterator value +*/ +type Tertiary = ( value: any, index: number, src: ArrayLike ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @param src - source array-like object +* @returns iterator value +*/ +type MapFunction = Nullary | Unary | Binary | Tertiary; + +/** +* Returns an iterator which iterates from right to left over each element in a sparse array-like object. +* +* ## Notes +* +* - For dynamic array resizing, the only behavior made intentionally consistent with iterating from left to right is when elements are pushed onto the beginning (end) of an array. In other words, iterating from left to right combined with `[].push()` is consistent with iterating from right to left combined with `[].unshift()`. +* +* @param src - input value +* @param mapFcn - function to invoke for each iterated value +* @param thisArg - execution context +* @returns iterator +* +* @example +* var iter = sparsearray2iteratorRight( [ 1, , 3, 4 ] ); +* +* var v = iter.next().value; +* // returns 4 +* +* v = iter.next().value; +* // returns 3 +* +* v = iter.next().value; +* // returns 1 +*/ +declare function sparsearray2iteratorRight( src: ArrayLike, mapFcn?: MapFunction, thisArg?: any ): Iterator; // tslint:disable-line:max-line-length + + +// EXPORTS // + +export = sparsearray2iteratorRight; diff --git a/to-sparse-iterator-right/docs/types/test.ts b/to-sparse-iterator-right/docs/types/test.ts new file mode 100644 index 00000000..8575e6b6 --- /dev/null +++ b/to-sparse-iterator-right/docs/types/test.ts @@ -0,0 +1,66 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import sparsearray2iteratorRight = require( './index' ); + +/** +* Multiplies a value by 10. +* +* @param v - iterated value +* @returns new value +*/ +function times10( v: number ): number { + return v * 10.0; +} + + +// TESTS // + +// The function returns an iterator... +{ + sparsearray2iteratorRight( [ 1, 2, 3, 4 ] ); // $ExpectType Iterator + sparsearray2iteratorRight( [ 1, 2, 3, 4 ], times10 ); // $ExpectType Iterator + sparsearray2iteratorRight( [ 1, 2, 3, 4 ], times10, {} ); // $ExpectType Iterator +} + +// The compiler throws an error if the function is provided a first argument which is not array-like... +{ + sparsearray2iteratorRight( 123 ); // $ExpectError + sparsearray2iteratorRight( true ); // $ExpectError + sparsearray2iteratorRight( false ); // $ExpectError + sparsearray2iteratorRight( {} ); // $ExpectError + sparsearray2iteratorRight( null ); // $ExpectError + sparsearray2iteratorRight( undefined ); // $ExpectError +} + +// The compiler throws an error if the function is provided a second argument which is not a map function... +{ + sparsearray2iteratorRight( [ 1, 2, 3, 4 ], 'abc' ); // $ExpectError + sparsearray2iteratorRight( [ 1, 2, 3, 4 ], 123 ); // $ExpectError + sparsearray2iteratorRight( [ 1, 2, 3, 4 ], [] ); // $ExpectError + sparsearray2iteratorRight( [ 1, 2, 3, 4 ], {} ); // $ExpectError + sparsearray2iteratorRight( [ 1, 2, 3, 4 ], true ); // $ExpectError + sparsearray2iteratorRight( [ 1, 2, 3, 4 ], false ); // $ExpectError + sparsearray2iteratorRight( [ 1, 2, 3, 4 ], null ); // $ExpectError +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + sparsearray2iteratorRight(); // $ExpectError + sparsearray2iteratorRight( [ 1, 2, 3, 4 ], times10, {}, 123 ); // $ExpectError +} diff --git a/to-sparse-iterator-right/examples/index.js b/to-sparse-iterator-right/examples/index.js new file mode 100644 index 00000000..6afa6697 --- /dev/null +++ b/to-sparse-iterator-right/examples/index.js @@ -0,0 +1,46 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var randu = require( '@stdlib/random/base/randu' ); +var sparsearray2iteratorRight = require( './../lib' ); + +function scale( v, i ) { + return v * (i+1); +} + +// Create an array partially filled with random numbers: +var arr = new Array( 100 ); +var i; +for ( i = 0; i < arr.length; i += 2 ) { + arr[ i ] = randu(); +} + +// Create an iterator from the array which scales iterated values: +var it = sparsearray2iteratorRight( arr, scale ); + +// Perform manual iteration... +var v; +while ( true ) { + v = it.next(); + if ( v.done ) { + break; + } + console.log( v.value ); +} diff --git a/to-sparse-iterator-right/lib/index.js b/to-sparse-iterator-right/lib/index.js new file mode 100644 index 00000000..02abe0e8 --- /dev/null +++ b/to-sparse-iterator-right/lib/index.js @@ -0,0 +1,48 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Create an iterator from a sparse array-like value, iterating from right to left. +* +* @module @stdlib/array/to-sparse-iterator-right +* +* @example +* var sparsearray2iteratorRight = require( '@stdlib/array/to-sparse-iterator-right' ); +* +* var iter = sparsearray2iteratorRight( [ 1, , 3, 4 ] ); +* +* var v = iter.next().value; +* // returns 4 +* +* v = iter.next().value; +* // returns 3 +* +* v = iter.next().value; +* // returns 1 +*/ + +// MODULES // + +var iterator = require( './main.js' ); + + +// EXPORTS // + +module.exports = iterator; diff --git a/to-sparse-iterator-right/lib/main.js b/to-sparse-iterator-right/lib/main.js new file mode 100644 index 00000000..965aa073 --- /dev/null +++ b/to-sparse-iterator-right/lib/main.js @@ -0,0 +1,187 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var isCollection = require( '@stdlib/assert/is-collection' ); +var iteratorSymbol = require( '@stdlib/symbol/iterator' ); + + +// MAIN // + +/** +* Returns an iterator which iterates from right to left over each element in a sparse array-like object. +* +* ## Notes +* +* - For dynamic array resizing, the only behavior made intentionally consistent with iterating from left to right is when elements are pushed onto the beginning (end) of an array. In other words, iterating from left to right combined with `[].push()` is consistent with iterating from right to left combined with `[].unshift()`. +* +* @param {Collection} src - input value +* @param {Function} [mapFcn] - function to invoke for each iterated value +* @param {*} [thisArg] - execution context +* @throws {TypeError} first argument must be an array-like object +* @throws {TypeError} second argument must be a function +* @returns {Iterator} iterator +* +* @example +* var iter = sparsearray2iteratorRight( [ 1, , 3, 4 ] ); +* +* var v = iter.next().value; +* // returns 4 +* +* v = iter.next().value; +* // returns 3 +* +* v = iter.next().value; +* // returns 1 +*/ +function sparsearray2iteratorRight( src ) { + var thisArg; + var iter; + var FLG; + var fcn; + var len; + var i; + if ( !isCollection( src ) ) { + throw new TypeError( 'invalid argument. First argument must be an array-like object. Value: `' + src + '`.' ); + } + if ( arguments.length > 1 ) { + fcn = arguments[ 1 ]; + if ( !isFunction( fcn ) ) { + throw new TypeError( 'invalid argument. Second argument must be a function. Value: `' + fcn + '`.' ); + } + thisArg = arguments[ 2 ]; + } + len = src.length; + i = len; + + // Create an iterator protocol-compliant object: + iter = {}; + if ( fcn ) { + setReadOnly( iter, 'next', next1 ); + } else { + setReadOnly( iter, 'next', next2 ); + } + setReadOnly( iter, 'return', end ); + + // If an environment supports `Symbol.iterator`, make the iterator iterable: + if ( iteratorSymbol ) { + setReadOnly( iter, iteratorSymbol, factory ); + } + return iter; + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next1() { + if ( FLG ) { + return { + 'done': true + }; + } + i += src.length - len - 1; // accounts for a dynamic array + len = src.length; + while ( i >= 0 && src[ i ] === void 0 ) { + i -= 1; + } + if ( i < 0 ) { + FLG = true; + return { + 'done': true + }; + } + return { + 'value': fcn.call( thisArg, src[ i ], i, src ), + 'done': false + }; + } + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next2() { + if ( FLG ) { + return { + 'done': true + }; + } + i += src.length - len - 1; // accounts for a dynamic array + len = src.length; + while ( i >= 0 && src[ i ] === void 0 ) { + i -= 1; + } + if ( i < 0 ) { + FLG = true; + return { + 'done': true + }; + } + return { + 'value': src[ i ], + 'done': false + }; + } + + /** + * Finishes an iterator. + * + * @private + * @param {*} [value] - value to return + * @returns {Object} iterator protocol-compliant object + */ + function end( value ) { + FLG = true; + if ( arguments.length ) { + return { + 'value': value, + 'done': true + }; + } + return { + 'done': true + }; + } + + /** + * Returns a new iterator. + * + * @private + * @returns {Iterator} iterator + */ + function factory() { + if ( fcn ) { + return sparsearray2iteratorRight( src, fcn, thisArg ); + } + return sparsearray2iteratorRight( src ); + } +} + + +// EXPORTS // + +module.exports = sparsearray2iteratorRight; diff --git a/to-sparse-iterator-right/package.json b/to-sparse-iterator-right/package.json new file mode 100644 index 00000000..e9838bdb --- /dev/null +++ b/to-sparse-iterator-right/package.json @@ -0,0 +1,72 @@ +{ + "name": "@stdlib/array/to-sparse-iterator-right", + "version": "0.0.0", + "description": "Create an iterator from a sparse array-like object, iterating from right to left.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "utils", + "util", + "utilities", + "utility", + "typed", + "array", + "arr", + "sparse", + "holes", + "typed-array", + "typed array", + "iterator", + "iterate", + "iteration", + "iter", + "to", + "convert" + ] +} diff --git a/to-sparse-iterator-right/test/test.js b/to-sparse-iterator-right/test/test.js new file mode 100644 index 00000000..465d4fa5 --- /dev/null +++ b/to-sparse-iterator-right/test/test.js @@ -0,0 +1,730 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var iteratorSymbol = require( '@stdlib/symbol/iterator' ); +var noop = require( '@stdlib/utils/noop' ); +var sparsearray2iteratorRight = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.equal( typeof sparsearray2iteratorRight, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + sparsearray2iteratorRight( value ); + }; + } +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object (callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + sparsearray2iteratorRight( value, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a second argument which is not a function', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + [], + {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + sparsearray2iteratorRight( [ 1, 2, 3, 4 ], value ); + }; + } +}); + +tape( 'the function returns an iterator protocol-compliant object', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, , , 4 ]; // eslint-disable-line no-sparse-arrays + expected = [ + { + 'value': 4, + 'done': false + }, + { + 'value': 1, + 'done': false + }, + { + 'done': true + } + ]; + + it = sparsearray2iteratorRight( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (empty array)', function test( t ) { + var expected; + var actual; + var values; + var it; + + values = new Array( 1e5 ); + expected = [ + { + 'done': true + } + ]; + + it = sparsearray2iteratorRight( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (empty end)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = new Array( 4 ); + + // Leave the last element empty: + for ( i = 0; i < values.length-1; i++ ) { + values[ i ] = i + 1; + } + expected = [ + { + 'value': 3, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 1, + 'done': false + }, + { + 'done': true + } + ]; + + it = sparsearray2iteratorRight( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-1; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (empty start)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = new Array( 4 ); + + // Leave the first element empty: + for ( i = 1; i < values.length; i++ ) { + values[ i ] = i + 1; + } + + expected = [ + { + 'value': 4, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'done': true + } + ]; + + it = sparsearray2iteratorRight( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-1; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (empty start+end)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = new Array( 4 ); + + // Leave the first and last elements empty: + for ( i = 1; i < values.length-1; i++ ) { + values[ i ] = i + 1; + } + + expected = [ + { + 'value': 3, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'done': true + } + ]; + + it = sparsearray2iteratorRight( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (array-like object)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = { + 'length': 4, + '1': 2, + '2': 3, + '3': 4 + }; + expected = [ + { + 'value': 4, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'done': true + } + ]; + + it = sparsearray2iteratorRight( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-1; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = new Array( 4 ); + + // Leave the last element empty: + for ( i = 0; i < values.length-1; i++ ) { + values[ i ] = i + 1; + } + + it = sparsearray2iteratorRight( values, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length-1; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length-1, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (array-like)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = { + 'length': 4, + '0': 1, + '1': 2, + '3': 4 + }; + + it = sparsearray2iteratorRight( values, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length-1; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length-1, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object', function test( t ) { + var expected; + var values; + var actual; + var it; + var i; + + values = [ 1, , 3, 4 ]; // eslint-disable-line no-sparse-arrays + expected = [ + { + 'value': 4, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 1, + 'done': false + }, + { + 'done': true + } + ]; + + it = sparsearray2iteratorRight( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-1; i++ ) { + actual.push( it.next() ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (callback)', function test( t ) { + var expected; + var values; + var actual; + var it; + var i; + + values = [ 1, 2, , 4 ]; // eslint-disable-line no-sparse-arrays + expected = [ + { + 'value': 16, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'value': 1, + 'done': false + }, + { + 'done': true + } + ]; + + it = sparsearray2iteratorRight( values, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-1; i++ ) { + actual.push( it.next() ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (no argument)', function test( t ) { + var it; + var r; + + it = sparsearray2iteratorRight( [ 1, 2, 3, 4 ] ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (no argument; callback)', function test( t ) { + var it; + var r; + + it = sparsearray2iteratorRight( [ 1, 2, 3, 4 ], scale ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (argument)', function test( t ) { + var it; + var r; + + it = sparsearray2iteratorRight( [ 1, 2, 3, 4 ] ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return( 'finished' ); + t.equal( r.value, 'finished', 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (argument; callback)', function test( t ) { + var it; + var r; + + it = sparsearray2iteratorRight( [ 1, 2, 3, 4 ], scale ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return( 'finished' ); + t.equal( r.value, 'finished', 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable', function test( t ) { + var sparsearray2iteratorRight; + var values; + var it1; + var it2; + var i; + + sparsearray2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = sparsearray2iteratorRight( values ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable (callback)', function test( t ) { + var sparsearray2iteratorRight; + var values; + var it1; + var it2; + var i; + + sparsearray2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = sparsearray2iteratorRight( values, scale ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); + + function scale( v ) { + return v * 10.0; + } +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable"', function test( t ) { + var sparsearray2iteratorRight; + var it; + + sparsearray2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = sparsearray2iteratorRight( [ 1, 2, 3, 4 ] ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable" (callback)', function test( t ) { + var sparsearray2iteratorRight; + var it; + + sparsearray2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = sparsearray2iteratorRight( [ 1, 2, 3, 4 ], scale ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); diff --git a/to-sparse-iterator/README.md b/to-sparse-iterator/README.md new file mode 100644 index 00000000..2edf3ba1 --- /dev/null +++ b/to-sparse-iterator/README.md @@ -0,0 +1,220 @@ + + +# sparsearray2iterator + +> Create an iterator from a sparse array-like object. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var sparsearray2iterator = require( '@stdlib/array/to-sparse-iterator' ); +``` + +#### sparsearray2iterator( src\[, mapFcn\[, thisArg]] ) + +Returns an iterator which iterates over each element in a sparse array-like `object`. + + + +```javascript +var it = sparsearray2iterator( [ 1, , , 4 ] ); +// returns + +var v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 4 + +var bool = it.next().done; +// returns true +``` + +The returned iterator protocol-compliant object has the following properties: + +- **next**: function which returns an iterator protocol-compliant object containing the next iterated value (if one exists) assigned to a `value` property and a `done` property having a `boolean` value indicating whether the iterator is finished. +- **return**: function which closes an iterator and returns a single (optional) argument in an iterator protocol-compliant object. + +To invoke a function for each `src` value, provide a callback function. + + + +```javascript +function fcn( v ) { + return v * 10.0; +} + +var it = sparsearray2iterator( [ 1, , 3, 4 ], fcn ); +// returns + +var v = it.next().value; +// returns 10.0 + +v = it.next().value; +// returns 30.0 + +// ... +``` + +The invoked function is provided three arguments: + +- `value`: iterated value +- `index`: iterated value index +- `src`: source array-like object + + + +```javascript +function fcn( v, i ) { + return v * (i+1); +} + +var it = sparsearray2iterator( [ 1, 2, , 4 ], fcn ); +// returns + +var v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 4 + +v = it.next().value; +// returns 16 +``` + +To set the callback function execution context, provide a `thisArg`. + + + +```javascript +function fcn( v ) { + this.count += 1; + return v * 10.0; +} + +var ctx = { + 'count': 0 +}; + +var it = sparsearray2iterator( [ 1, , 3, 4 ], fcn, ctx ); +// returns + +var v = it.next().value; +// returns 10.0 + +v = it.next().value; +// returns 30.0 + +var count = ctx.count; +// returns 2 +``` + + + + + + + +
+ +## Notes + +- If an environment supports `Symbol.iterator`, the returned iterator is iterable. +- If provided a generic `array`, the returned iterator **ignores** holes (i.e., `undefined` values). To iterate over all generic `array` elements, use [`@stdlib/array/to-iterator`][@stdlib/array/to-iterator]. +- A returned iterator does **not** copy a provided array-like `object`. To ensure iterable reproducibility, copy a provided array-like `object` **before** creating an iterator. Otherwise, any changes to the contents of an array-like `object` will be reflected in the returned iterator. +- In environments supporting `Symbol.iterator`, the function **explicitly** does **not** invoke an array's `@@iterator` method, regardless of whether this method is defined. To convert an array to an implementation defined iterator, invoke this method directly. + +
+ + + + + +
+ +## Examples + + + +```javascript +var Float64Array = require( '@stdlib/array/float64' ); +var inmap = require( '@stdlib/utils/inmap' ); +var randu = require( '@stdlib/random/base/randu' ); +var sparsearray2iterator = require( '@stdlib/array/to-sparse-iterator' ); + +function scale( v, i ) { + return v * (i+1); +} + +// Create an array partially filled with random numbers: +var arr = new Array( 100 ); +var i; +for ( i = 0; i < arr.length; i += 2 ) { + arr[ i ] = randu(); +} + +// Create an iterator from the array which scales iterated values: +var it = sparsearray2iterator( arr, scale ); + +// Perform manual iteration... +var v; +while ( true ) { + v = it.next(); + if ( v.done ) { + break; + } + console.log( v.value ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/to-sparse-iterator/benchmark/benchmark.js b/to-sparse-iterator/benchmark/benchmark.js new file mode 100644 index 00000000..7419dc87 --- /dev/null +++ b/to-sparse-iterator/benchmark/benchmark.js @@ -0,0 +1,113 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isnan = require( '@stdlib/math/base/assert/is-nan' ); +var isIteratorLike = require( '@stdlib/assert/is-iterator-like' ); +var pkg = require( './../package.json' ).name; +var sparsearray2iterator = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var values; + var iter; + var i; + + values = [ 1, 2, 3, 4 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + values[ 0 ] = i; + iter = sparsearray2iterator( values ); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isIteratorLike( iter ) ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::iteration', function benchmark( b ) { + var values; + var iter; + var z; + var i; + + values = []; + for ( i = 0; i < b.iterations; i++ ) { + values.push( i ); + } + + iter = sparsearray2iterator( values ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + z = iter.next().value; + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::iteration,map', function benchmark( b ) { + var values; + var iter; + var z; + var i; + + values = []; + for ( i = 0; i < b.iterations; i++ ) { + values.push( i ); + } + + iter = sparsearray2iterator( values, transform ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + z = iter.next().value; + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function transform( v, i ) { + return i; + } +}); diff --git a/to-sparse-iterator/docs/repl.txt b/to-sparse-iterator/docs/repl.txt new file mode 100644 index 00000000..98b8b78c --- /dev/null +++ b/to-sparse-iterator/docs/repl.txt @@ -0,0 +1,56 @@ + +{{alias}}( src[, mapFcn[, thisArg]] ) + Returns an iterator which iterates over the elements of a sparse array-like + object. + + The returned iterator skips elements which are undefined. + + When invoked, an input function is provided three arguments: + + - value: iterated value + - index: iterated value index + - src: source array-like object + + If an environment supports Symbol.iterator, the returned iterator is + iterable. + + If an environment supports Symbol.iterator, the function explicitly does not + not invoke an array's `@@iterator` method, regardless of whether this method + is defined. To convert an array to an implementation defined iterator, + invoke this method directly. + + Parameters + ---------- + src: ArrayLikeObject + Sparse array-like object from which to create the iterator. + + mapFcn: Function (optional) + Function to invoke for each iterated value. + + thisArg: any (optional) + Execution context. + + Returns + ------- + iterator: Object + Iterator. + + iterator.next(): Function + Returns an iterator protocol-compliant object containing the next + iterated value (if one exists) and a boolean flag indicating whether the + iterator is finished. + + iterator.return( [value] ): Function + Finishes an iterator and returns a provided value. + + Examples + -------- + > var it = {{alias}}( [ 1, , 3, 4 ] ); + > var v = it.next().value + 1 + > v = it.next().value + 3 + + See Also + -------- + diff --git a/to-sparse-iterator/docs/types/index.d.ts b/to-sparse-iterator/docs/types/index.d.ts new file mode 100644 index 00000000..2c8b40a7 --- /dev/null +++ b/to-sparse-iterator/docs/types/index.d.ts @@ -0,0 +1,98 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/// + +import { Iterator as Iter, IterableIterator } from '@stdlib/types/iter'; +import { ArrayLike } from '@stdlib/types/array'; + +// Define a union type representing both iterable and non-iterable iterators: +type Iterator = Iter | IterableIterator; + +/** +* Map function invoked for each iterated value. +* +* @returns iterator value +*/ +type Nullary = () => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @returns iterator value +*/ +type Unary = ( value: any ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @returns iterator value +*/ +type Binary = ( value: any, index: number ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @param src - source array-like object +* @returns iterator value +*/ +type Tertiary = ( value: any, index: number, src: ArrayLike ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @param src - source array-like object +* @returns iterator value +*/ +type MapFunction = Nullary | Unary | Binary | Tertiary; + +/** +* Returns an iterator which iterates over each element in a sparse array-like object. +* +* @param src - input value +* @param mapFcn - function to invoke for each iterated value +* @param thisArg - execution context +* @returns iterator +* +* @example +* var iter = sparsearray2iterator( [ 1, , 3, 4 ] ); +* +* var v = iter.next().value; +* // returns 1 +* +* v = iter.next().value; +* // returns 3 +* +* v = iter.next().value; +* // returns 4 +*/ +declare function sparsearray2iterator( src: ArrayLike, mapFcn?: MapFunction, thisArg?: any ): Iterator; // tslint:disable-line:max-line-length + + +// EXPORTS // + +export = sparsearray2iterator; diff --git a/to-sparse-iterator/docs/types/test.ts b/to-sparse-iterator/docs/types/test.ts new file mode 100644 index 00000000..226ad113 --- /dev/null +++ b/to-sparse-iterator/docs/types/test.ts @@ -0,0 +1,66 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import sparsearray2iterator = require( './index' ); + +/** +* Multiplies a value by 10. +* +* @param v - iterated value +* @returns new value +*/ +function times10( v: number ): number { + return v * 10.0; +} + + +// TESTS // + +// The function returns an iterator... +{ + sparsearray2iterator( [ 1, 2, 3, 4 ] ); // $ExpectType Iterator + sparsearray2iterator( [ 1, 2, 3, 4 ], times10 ); // $ExpectType Iterator + sparsearray2iterator( [ 1, 2, 3, 4 ], times10, {} ); // $ExpectType Iterator +} + +// The compiler throws an error if the function is provided a first argument which is not array-like... +{ + sparsearray2iterator( 123 ); // $ExpectError + sparsearray2iterator( true ); // $ExpectError + sparsearray2iterator( false ); // $ExpectError + sparsearray2iterator( {} ); // $ExpectError + sparsearray2iterator( null ); // $ExpectError + sparsearray2iterator( undefined ); // $ExpectError +} + +// The compiler throws an error if the function is provided a second argument which is not a map function... +{ + sparsearray2iterator( [ 1, 2, 3, 4 ], 'abc' ); // $ExpectError + sparsearray2iterator( [ 1, 2, 3, 4 ], 123 ); // $ExpectError + sparsearray2iterator( [ 1, 2, 3, 4 ], [] ); // $ExpectError + sparsearray2iterator( [ 1, 2, 3, 4 ], {} ); // $ExpectError + sparsearray2iterator( [ 1, 2, 3, 4 ], true ); // $ExpectError + sparsearray2iterator( [ 1, 2, 3, 4 ], false ); // $ExpectError + sparsearray2iterator( [ 1, 2, 3, 4 ], null ); // $ExpectError +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + sparsearray2iterator(); // $ExpectError + sparsearray2iterator( [ 1, 2, 3, 4 ], times10, {}, 123 ); // $ExpectError +} diff --git a/to-sparse-iterator/examples/index.js b/to-sparse-iterator/examples/index.js new file mode 100644 index 00000000..304c3b28 --- /dev/null +++ b/to-sparse-iterator/examples/index.js @@ -0,0 +1,46 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var randu = require( '@stdlib/random/base/randu' ); +var sparsearray2iterator = require( './../lib' ); + +function scale( v, i ) { + return v * (i+1); +} + +// Create an array partially filled with random numbers: +var arr = new Array( 100 ); +var i; +for ( i = 0; i < arr.length; i += 2 ) { + arr[ i ] = randu(); +} + +// Create an iterator from the array which scales iterated values: +var it = sparsearray2iterator( arr, scale ); + +// Perform manual iteration... +var v; +while ( true ) { + v = it.next(); + if ( v.done ) { + break; + } + console.log( v.value ); +} diff --git a/to-sparse-iterator/lib/index.js b/to-sparse-iterator/lib/index.js new file mode 100644 index 00000000..e237ca8f --- /dev/null +++ b/to-sparse-iterator/lib/index.js @@ -0,0 +1,48 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Create an iterator from a sparse array-like value. +* +* @module @stdlib/array/to-sparse-iterator +* +* @example +* var sparsearray2iterator = require( '@stdlib/array/to-sparse-iterator' ); +* +* var iter = sparsearray2iterator( [ 1, , 3, 4 ] ); +* +* var v = iter.next().value; +* // returns 1 +* +* v = iter.next().value; +* // returns 3 +* +* v = iter.next().value; +* // returns 4 +*/ + +// MODULES // + +var iterator = require( './main.js' ); + + +// EXPORTS // + +module.exports = iterator; diff --git a/to-sparse-iterator/lib/main.js b/to-sparse-iterator/lib/main.js new file mode 100644 index 00000000..a919cecf --- /dev/null +++ b/to-sparse-iterator/lib/main.js @@ -0,0 +1,183 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var isCollection = require( '@stdlib/assert/is-collection' ); +var iteratorSymbol = require( '@stdlib/symbol/iterator' ); + + +// MAIN // + +/** +* Returns an iterator which iterates over each element in a sparse array-like object. +* +* @param {Collection} src - input value +* @param {Function} [mapFcn] - function to invoke for each iterated value +* @param {*} [thisArg] - execution context +* @throws {TypeError} first argument must be an array-like object +* @throws {TypeError} second argument must be a function +* @returns {Iterator} iterator +* +* @example +* var iter = sparsearray2iterator( [ 1, , 3, 4 ] ); +* +* var v = iter.next().value; +* // returns 1 +* +* v = iter.next().value; +* // returns 3 +* +* v = iter.next().value; +* // returns 4 +*/ +function sparsearray2iterator( src ) { + var thisArg; + var iter; + var FLG; + var fcn; + var i; + if ( !isCollection( src ) ) { + throw new TypeError( 'invalid argument. First argument must be an array-like object. Value: `' + src + '`.' ); + } + if ( arguments.length > 1 ) { + fcn = arguments[ 1 ]; + if ( !isFunction( fcn ) ) { + throw new TypeError( 'invalid argument. Second argument must be a function. Value: `' + fcn + '`.' ); + } + thisArg = arguments[ 2 ]; + } + i = -1; + + // Create an iterator protocol-compliant object: + iter = {}; + if ( fcn ) { + setReadOnly( iter, 'next', next1 ); + } else { + setReadOnly( iter, 'next', next2 ); + } + setReadOnly( iter, 'return', end ); + + // If an environment supports `Symbol.iterator`, make the iterator iterable: + if ( iteratorSymbol ) { + setReadOnly( iter, iteratorSymbol, factory ); + } + return iter; + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next1() { + var len; + if ( FLG ) { + return { + 'done': true + }; + } + len = src.length; + i += 1; + while ( i < len && src[ i ] === void 0 ) { + i += 1; + } + if ( i >= len ) { + FLG = true; + return { + 'done': true + }; + } + return { + 'value': fcn.call( thisArg, src[ i ], i, src ), + 'done': false + }; + } + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next2() { + var len; + if ( FLG ) { + return { + 'done': true + }; + } + len = src.length; + i += 1; + while ( i < len && src[ i ] === void 0 ) { + i += 1; + } + if ( i >= len ) { + FLG = true; + return { + 'done': true + }; + } + return { + 'value': src[ i ], + 'done': false + }; + } + + /** + * Finishes an iterator. + * + * @private + * @param {*} [value] - value to return + * @returns {Object} iterator protocol-compliant object + */ + function end( value ) { + FLG = true; + if ( arguments.length ) { + return { + 'value': value, + 'done': true + }; + } + return { + 'done': true + }; + } + + /** + * Returns a new iterator. + * + * @private + * @returns {Iterator} iterator + */ + function factory() { + if ( fcn ) { + return sparsearray2iterator( src, fcn, thisArg ); + } + return sparsearray2iterator( src ); + } +} + + +// EXPORTS // + +module.exports = sparsearray2iterator; diff --git a/to-sparse-iterator/package.json b/to-sparse-iterator/package.json new file mode 100644 index 00000000..eb9e33c2 --- /dev/null +++ b/to-sparse-iterator/package.json @@ -0,0 +1,72 @@ +{ + "name": "@stdlib/array/to-sparse-iterator", + "version": "0.0.0", + "description": "Create an iterator from a sparse array-like object.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "utils", + "util", + "utilities", + "utility", + "typed", + "array", + "arr", + "sparse", + "holes", + "typed-array", + "typed array", + "iterator", + "iterate", + "iteration", + "iter", + "to", + "convert" + ] +} diff --git a/to-sparse-iterator/test/test.js b/to-sparse-iterator/test/test.js new file mode 100644 index 00000000..be9b4b1d --- /dev/null +++ b/to-sparse-iterator/test/test.js @@ -0,0 +1,730 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var iteratorSymbol = require( '@stdlib/symbol/iterator' ); +var noop = require( '@stdlib/utils/noop' ); +var sparsearray2iterator = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.equal( typeof sparsearray2iterator, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + sparsearray2iterator( value ); + }; + } +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object (callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + sparsearray2iterator( value, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a second argument which is not a function', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + [], + {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + sparsearray2iterator( [ 1, 2, 3, 4 ], value ); + }; + } +}); + +tape( 'the function returns an iterator protocol-compliant object', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, , , 4 ]; // eslint-disable-line no-sparse-arrays + expected = [ + { + 'value': 1, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'done': true + } + ]; + + it = sparsearray2iterator( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (empty array)', function test( t ) { + var expected; + var actual; + var values; + var it; + + values = new Array( 1e5 ); + expected = [ + { + 'done': true + } + ]; + + it = sparsearray2iterator( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (empty end)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = new Array( 4 ); + + // Leave the last element empty: + for ( i = 0; i < values.length-1; i++ ) { + values[ i ] = i + 1; + } + expected = [ + { + 'value': 1, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'done': true + } + ]; + + it = sparsearray2iterator( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-1; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (empty start)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = new Array( 4 ); + + // Leave the first element empty: + for ( i = 1; i < values.length; i++ ) { + values[ i ] = i + 1; + } + + expected = [ + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'done': true + } + ]; + + it = sparsearray2iterator( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-1; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (empty start+end)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = new Array( 4 ); + + // Leave the first and last elements empty: + for ( i = 1; i < values.length-1; i++ ) { + values[ i ] = i + 1; + } + + expected = [ + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'done': true + } + ]; + + it = sparsearray2iterator( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (array-like object)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = { + 'length': 4, + '1': 2, + '2': 3, + '3': 4 + }; + expected = [ + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'done': true + } + ]; + + it = sparsearray2iterator( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-1; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = new Array( 4 ); + + // Leave the last element empty: + for ( i = 0; i < values.length-1; i++ ) { + values[ i ] = i + 1; + } + + it = sparsearray2iterator( values, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length-1; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length-1, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (array-like)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = { + 'length': 4, + '0': 1, + '1': 2, + '3': 4 + }; + + it = sparsearray2iterator( values, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length-1; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length-1, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object', function test( t ) { + var expected; + var values; + var actual; + var it; + var i; + + values = [ 1, , 3, 4 ]; // eslint-disable-line no-sparse-arrays + expected = [ + { + 'value': 1, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'done': true + } + ]; + + it = sparsearray2iterator( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-1; i++ ) { + actual.push( it.next() ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (callback)', function test( t ) { + var expected; + var values; + var actual; + var it; + var i; + + values = [ 1, 2, , 4 ]; // eslint-disable-line no-sparse-arrays + expected = [ + { + 'value': 1, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'value': 16, + 'done': false + }, + { + 'done': true + } + ]; + + it = sparsearray2iterator( values, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-1; i++ ) { + actual.push( it.next() ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (no argument)', function test( t ) { + var it; + var r; + + it = sparsearray2iterator( [ 1, 2, 3, 4 ] ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (no argument; callback)', function test( t ) { + var it; + var r; + + it = sparsearray2iterator( [ 1, 2, 3, 4 ], scale ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (argument)', function test( t ) { + var it; + var r; + + it = sparsearray2iterator( [ 1, 2, 3, 4 ] ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return( 'finished' ); + t.equal( r.value, 'finished', 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (argument; callback)', function test( t ) { + var it; + var r; + + it = sparsearray2iterator( [ 1, 2, 3, 4 ], scale ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return( 'finished' ); + t.equal( r.value, 'finished', 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable', function test( t ) { + var sparsearray2iterator; + var values; + var it1; + var it2; + var i; + + sparsearray2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = sparsearray2iterator( values ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable (callback)', function test( t ) { + var sparsearray2iterator; + var values; + var it1; + var it2; + var i; + + sparsearray2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = sparsearray2iterator( values, scale ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); + + function scale( v ) { + return v * 10.0; + } +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable"', function test( t ) { + var sparsearray2iterator; + var it; + + sparsearray2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = sparsearray2iterator( [ 1, 2, 3, 4 ] ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable" (callback)', function test( t ) { + var sparsearray2iterator; + var it; + + sparsearray2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = sparsearray2iterator( [ 1, 2, 3, 4 ], scale ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); diff --git a/to-strided-iterator/README.md b/to-strided-iterator/README.md new file mode 100644 index 00000000..f1eec064 --- /dev/null +++ b/to-strided-iterator/README.md @@ -0,0 +1,225 @@ + + +# Strided Iterator + +> Create an [iterator][mdn-iterator-protocol] from a strided array-like object. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var stridedarray2iterator = require( '@stdlib/array/to-strided-iterator' ); +``` + +#### stridedarray2iterator( N, src, stride, offset\[, mapFcn\[, thisArg]] ) + +Returns an [iterator][mdn-iterator-protocol] which iterates over elements in an array-like `object` according to specified stride parameters. + +```javascript +var values = [ 1, 2, 3, 4, 5, 6, 7, 8 ]; + +var N = 4; +var stride = -2; +var offset = 6; + +var it = stridedarray2iterator( N, values, stride, offset ); +// returns + +var v = it.next().value; +// returns 7 + +v = it.next().value; +// returns 5 + +v = it.next().value; +// returns 3 + +// ... +``` + +The returned [iterator][mdn-iterator-protocol] protocol-compliant object has the following properties: + +- **next**: function which returns an [iterator][mdn-iterator-protocol] protocol-compliant object containing the next iterated value (if one exists) assigned to a `value` property and a `done` property having a `boolean` value indicating whether the [iterator][mdn-iterator-protocol] is finished. +- **return**: function which closes an [iterator][mdn-iterator-protocol] and returns a single (optional) argument in an iterator protocol-compliant object. + +To invoke a function for each `src` value, provide a callback function. + +```javascript +function fcn( v ) { + return v * 10.0; +} + +var it = stridedarray2iterator( 4, [ 1, 2, 3, 4 ], 1, 0, fcn ); +// returns + +var v = it.next().value; +// returns 10.0 + +v = it.next().value; +// returns 20.0 + +v = it.next().value; +// returns 30.0 + +// ... +``` + +The invoked function is provided four arguments: + +- `value`: iterated value +- `index`: iterated value index +- `n`: iteration count (zero-based) +- `src`: source array-like object + +```javascript +function fcn( v, i ) { + return v * (i+1); +} + +var it = stridedarray2iterator( 4, [ 1, 2, 3, 4 ], 1, 0, fcn ); +// returns + +var v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 4 + +v = it.next().value; +// returns 9 + +// ... +``` + +To set the callback function execution context, provide a `thisArg`. + +```javascript +function fcn( v ) { + this.count += 1; + return v * 10.0; +} + +var ctx = { + 'count': 0 +}; + +var it = stridedarray2iterator( 4, [ 1, 2, 3, 4 ], 1, 0, fcn, ctx ); +// returns + +var v = it.next().value; +// returns 10.0 + +v = it.next().value; +// returns 20.0 + +v = it.next().value; +// returns 30.0 + +var count = ctx.count; +// returns 3 +``` + + + + + + + +
+ +## Notes + +- If an environment supports `Symbol.iterator`, the returned [iterator][mdn-iterator-protocol] is iterable. +- If provided a generic `array`, the returned [iterator][mdn-iterator-protocol] does **not** ignore holes. To achieve greater performance for sparse arrays, use a custom [iterator][mdn-iterator-protocol]. +- A returned [iterator][mdn-iterator-protocol] does **not** copy a provided array-like `object`. To ensure iterable reproducibility, copy a provided array-like `object` **before** creating an [iterator][mdn-iterator-protocol]. Otherwise, any changes to the contents of an array-like `object` will be reflected in the returned [iterator][mdn-iterator-protocol]. +- In environments supporting `Symbol.iterator`, the function **explicitly** does **not** invoke an array's `@@iterator` method, regardless of whether this method is defined. To convert an array to an implementation defined [iterator][mdn-iterator-protocol], invoke this method directly. + +
+ + + + + +
+ +## Examples + + + +```javascript +var Float64Array = require( '@stdlib/array/float64' ); +var inmap = require( '@stdlib/utils/inmap' ); +var randu = require( '@stdlib/random/base/randu' ); +var stridedarray2iterator = require( '@stdlib/array/to-strided-iterator' ); + +function scale( v, i ) { + return v * (i+1); +} + +// Create an array filled with random numbers: +var arr = inmap( new Float64Array( 100 ), randu ); + +// Create an iterator which scales every fourth value in reverse order: +var it = stridedarray2iterator( 25, arr, -4, 99, scale ); + +// Perform manual iteration... +var v; +while ( true ) { + v = it.next(); + if ( v.done ) { + break; + } + console.log( v.value ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/to-strided-iterator/benchmark/benchmark.js b/to-strided-iterator/benchmark/benchmark.js new file mode 100644 index 00000000..1a4b1da4 --- /dev/null +++ b/to-strided-iterator/benchmark/benchmark.js @@ -0,0 +1,115 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isnan = require( '@stdlib/math/base/assert/is-nan' ); +var isIteratorLike = require( '@stdlib/assert/is-iterator-like' ); +var pkg = require( './../package.json' ).name; +var stridedarray2iterator = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var values; + var iter; + var N; + var i; + + values = [ 1, 2, 3, 4 ]; + N = values.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + values[ 0 ] = i; + iter = stridedarray2iterator( N, values, 1, 0 ); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isIteratorLike( iter ) ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::iteration', function benchmark( b ) { + var values; + var iter; + var N; + var z; + var i; + + values = []; + values.length = b.iterations; + N = values.length; + + iter = stridedarray2iterator( N, values, 1, 0 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + z = iter.next().value; + if ( z !== void 0 ) { + b.fail( 'should be undefined' ); + } + } + b.toc(); + if ( z !== void 0 ) { + b.fail( 'should be undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::iteration,map', function benchmark( b ) { + var values; + var iter; + var N; + var z; + var i; + + values = []; + values.length = b.iterations; + N = values.length; + + iter = stridedarray2iterator( N, values, 1, 0, transform ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + z = iter.next().value; + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function transform( v, i ) { + return i; + } +}); diff --git a/to-strided-iterator/docs/repl.txt b/to-strided-iterator/docs/repl.txt new file mode 100644 index 00000000..33944c6d --- /dev/null +++ b/to-strided-iterator/docs/repl.txt @@ -0,0 +1,64 @@ + +{{alias}}( N, src, stride, offset[, mapFcn[, thisArg]] ) + Returns an iterator which iterates over elements of an array-like object + according to specified stride parameters. + + When invoked, an input function is provided four arguments: + + - value: iterated value + - index: iterated value index + - n: iteration count (zero-based) + - src: source array-like object + + If an environment supports Symbol.iterator, the returned iterator is + iterable. + + If an environment supports Symbol.iterator, the function explicitly does not + not invoke an array's `@@iterator` method, regardless of whether this method + is defined. To convert an array to an implementation defined iterator, + invoke this method directly. + + Parameters + ---------- + N: integer + Number of values to iterate. + + src: ArrayLikeObject + Array-like object from which to create the iterator. + + stride: integer + Stride length. + + offset: integer + Starting index. + + mapFcn: Function (optional) + Function to invoke for each iterated value. + + thisArg: any (optional) + Execution context. + + Returns + ------- + iterator: Object + Iterator. + + iterator.next(): Function + Returns an iterator protocol-compliant object containing the next + iterated value (if one exists) and a boolean flag indicating whether the + iterator is finished. + + iterator.return( [value] ): Function + Finishes an iterator and returns a provided value. + + Examples + -------- + > var it = {{alias}}( 2, [ 1, 2, 3, 4 ], -2, 3 ); + > var v = it.next().value + 4 + > v = it.next().value + 2 + + See Also + -------- + diff --git a/to-strided-iterator/docs/types/index.d.ts b/to-strided-iterator/docs/types/index.d.ts new file mode 100644 index 00000000..bbc1b567 --- /dev/null +++ b/to-strided-iterator/docs/types/index.d.ts @@ -0,0 +1,124 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/// + +import { Iterator as Iter, IterableIterator } from '@stdlib/types/iter'; +import { ArrayLike } from '@stdlib/types/array'; + +// Define a union type representing both iterable and non-iterable iterators: +type Iterator = Iter | IterableIterator; + +/** +* Map function invoked for each iterated value. +* +* @returns iterator value +*/ +type Nullary = () => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @returns iterator value +*/ +type Unary = ( value: any ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @returns iterator value +*/ +type Binary = ( value: any, index: number ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @param n - iteration count (zero-based) +* @returns iterator value +*/ +type Tertiary = ( value: any, index: number, n: number ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @param n - iteration count (zero-based) +* @param src - source array-like object +* @returns iterator value +*/ +type Quaternary = ( value: any, index: number, n: number, src: ArrayLike ) => any; // tslint:disable-line:max-line-length + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @param n - iteration count (zero-based) +* @param src - source array-like object +* @returns iterator value +*/ +type MapFunction = Nullary | Unary | Binary | Tertiary | Quaternary; + +/** +* Returns an iterator which iterates over elements in an array-like object according to specified stride parameters. +* +* @param N - number of values to iterate +* @param src - input value +* @param stride - stride length +* @param offset - starting index +* @param mapFcn - function to invoke for each iterated value +* @param thisArg - execution context +* @throws first argument must be a nonnegative integer +* @throws third argument must be an integer +* @throws fourth argument must be a nonnegative integer +* @returns iterator +* +* @example +* var values = [ 1, 2, 3, 4, 5, 6, 7, 8 ]; +* +* var N = 4; +* var stride = -2; +* var offset = 6; +* +* var iter = stridedarray2iterator( N, values, stride, offset ); +* +* var v = iter.next().value; +* // returns 7 +* +* v = iter.next().value; +* // returns 5 +* +* v = iter.next().value; +* // returns 3 +* +* // ... +*/ +declare function stridedarray2iterator( N: number, src: ArrayLike, stride: number, offset: number, mapFcn?: MapFunction, thisArg?: any ): Iterator; // tslint:disable-line:max-line-length + + +// EXPORTS // + +export = stridedarray2iterator; diff --git a/to-strided-iterator/docs/types/test.ts b/to-strided-iterator/docs/types/test.ts new file mode 100644 index 00000000..721a86d4 --- /dev/null +++ b/to-strided-iterator/docs/types/test.ts @@ -0,0 +1,99 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import stridedarray2iterator = require( './index' ); + +/** +* Multiplies a value by 10. +* +* @param v - iterated value +* @returns new value +*/ +function times10( v: number ): number { + return v * 10.0; +} + + +// TESTS // + +// The function returns an iterator... +{ + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], -2, 3 ); // $ExpectType Iterator + stridedarray2iterator( 4, [ 1, 2, 3, 4, 5, 6, 7, 8 ], -2, 6, times10 ); // $ExpectType Iterator + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], -2, 3, times10, {} ); // $ExpectType Iterator +} + +// The compiler throws an error if the function is provided a first argument which is not a number... +{ + stridedarray2iterator( 'abc', [ 1, 2, 3, 4 ], -2, 3 ); // $ExpectError + stridedarray2iterator( true, [ 1, 2, 3, 4 ], -2, 3 ); // $ExpectError + stridedarray2iterator( false, [ 1, 2, 3, 4 ], -2, 3 ); // $ExpectError + stridedarray2iterator( {}, [ 1, 2, 3, 4 ], -2, 3 ); // $ExpectError + stridedarray2iterator( null, [ 1, 2, 3, 4 ], -2, 3 ); // $ExpectError + stridedarray2iterator( undefined, [ 1, 2, 3, 4 ], -2, 3 ); // $ExpectError +} + +// The compiler throws an error if the function is provided a second argument which is not array-like... +{ + stridedarray2iterator( 2, 123, -2, 3 ); // $ExpectError + stridedarray2iterator( 2, true, -2, 3 ); // $ExpectError + stridedarray2iterator( 2, false, -2, 3 ); // $ExpectError + stridedarray2iterator( 2, {}, -2, 3 ); // $ExpectError + stridedarray2iterator( 2, null, -2, 3 ); // $ExpectError + stridedarray2iterator( 2, undefined, -2, 3 ); // $ExpectError +} + +// The compiler throws an error if the function is provided a third argument which is not a number... +{ + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], 'abc', 3 ); // $ExpectError + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], true, 3 ); // $ExpectError + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], false, 3 ); // $ExpectError + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], {}, 3 ); // $ExpectError + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], null, 3 ); // $ExpectError + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], undefined, 3 ); // $ExpectError +} + +// The compiler throws an error if the function is provided a fourth argument which is not a number... +{ + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], -2, 'abc' ); // $ExpectError + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], -2, true ); // $ExpectError + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], -2, false ); // $ExpectError + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], -2, {} ); // $ExpectError + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], -2, null ); // $ExpectError + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], -2, undefined ); // $ExpectError +} + +// The compiler throws an error if the function is provided a fifth argument which is not a map function... +{ + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], -2, 3, 'abc' ); // $ExpectError + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], -2, 3, 123 ); // $ExpectError + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], -2, 3, [] ); // $ExpectError + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], -2, 3, {} ); // $ExpectError + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], -2, 3, true ); // $ExpectError + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], -2, 3, false ); // $ExpectError + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], -2, 3, null ); // $ExpectError +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + stridedarray2iterator(); // $ExpectError + stridedarray2iterator( 2 ); // $ExpectError + stridedarray2iterator( 2, [ 1, 2, 3, 4 ] ); // $ExpectError + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], -2 ); // $ExpectError + stridedarray2iterator( 2, [ 1, 2, 3, 4 ], -2, 3, times10, {}, 123 ); // $ExpectError +} diff --git a/to-strided-iterator/examples/index.js b/to-strided-iterator/examples/index.js new file mode 100644 index 00000000..6e75d758 --- /dev/null +++ b/to-strided-iterator/examples/index.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var Float64Array = require( '@stdlib/array/float64' ); +var inmap = require( '@stdlib/utils/inmap' ); +var randu = require( '@stdlib/random/base/randu' ); +var stridedarray2iterator = require( './../lib' ); + +function scale( v, i ) { + return v * (i+1); +} + +// Create an array filled with random numbers: +var arr = inmap( new Float64Array( 100 ), randu ); + +// Create an iterator which scales every fourth value in reverse order: +var it = stridedarray2iterator( 25, arr, -4, 99, scale ); + +// Perform manual iteration... +var v; +while ( true ) { + v = it.next(); + if ( v.done ) { + break; + } + console.log( v.value ); +} diff --git a/to-strided-iterator/lib/index.js b/to-strided-iterator/lib/index.js new file mode 100644 index 00000000..38d17fa5 --- /dev/null +++ b/to-strided-iterator/lib/index.js @@ -0,0 +1,56 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Create an iterator from a strided array-like value. +* +* @module @stdlib/array/to-strided-iterator +* +* @example +* var stridedarray2iterator = require( '@stdlib/array/to-strided-iterator' ); +* +* var values = [ 1, 2, 3, 4, 5, 6, 7, 8 ]; +* +* var N = 4; +* var stride = -2; +* var offset = 6; +* +* var iter = stridedarray2iterator( N, values, stride, offset ); +* +* var v = iter.next().value; +* // returns 7 +* +* v = iter.next().value; +* // returns 5 +* +* v = iter.next().value; +* // returns 3 +* +* // ... +*/ + +// MODULES // + +var iterator = require( './main.js' ); + + +// EXPORTS // + +module.exports = iterator; diff --git a/to-strided-iterator/lib/main.js b/to-strided-iterator/lib/main.js new file mode 100644 index 00000000..9f1c9b5a --- /dev/null +++ b/to-strided-iterator/lib/main.js @@ -0,0 +1,194 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var isCollection = require( '@stdlib/assert/is-collection' ); +var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; +var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; +var iteratorSymbol = require( '@stdlib/symbol/iterator' ); + + +// MAIN // + +/** +* Returns an iterator which iterates over elements in an array-like object according to specified stride parameters. +* +* @param {NonNegativeInteger} N - number of values to iterate +* @param {Collection} src - input value +* @param {integer} stride - stride length +* @param {NonNegativeInteger} offset - starting index +* @param {Function} [mapFcn] - function to invoke for each iterated value +* @param {*} [thisArg] - execution context +* @throws {TypeError} first argument must be a nonnegative integer +* @throws {TypeError} second argument must be an array-like object +* @throws {TypeError} third argument must be an integer +* @throws {TypeError} fourth argument must be a nonnegative integer +* @throws {TypeError} fifth argument must be a function +* @returns {Iterator} iterator +* +* @example +* var values = [ 1, 2, 3, 4, 5, 6, 7, 8 ]; +* +* var N = 4; +* var stride = -2; +* var offset = 6; +* +* var iter = stridedarray2iterator( N, values, stride, offset ); +* +* var v = iter.next().value; +* // returns 7 +* +* v = iter.next().value; +* // returns 5 +* +* v = iter.next().value; +* // returns 3 +* +* // ... +*/ +function stridedarray2iterator( N, src, stride, offset ) { + var thisArg; + var iter; + var FLG; + var fcn; + var idx; + var i; + if ( !isNonNegativeInteger( N ) ) { + throw new TypeError( 'invalid argument. First argument must be a nonnegative integer. Value: `' + N + '`.' ); + } + if ( !isCollection( src ) ) { + throw new TypeError( 'invalid argument. Second argument must be an array-like object. Value: `' + src + '`.' ); + } + if ( !isInteger( stride ) ) { + throw new TypeError( 'invalid argument. Third argument must be an integer. Value: `' + stride + '`.' ); + } + if ( !isNonNegativeInteger( offset ) ) { + throw new TypeError( 'invalid argument. Fourth argument must be a nonnegative integer. Value: `' + offset + '`.' ); + } + if ( arguments.length > 4 ) { + fcn = arguments[ 4 ]; + if ( !isFunction( fcn ) ) { + throw new TypeError( 'invalid argument. Fifth argument must be a function. Value: `' + fcn + '`.' ); + } + thisArg = arguments[ 5 ]; + } + idx = offset; + i = -1; + + // Create an iterator protocol-compliant object: + iter = {}; + if ( fcn ) { + setReadOnly( iter, 'next', next1 ); + } else { + setReadOnly( iter, 'next', next2 ); + } + setReadOnly( iter, 'return', end ); + + // If an environment supports `Symbol.iterator`, make the iterator iterable: + if ( iteratorSymbol ) { + setReadOnly( iter, iteratorSymbol, factory ); + } + return iter; + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next1() { + var v; + i += 1; + if ( FLG || i >= N ) { + return { + 'done': true + }; + } + v = fcn.call( thisArg, src[ idx ], idx, i, src ); + idx += stride; + return { + 'value': v, + 'done': false + }; + } + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next2() { + var v; + i += 1; + if ( FLG || i >= N ) { + return { + 'done': true + }; + } + v = src[ idx ]; + idx += stride; + return { + 'value': v, + 'done': false + }; + } + + /** + * Finishes an iterator. + * + * @private + * @param {*} [value] - value to return + * @returns {Object} iterator protocol-compliant object + */ + function end( value ) { + FLG = true; + if ( arguments.length ) { + return { + 'value': value, + 'done': true + }; + } + return { + 'done': true + }; + } + + /** + * Returns a new iterator. + * + * @private + * @returns {Iterator} iterator + */ + function factory() { + if ( fcn ) { + return stridedarray2iterator( N, src, stride, offset, fcn, thisArg ); // eslint-disable-line max-len + } + return stridedarray2iterator( N, src, stride, offset ); + } +} + + +// EXPORTS // + +module.exports = stridedarray2iterator; diff --git a/to-strided-iterator/package.json b/to-strided-iterator/package.json new file mode 100644 index 00000000..6cf7f0ab --- /dev/null +++ b/to-strided-iterator/package.json @@ -0,0 +1,75 @@ +{ + "name": "@stdlib/array/to-strided-iterator", + "version": "0.0.0", + "description": "Create an iterator from a strided array-like object.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "utils", + "util", + "utilities", + "utility", + "typed", + "array", + "arr", + "typed-array", + "typed array", + "iterator", + "iterate", + "iteration", + "iter", + "to", + "convert", + "strided", + "stride", + "view", + "ndarray", + "multidimensional" + ] +} diff --git a/to-strided-iterator/test/test.js b/to-strided-iterator/test/test.js new file mode 100644 index 00000000..348005e1 --- /dev/null +++ b/to-strided-iterator/test/test.js @@ -0,0 +1,760 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var iteratorSymbol = require( '@stdlib/symbol/iterator' ); +var noop = require( '@stdlib/utils/noop' ); +var stridedarray2iterator = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.equal( typeof stridedarray2iterator, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error if provided a first argument which is not a nonnegative integer', function test( t ) { + var values; + var i; + + values = [ + '5', + -5, + 3.14, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + stridedarray2iterator( value, [ 1, 2, 3 ], 1, 0 ); + }; + } +}); + +tape( 'the function throws an error if provided a first argument which is not a nonnegative integer (callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + -5, + 3.14, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + stridedarray2iterator( value, [ 1, 2, 3 ], 1, 0, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a second argument which is not an array-like object', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + stridedarray2iterator( 1, value, 1, 0 ); + }; + } +}); + +tape( 'the function throws an error if provided a second argument which is not an array-like object (callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + stridedarray2iterator( 1, value, 1, 0, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a third argument which is not an integer', function test( t ) { + var values; + var i; + + values = [ + '5', + 3.14, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + stridedarray2iterator( 1, [ 1, 2, 3 ], value, 0 ); + }; + } +}); + +tape( 'the function throws an error if provided a third argument which is not an integer (callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 3.14, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + stridedarray2iterator( 1, [ 1, 2, 3 ], value, 0, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a fourth argument which is not a nonnegative integer', function test( t ) { + var values; + var i; + + values = [ + '5', + -5, + 3.14, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + stridedarray2iterator( 1, [ 1, 2, 3 ], 1, value ); + }; + } +}); + +tape( 'the function throws an error if provided a fourth argument which is not a nonnegative integer (callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + -5, + 3.14, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + stridedarray2iterator( 1, [ 1, 2, 3 ], 1, value, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a fifth argument which is not a function', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + [], + {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + stridedarray2iterator( 1, [ 1, 2, 3, 4 ], 1, 0, value ); + }; + } +}); + +tape( 'the function returns an iterator protocol-compliant object', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4, 5, 6, 7, 8 ]; + expected = [ + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'value': 5, + 'done': false + }, + { + 'value': 6, + 'done': false + }, + { + 'done': true + } + ]; + + it = stridedarray2iterator( 4, values, 1, 2 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < 4; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (array-like object)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = { + 'length': 8, + '0': 1, + '1': 2, + '2': 3, + '3': 4, + '4': 5, + '5': 6, + '6': 7, + '7': 8 + }; + expected = [ + { + 'value': 8, + 'done': false + }, + { + 'value': 7, + 'done': false + }, + { + 'value': 6, + 'done': false + }, + { + 'value': 5, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'done': true + } + ]; + + it = stridedarray2iterator( 5, values, -1, 7 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < 5; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + + it = stridedarray2iterator( 4, values, -1, 3, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = [ 4, 6, 6, 4 ]; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i, n ) { + v *= n + 1; + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (array-like)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = { + 'length': 4, + '0': 1, + '1': 2, + '2': 3, + '3': 4 + }; + + it = stridedarray2iterator( 4, values, 1, 0, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = [ 1, 4, 9, 16 ]; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object', function test( t ) { + var expected; + var values; + var actual; + var it; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 1, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'done': true + } + ]; + + it = stridedarray2iterator( 4, values, 1, 0 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length; i++ ) { + actual.push( it.next() ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (callback)', function test( t ) { + var expected; + var values; + var actual; + var it; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 1, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'value': 9, + 'done': false + }, + { + 'value': 16, + 'done': false + }, + { + 'done': true + } + ]; + + it = stridedarray2iterator( 4, values, 1, 0, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length; i++ ) { + actual.push( it.next() ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (no argument)', function test( t ) { + var it; + var r; + + it = stridedarray2iterator( 4, [ 1, 2, 3, 4 ], 1, 0 ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (no argument; callback)', function test( t ) { + var it; + var r; + + it = stridedarray2iterator( 4, [ 1, 2, 3, 4 ], 1, 0, scale ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (argument)', function test( t ) { + var it; + var r; + + it = stridedarray2iterator( 4, [ 1, 2, 3, 4 ], 1, 0 ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return( 'finished' ); + t.equal( r.value, 'finished', 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (argument; callback)', function test( t ) { + var it; + var r; + + it = stridedarray2iterator( 4, [ 1, 2, 3, 4 ], 1, 0, scale ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return( 'finished' ); + t.equal( r.value, 'finished', 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable', function test( t ) { + var stridedarray2iterator; + var values; + var it1; + var it2; + var i; + + stridedarray2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = stridedarray2iterator( 4, values, 1, 0 ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable (callback)', function test( t ) { + var stridedarray2iterator; + var values; + var it1; + var it2; + var i; + + stridedarray2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = stridedarray2iterator( 4, values, 1, 0, scale ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); + + function scale( v ) { + return v * 10.0; + } +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable"', function test( t ) { + var stridedarray2iterator; + var it; + + stridedarray2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = stridedarray2iterator( 4, [ 1, 2, 3, 4 ], 1, 0 ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable" (callback)', function test( t ) { + var stridedarray2iterator; + var it; + + stridedarray2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = stridedarray2iterator( 4, [ 1, 2, 3, 4 ], 1, 0, scale ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); diff --git a/to-view-iterator-right/README.md b/to-view-iterator-right/README.md new file mode 100644 index 00000000..048ad6d4 --- /dev/null +++ b/to-view-iterator-right/README.md @@ -0,0 +1,293 @@ + + +# arrayview2iteratorRight + +> Create an iterator from an array-like object view, iterating from right to left. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var arrayview2iteratorRight = require( '@stdlib/array/to-view-iterator-right' ); +``` + +#### arrayview2iteratorRight( src\[, begin\[, end]]\[, mapFcn\[, thisArg]] ) + +Returns an iterator which iterates from right to left over each element in an array-like `object` view. + +```javascript +var it = arrayview2iteratorRight( [ 1, 2, 3, 4 ] ); +// returns + +var v = it.next().value; +// returns 4 + +v = it.next().value; +// returns 3 + +v = it.next().value; +// returns 2 + +// ... +``` + +The returned iterator protocol-compliant object has the following properties: + +- **next**: function which returns an iterator protocol-compliant object containing the next iterated value (if one exists) assigned to a `value` property and a `done` property having a `boolean` value indicating whether the iterator is finished. +- **return**: function which closes an iterator and returns a single (optional) argument in an iterator protocol-compliant object. + +The `begin` and `end` arguments define the starting (inclusive) and ending (non-inclusive) indices of the array view. By default, the returned iterator starts iterating from the last element in an array-like `object` (i.e., from the "end"). To specify an alternative view end, provide an `end` argument (non-inclusive). + +```javascript +var it = arrayview2iteratorRight( [ 1, 2, 3, 4 ], 0, 3 ); +// returns + +var v = it.next().value; +// returns 3 + +v = it.next().value; +// returns 2 + +v = it.next().value; +// returns 1 + +var bool = it.next().done; +// returns true +``` + +If `end` is less than `0`, the first iterated value is resolved relative to the last view element. For example, the following generates the same behavior as in the previous example + +```javascript +var it = arrayview2iteratorRight( [ 1, 2, 3, 4 ], 0, -1 ); +// returns + +var v = it.next().value; +// returns 3 + +v = it.next().value; +// returns 2 + +v = it.next().value; +// returns 1 + +var bool = it.next().done; +// returns true +``` + +By default, the returned iterator iterates through the first element in an array-like `object` view. To specify an alternative view beginning, provide a `begin` argument (inclusive). + +```javascript +var it = arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1 ); +// returns + +var v = it.next().value; +// returns 4 + +v = it.next().value; +// returns 3 + +v = it.next().value; +// returns 2 + +var bool = it.next().done; +// returns true +``` + +If `begin` is less than `0`, the last iterated value is resolved relative to the last view element. For example, the following generates the same behavior as in the previous example + +```javascript +var it = arrayview2iteratorRight( [ 1, 2, 3, 4 ], -3 ); +// returns + +var v = it.next().value; +// returns 4 + +v = it.next().value; +// returns 3 + +v = it.next().value; +// returns 2 + +var bool = it.next().done; +// returns true +``` + +To invoke a function for each `src` value, provide a callback function. + +```javascript +function fcn( v ) { + return v * 10.0; +} + +var it = arrayview2iteratorRight( [ 1, 2, 3, 4 ], fcn ); +// returns + +var v = it.next().value; +// returns 40.0 + +v = it.next().value; +// returns 30.0 + +v = it.next().value; +// returns 20.0 + +// ... +``` + +The invoked function is provided four arguments: + +- `value`: iterated value +- `index`: iterated value index +- `n`: iteration count (zero-based) +- `src`: source array-like object + +```javascript +function fcn( v, i ) { + return v * (i+1); +} + +var it = arrayview2iteratorRight( [ 1, 2, 3, 4 ], fcn ); +// returns + +var v = it.next().value; +// returns 16 + +v = it.next().value; +// returns 9 + +v = it.next().value; +// returns 4 + +// ... +``` + +To set the callback function execution context, provide a `thisArg`. + +```javascript +function fcn( v ) { + this.count += 1; + return v * 10.0; +} + +var ctx = { + 'count': 0 +}; + +var it = arrayview2iteratorRight( [ 1, 2, 3, 4 ], fcn, ctx ); +// returns + +var v = it.next().value; +// returns 40.0 + +v = it.next().value; +// returns 30.0 + +v = it.next().value; +// returns 20.0 + +var count = ctx.count; +// returns 3 +``` + + + + + + + +
+ +## Notes + +- If an environment supports `Symbol.iterator`, the returned iterator is iterable. +- If provided a generic `array`, the returned iterator does **not** ignore holes. To achieve greater performance for sparse arrays, use a custom iterator. +- A returned iterator does **not** copy a provided array-like `object`. To ensure iterable reproducibility, copy a provided array-like `object` **before** creating an iterator. Otherwise, any changes to the contents of an array-like `object` will be reflected in the returned iterator. +- In environments supporting `Symbol.iterator`, the function **explicitly** does **not** invoke an array's `@@iterator` method, regardless of whether this method is defined. To convert an array to an implementation defined iterator, invoke this method directly. + +
+ + + + + +
+ +## Examples + + + +```javascript +var Float64Array = require( '@stdlib/array/float64' ); +var inmap = require( '@stdlib/utils/inmap' ); +var randu = require( '@stdlib/random/base/randu' ); +var arrayview2iteratorRight = require( '@stdlib/array/to-view-iterator-right' ); + +function scale( v, i ) { + return v * (i+1); +} + +// Create an array filled with random numbers: +var arr = inmap( new Float64Array( 100 ), randu ); + +// Create an iterator from an array view which scales iterated values: +var it = arrayview2iteratorRight( arr, 40, 60, scale ); + +// Perform manual iteration... +var v; +while ( true ) { + v = it.next(); + if ( v.done ) { + break; + } + console.log( v.value ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/to-view-iterator-right/benchmark/benchmark.js b/to-view-iterator-right/benchmark/benchmark.js new file mode 100644 index 00000000..699761b0 --- /dev/null +++ b/to-view-iterator-right/benchmark/benchmark.js @@ -0,0 +1,109 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isnan = require( '@stdlib/math/base/assert/is-nan' ); +var isIteratorLike = require( '@stdlib/assert/is-iterator-like' ); +var pkg = require( './../package.json' ).name; +var arrayview2iteratorRight = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var values; + var iter; + var i; + + values = [ 1, 2, 3, 4 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + values[ 0 ] = i; + iter = arrayview2iteratorRight( values ); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isIteratorLike( iter ) ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::iteration', function benchmark( b ) { + var values; + var iter; + var z; + var i; + + values = []; + values.length = b.iterations; + + iter = arrayview2iteratorRight( values ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + z = iter.next().value; + if ( z !== void 0 ) { + b.fail( 'should be undefined' ); + } + } + b.toc(); + if ( z !== void 0 ) { + b.fail( 'should be undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::iteration,map', function benchmark( b ) { + var values; + var iter; + var z; + var i; + + values = []; + values.length = b.iterations; + + iter = arrayview2iteratorRight( values, transform ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + z = iter.next().value; + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function transform( v, i ) { + return i; + } +}); diff --git a/to-view-iterator-right/docs/repl.txt b/to-view-iterator-right/docs/repl.txt new file mode 100644 index 00000000..7acb811f --- /dev/null +++ b/to-view-iterator-right/docs/repl.txt @@ -0,0 +1,63 @@ + +{{alias}}( src[, begin[, end]][, mapFcn[, thisArg]] ) + Returns an iterator which iterates from right to left over the elements of + an array-like object view. + + When invoked, an input function is provided four arguments: + + - value: iterated value + - index: iterated value index + - n: iteration count (zero-based) + - src: source array-like object + + If an environment supports Symbol.iterator, the returned iterator is + iterable. + + If an environment supports Symbol.iterator, the function explicitly does not + not invoke an array's `@@iterator` method, regardless of whether this method + is defined. To convert an array to an implementation defined iterator, + invoke this method directly. + + Parameters + ---------- + src: ArrayLikeObject + Array-like object from which to create the iterator. + + begin: integer (optional) + Starting index (inclusive). When negative, determined relative to the + last element. Default: 0. + + end: integer (optional) + Ending index (non-inclusive). When negative, determined relative to the + last element. Default: src.length. + + mapFcn: Function (optional) + Function to invoke for each iterated value. + + thisArg: any (optional) + Execution context. + + Returns + ------- + iterator: Object + Iterator. + + iterator.next(): Function + Returns an iterator protocol-compliant object containing the next + iterated value (if one exists) and a boolean flag indicating whether the + iterator is finished. + + iterator.return( [value] ): Function + Finishes an iterator and returns a provided value. + + Examples + -------- + > var it = {{alias}}( [ 1, 2, 3, 4 ], 1, 3 ); + > var v = it.next().value + 3 + > v = it.next().value + 2 + + See Also + -------- + diff --git a/to-view-iterator-right/docs/types/index.d.ts b/to-view-iterator-right/docs/types/index.d.ts new file mode 100644 index 00000000..1457634a --- /dev/null +++ b/to-view-iterator-right/docs/types/index.d.ts @@ -0,0 +1,149 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/// + +import { Iterator as Iter, IterableIterator } from '@stdlib/types/iter'; +import { ArrayLike } from '@stdlib/types/array'; + +// Define a union type representing both iterable and non-iterable iterators: +type Iterator = Iter | IterableIterator; + +/** +* Map function invoked for each iterated value. +* +* @returns iterator value +*/ +type Nullary = () => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @returns iterator value +*/ +type Unary = ( value: any ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @returns iterator value +*/ +type Binary = ( value: any, index: number ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @param src - source array-like object +* @returns iterator value +*/ +type Tertiary = ( value: any, index: number, src: ArrayLike ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @param src - source array-like object +* @returns iterator value +*/ +type MapFunction = Nullary | Unary | Binary | Tertiary; + +/** +* Returns an iterator which iterates from right to left over each element in an array-like object view. +* +* @param src - input value +* @param mapFcn - function to invoke for each iterated value +* @param thisArg - execution context +* @returns iterator +* +* @example +* function fcn( v ) { +* return v * 10.0; +* } +* +* var iter = arrayview2iteratorRight( [ 1, 2, 3, 4 ], fcn ); +* +* var v = iter.next().value; +* // returns 3 +* +* v = iter.next().value; +* // returns 2 +* +* var bool = iter.next().done; +* // returns true +*/ +declare function arrayview2iteratorRight( src: ArrayLike, mapFcn?: MapFunction, thisArg?: any ): Iterator; // tslint:disable-line:max-line-length + +/** +* Returns an iterator which iterates from right to left over each element in an array-like object view. +* +* @param src - input value +* @param begin - starting **view** index (inclusive) (default: 0) +* @param mapFcn - function to invoke for each iterated value +* @param thisArg - execution context +* @returns iterator +* +* @example +* var iter = arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1 ); +* +* var v = iter.next().value; +* // returns 3 +* +* v = iter.next().value; +* // returns 2 +* +* var bool = iter.next().done; +* // returns false +*/ +declare function arrayview2iteratorRight( src: ArrayLike, begin: number, mapFcn?: MapFunction, thisArg?: any ): Iterator; // tslint:disable-line:max-line-length + +/** +* Returns an iterator which iterates from right to left over each element in an array-like object view. +* +* @param src - input value +* @param begin - starting **view** index (inclusive) (default: 0) +* @param end - ending **view** index (non-inclusive) (default: src.length) +* @param mapFcn - function to invoke for each iterated value +* @param thisArg - execution context +* @returns iterator +* +* @example +* var iter = arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1, 3 ); +* +* var v = iter.next().value; +* // returns 3 +* +* v = iter.next().value; +* // returns 2 +* +* var bool = iter.next().done; +* // returns true +*/ +declare function arrayview2iteratorRight( src: ArrayLike, begin: number, end: number, mapFcn?: MapFunction, thisArg?: any ): Iterator; // tslint:disable-line:max-line-length + + +// EXPORTS // + +export = arrayview2iteratorRight; diff --git a/to-view-iterator-right/docs/types/test.ts b/to-view-iterator-right/docs/types/test.ts new file mode 100644 index 00000000..6f74bf33 --- /dev/null +++ b/to-view-iterator-right/docs/types/test.ts @@ -0,0 +1,86 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import arrayview2iteratorRight = require( './index' ); + +/** +* Multiplies a value by 10. +* +* @param v - iterated value +* @returns new value +*/ +function times10( v: number ): number { + return v * 10.0; +} + + +// TESTS // + +// The function returns an iterator... +{ + arrayview2iteratorRight( [ 1, 2, 3, 4 ] ); // $ExpectType Iterator + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1, 2, times10 ); // $ExpectType Iterator + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1, 2, times10, {} ); // $ExpectType Iterator +} + +// The compiler throws an error if the function is provided a first argument which is not array-like... +{ + arrayview2iteratorRight( 123 ); // $ExpectError + arrayview2iteratorRight( true ); // $ExpectError + arrayview2iteratorRight( false ); // $ExpectError + arrayview2iteratorRight( {} ); // $ExpectError + arrayview2iteratorRight( null ); // $ExpectError + arrayview2iteratorRight( undefined ); // $ExpectError +} + +// The compiler throws an error if the function is provided a second argument which is not a number or function... +{ + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 'abc' ); // $ExpectError + arrayview2iteratorRight( [ 1, 2, 3, 4 ], [] ); // $ExpectError + arrayview2iteratorRight( [ 1, 2, 3, 4 ], {} ); // $ExpectError + arrayview2iteratorRight( [ 1, 2, 3, 4 ], true ); // $ExpectError + arrayview2iteratorRight( [ 1, 2, 3, 4 ], false ); // $ExpectError + arrayview2iteratorRight( [ 1, 2, 3, 4 ], null ); // $ExpectError +} + +// The compiler throws an error if the function is provided a third argument which is not number or function... +{ + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1, 'abc' ); // $ExpectError + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1, [] ); // $ExpectError + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1, {} ); // $ExpectError + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1, true ); // $ExpectError + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1, false ); // $ExpectError + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1, null ); // $ExpectError +} + +// The compiler throws an error if the function is provided a fourth argument which is not a function... +{ + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 0, 2, 'abc' ); // $ExpectError + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 0, 2, 123 ); // $ExpectError + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 0, 2, [] ); // $ExpectError + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 0, 2, {} ); // $ExpectError + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 0, 2, true ); // $ExpectError + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 0, 2, false ); // $ExpectError + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 0, 2, null ); // $ExpectError +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + arrayview2iteratorRight(); // $ExpectError + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1, 2, times10, {}, 123 ); // $ExpectError +} diff --git a/to-view-iterator-right/examples/index.js b/to-view-iterator-right/examples/index.js new file mode 100644 index 00000000..82fc8cb9 --- /dev/null +++ b/to-view-iterator-right/examples/index.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var Float64Array = require( '@stdlib/array/float64' ); +var inmap = require( '@stdlib/utils/inmap' ); +var randu = require( '@stdlib/random/base/randu' ); +var arrayview2iteratorRight = require( './../lib' ); + +function scale( v, i ) { + return v * (i+1); +} + +// Create an array filled with random numbers: +var arr = inmap( new Float64Array( 100 ), randu ); + +// Create an iterator from an array view which scales iterated values: +var it = arrayview2iteratorRight( arr, 40, 60, scale ); + +// Perform manual iteration... +var v; +while ( true ) { + v = it.next(); + if ( v.done ) { + break; + } + console.log( v.value ); +} diff --git a/to-view-iterator-right/lib/index.js b/to-view-iterator-right/lib/index.js new file mode 100644 index 00000000..9a383d97 --- /dev/null +++ b/to-view-iterator-right/lib/index.js @@ -0,0 +1,48 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Create an iterator from an array-like object view, iterating from right to left. +* +* @module @stdlib/array/to-view-iterator-right +* +* @example +* var arrayview2iteratorRight = require( '@stdlib/array/to-view-iterator-right' ); +* +* var iter = arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1, 3 ); +* +* var v = iter.next().value; +* // returns 3 +* +* v = iter.next().value; +* // returns 2 +* +* var bool = iter.next().done; +* // returns true +*/ + +// MODULES // + +var iterator = require( './main.js' ); + + +// EXPORTS // + +module.exports = iterator; diff --git a/to-view-iterator-right/lib/main.js b/to-view-iterator-right/lib/main.js new file mode 100644 index 00000000..cd9214b8 --- /dev/null +++ b/to-view-iterator-right/lib/main.js @@ -0,0 +1,217 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var isCollection = require( '@stdlib/assert/is-collection' ); +var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; +var iteratorSymbol = require( '@stdlib/symbol/iterator' ); + + +// MAIN // + +/** +* Returns an iterator which iterates from right to left over each element in an array-like object view. +* +* @param {Collection} src - input value +* @param {integer} [begin=0] - starting **view** index (inclusive) +* @param {integer} [end=src.length] - ending **view** index (non-inclusive) +* @param {Function} [mapFcn] - function to invoke for each iterated value +* @param {*} [thisArg] - execution context +* @throws {TypeError} first argument must be an array-like object +* @throws {TypeError} second argument must be either an integer (starting index) or a function +* @throws {TypeError} third argument must be either an integer (ending index) or a function +* @throws {TypeError} fourth argument must be a function +* @returns {Iterator} iterator +* +* @example +* var iter = arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1, 3 ); +* +* var v = iter.next().value; +* // returns 3 +* +* v = iter.next().value; +* // returns 2 +* +* var bool = iter.next().done; +* // returns true +*/ +function arrayview2iteratorRight( src ) { + var thisArg; + var begin; + var nargs; + var iter; + var FLG; + var fcn; + var end; + var i; + if ( !isCollection( src ) ) { + throw new TypeError( 'invalid argument. First argument must be an array-like object. Value: `' + src + '`.' ); + } + nargs = arguments.length; + if ( nargs === 1 ) { + begin = 0; + end = src.length; + } else if ( nargs === 2 ) { + if ( isFunction( arguments[ 1 ] ) ) { + begin = 0; + fcn = arguments[ 1 ]; + } else { + begin = arguments[ 1 ]; + } + end = src.length; + } else if ( nargs === 3 ) { + if ( isFunction( arguments[ 1 ] ) ) { + begin = 0; + end = src.length; + fcn = arguments[ 1 ]; + thisArg = arguments[ 2 ]; + } else if ( isFunction( arguments[ 2 ] ) ) { + begin = arguments[ 1 ]; + end = src.length; + fcn = arguments[ 2 ]; + } else { + begin = arguments[ 1 ]; + end = arguments[ 2 ]; + } + } else { // nargs >= 4 + begin = arguments[ 1 ]; + end = arguments[ 2 ]; + fcn = arguments[ 3 ]; + if ( !isFunction( fcn ) ) { + throw new TypeError( 'invalid argument. Fourth argument must be a function. Value: `' + fcn + '`.' ); + } + thisArg = arguments[ 4 ]; + } + if ( !isInteger( begin ) ) { + throw new TypeError( 'invalid argument. Second argument must be either an integer (starting vie windex) or a callback function. Value: `' + begin + '`.' ); + } + if ( !isInteger( end ) ) { + throw new TypeError( 'invalid argument. Third argument must be either an integer (ending view index) or a callback function. Value: `' + end + '`.' ); + } + if ( end < 0 ) { + end = src.length + end; + if ( end < 0 ) { + end = 0; + } + } else if ( end > src.length ) { + end = src.length; + } + if ( begin < 0 ) { + begin = src.length + begin; + if ( begin < 0 ) { + begin = 0; + } + } + i = end; + + // Create an iterator protocol-compliant object: + iter = {}; + if ( fcn ) { + setReadOnly( iter, 'next', next1 ); + } else { + setReadOnly( iter, 'next', next2 ); + } + setReadOnly( iter, 'return', finish ); + + // If an environment supports `Symbol.iterator`, make the iterator iterable: + if ( iteratorSymbol ) { + setReadOnly( iter, iteratorSymbol, factory ); + } + return iter; + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next1() { + i -= 1; + if ( FLG || i < begin ) { + return { + 'done': true + }; + } + return { + 'value': fcn.call( thisArg, src[ i ], i, end-i-1, src ), + 'done': false + }; + } + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next2() { + i -= 1; + if ( FLG || i < begin ) { + return { + 'done': true + }; + } + return { + 'value': src[ i ], + 'done': false + }; + } + + /** + * Finishes an iterator. + * + * @private + * @param {*} [value] - value to return + * @returns {Object} iterator protocol-compliant object + */ + function finish( value ) { + FLG = true; + if ( arguments.length ) { + return { + 'value': value, + 'done': true + }; + } + return { + 'done': true + }; + } + + /** + * Returns a new iterator. + * + * @private + * @returns {Iterator} iterator + */ + function factory() { + if ( fcn ) { + return arrayview2iteratorRight( src, begin, end, fcn, thisArg ); + } + return arrayview2iteratorRight( src, begin, end ); + } +} + + +// EXPORTS // + +module.exports = arrayview2iteratorRight; diff --git a/to-view-iterator-right/package.json b/to-view-iterator-right/package.json new file mode 100644 index 00000000..7933d12d --- /dev/null +++ b/to-view-iterator-right/package.json @@ -0,0 +1,73 @@ +{ + "name": "@stdlib/array/to-view-iterator-right", + "version": "0.0.0", + "description": "Create an iterator from an array-like object view, iterating from right to left.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "utils", + "util", + "utilities", + "utility", + "typed", + "array", + "arr", + "view", + "slice", + "reverse", + "typed-array", + "typed array", + "iterator", + "iterate", + "iteration", + "iter", + "to", + "convert" + ] +} diff --git a/to-view-iterator-right/test/test.js b/to-view-iterator-right/test/test.js new file mode 100644 index 00000000..783cdb8c --- /dev/null +++ b/to-view-iterator-right/test/test.js @@ -0,0 +1,1490 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var iteratorSymbol = require( '@stdlib/symbol/iterator' ); +var noop = require( '@stdlib/utils/noop' ); +var arrayview2iteratorRight = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.equal( typeof arrayview2iteratorRight, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iteratorRight( value ); + }; + } +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object (begin)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iteratorRight( value, 1 ); + }; + } +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object (begin+callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iteratorRight( value, 1, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object (begin+end)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iteratorRight( value, 1, 3 ); + }; + } +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object (begin+end+callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iteratorRight( value, 1, 3, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object (callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iteratorRight( value, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a second argument which is neither an integer nor a function', function test( t ) { + var values; + var i; + + values = [ + '5', + 3.14, + NaN, + true, + false, + null, + void 0, + [], + {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iteratorRight( [ 1, 2, 3, 4 ], value ); + }; + } +}); + +tape( 'the function throws an error if provided a second argument which is not an integer (callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 3.14, + NaN, + true, + false, + null, + void 0, + [], + {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iteratorRight( [ 1, 2, 3, 4 ], value, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a third argument which is neither an integer nor a function', function test( t ) { + var values; + var i; + + values = [ + '5', + 3.14, + NaN, + true, + false, + null, + void 0, + [], + {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1, value ); + }; + } +}); + +tape( 'the function throws an error if provided a third argument which is not an integer (callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 3.14, + NaN, + true, + false, + null, + void 0, + [], + {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1, value, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a fourth argument which is not a function', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + 3.14, + NaN, + true, + false, + null, + void 0, + [], + {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1, 3, value ); + }; + } +}); + +tape( 'the function returns an iterator protocol-compliant object', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 4, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 1, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iteratorRight( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (begin)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 4, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iteratorRight( values, 2 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (begin+end)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 3, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iteratorRight( values, 1, 3 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (begin+end)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 4, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iteratorRight( values, 1, 3000 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-1; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (begin<0)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 4, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iteratorRight( values, -3 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-1; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (begin<0)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 4, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 1, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iteratorRight( values, -300 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (begin<0+end)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 3, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iteratorRight( values, -3, 3 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (begin+end<0)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 3, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iteratorRight( values, 1, -1 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (begin+end<0)', function test( t ) { + var expected; + var actual; + var values; + var it; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'done': true + } + ]; + + it = arrayview2iteratorRight( values, 0, -3000 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (begin<0+end<0)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 3, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iteratorRight( values, -3, -1 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (array-like object)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = { + 'length': 4, + '0': 1, + '1': 2, + '2': 3, + '3': 4 + }; + expected = [ + { + 'value': 4, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 1, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iteratorRight( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + + it = arrayview2iteratorRight( values, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (context)', function test( t ) { + var expected; + var values; + var ctx; + var it; + var r; + var i; + + ctx = { + 'count': 0 + }; + values = [ 1, 2, 3, 4 ]; + + it = arrayview2iteratorRight( values, scale, ctx ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.equal( ctx.count, values.length, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + this.count += 1; // eslint-disable-line no-invalid-this + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (begin)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + + it = arrayview2iteratorRight( values, 1, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length-1; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length-1, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (begin<0)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + + it = arrayview2iteratorRight( values, -3, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length-1; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length-1, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (begin+end)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + + it = arrayview2iteratorRight( values, 0, 2, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length-2, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (begin+end<0)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + + it = arrayview2iteratorRight( values, 0, -2, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length-2, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (begin<0+end<0)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + + it = arrayview2iteratorRight( values, -3, -1, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length-2, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (begin+end<0)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + + it = arrayview2iteratorRight( values, 1, -1, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length-2, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (array-like)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = { + 'length': 4, + '0': 1, + '1': 2, + '2': 3, + '3': 4 + }; + + it = arrayview2iteratorRight( values, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (no argument)', function test( t ) { + var it; + var r; + + it = arrayview2iteratorRight( [ 1, 2, 3, 4 ] ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (no argument; callback)', function test( t ) { + var it; + var r; + + it = arrayview2iteratorRight( [ 1, 2, 3, 4 ], scale ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (argument)', function test( t ) { + var it; + var r; + + it = arrayview2iteratorRight( [ 1, 2, 3, 4 ] ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return( 'finished' ); + t.equal( r.value, 'finished', 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (argument; callback)', function test( t ) { + var it; + var r; + + it = arrayview2iteratorRight( [ 1, 2, 3, 4 ], scale ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return( 'finished' ); + t.equal( r.value, 'finished', 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable', function test( t ) { + var arrayview2iteratorRight; + var values; + var it1; + var it2; + var i; + + arrayview2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = arrayview2iteratorRight( values ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable (begin)', function test( t ) { + var arrayview2iteratorRight; + var values; + var it1; + var it2; + var i; + + arrayview2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = arrayview2iteratorRight( values, 1 ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable (begin+end)', function test( t ) { + var arrayview2iteratorRight; + var values; + var it1; + var it2; + var i; + + arrayview2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = arrayview2iteratorRight( values, 1, 3 ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable (callback)', function test( t ) { + var arrayview2iteratorRight; + var values; + var it1; + var it2; + var i; + + arrayview2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = arrayview2iteratorRight( values, scale ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); + + function scale( v ) { + return v * 10.0; + } +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable (begin+callback)', function test( t ) { + var arrayview2iteratorRight; + var values; + var it1; + var it2; + var i; + + arrayview2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = arrayview2iteratorRight( values, 1, scale ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); + + function scale( v ) { + return v * 10.0; + } +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable (begin+end+callback)', function test( t ) { + var arrayview2iteratorRight; + var values; + var it1; + var it2; + var i; + + arrayview2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = arrayview2iteratorRight( values, 1, 3, scale ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); + + function scale( v ) { + return v * 10.0; + } +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable"', function test( t ) { + var arrayview2iteratorRight; + var it; + + arrayview2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = arrayview2iteratorRight( [ 1, 2, 3, 4 ] ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable" (begin)', function test( t ) { + var arrayview2iteratorRight; + var it; + + arrayview2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1 ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable" (begin+end)', function test( t ) { + var arrayview2iteratorRight; + var it; + + arrayview2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1, 3 ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable" (callback)', function test( t ) { + var arrayview2iteratorRight; + var it; + + arrayview2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = arrayview2iteratorRight( [ 1, 2, 3, 4 ], scale ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable" (begin+callback)', function test( t ) { + var arrayview2iteratorRight; + var it; + + arrayview2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1, scale ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable" (begin+end+callback)', function test( t ) { + var arrayview2iteratorRight; + var it; + + arrayview2iteratorRight = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = arrayview2iteratorRight( [ 1, 2, 3, 4 ], 1, 3, scale ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); diff --git a/to-view-iterator/README.md b/to-view-iterator/README.md new file mode 100644 index 00000000..2939fe77 --- /dev/null +++ b/to-view-iterator/README.md @@ -0,0 +1,293 @@ + + +# arrayview2iterator + +> Create an iterator from an array-like object view. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var arrayview2iterator = require( '@stdlib/array/to-view-iterator' ); +``` + +#### arrayview2iterator( src\[, begin\[, end]]\[, mapFcn\[, thisArg]] ) + +Returns an iterator which iterates over each element in an array-like `object` view. + +```javascript +var it = arrayview2iterator( [ 1, 2, 3, 4 ] ); +// returns + +var v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 2 + +v = it.next().value; +// returns 3 + +// ... +``` + +The returned iterator protocol-compliant object has the following properties: + +- **next**: function which returns an iterator protocol-compliant object containing the next iterated value (if one exists) assigned to a `value` property and a `done` property having a `boolean` value indicating whether the iterator is finished. +- **return**: function which closes an iterator and returns a single (optional) argument in an iterator protocol-compliant object. + +By default, the returned iterator begins iterating from the first element in an array-like `object`. To specify an alternative starting index, provide a `begin` argument (inclusive). + +```javascript +var it = arrayview2iterator( [ 1, 2, 3, 4 ], 1 ); +// returns + +var v = it.next().value; +// returns 2 + +v = it.next().value; +// returns 3 + +v = it.next().value; +// returns 4 + +var bool = it.next().done; +// returns true +``` + +If `begin` is less than `0`, the starting index is resolved relative to the last element. For example, the following generates the same behavior as in the previous example + +```javascript +var it = arrayview2iterator( [ 1, 2, 3, 4 ], -3 ); +// returns + +var v = it.next().value; +// returns 2 + +v = it.next().value; +// returns 3 + +v = it.next().value; +// returns 4 + +var bool = it.next().done; +// returns true +``` + +By default, the returned iterator iterates until the last element in an array-like `object`. To specify an alternative ending index, provide an `end` argument (non-inclusive). + +```javascript +var it = arrayview2iterator( [ 1, 2, 3, 4 ], 0, 3 ); +// returns + +var v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 2 + +v = it.next().value; +// returns 3 + +var bool = it.next().done; +// returns true +``` + +If `end` is less than `0`, the ending index is resolved relative to the last element. For example, the following generates the same behavior as in the previous example + +```javascript +var it = arrayview2iterator( [ 1, 2, 3, 4 ], 0, -1 ); +// returns + +var v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 2 + +v = it.next().value; +// returns 3 + +var bool = it.next().done; +// returns true +``` + +To invoke a function for each `src` value, provide a callback function. + +```javascript +function fcn( v ) { + return v * 10.0; +} + +var it = arrayview2iterator( [ 1, 2, 3, 4 ], fcn ); +// returns + +var v = it.next().value; +// returns 10.0 + +v = it.next().value; +// returns 20.0 + +v = it.next().value; +// returns 30.0 + +// ... +``` + +The invoked function is provided four arguments: + +- `value`: iterated value +- `index`: iterated value index +- `n`: iteration count (zero-based) +- `src`: source array-like object + +```javascript +function fcn( v, i ) { + return v * (i+1); +} + +var it = arrayview2iterator( [ 1, 2, 3, 4 ], fcn ); +// returns + +var v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 4 + +v = it.next().value; +// returns 9 + +// ... +``` + +To set the callback function execution context, provide a `thisArg`. + +```javascript +function fcn( v ) { + this.count += 1; + return v * 10.0; +} + +var ctx = { + 'count': 0 +}; + +var it = arrayview2iterator( [ 1, 2, 3, 4 ], fcn, ctx ); +// returns + +var v = it.next().value; +// returns 10.0 + +v = it.next().value; +// returns 20.0 + +v = it.next().value; +// returns 30.0 + +var count = ctx.count; +// returns 3 +``` + + + + + + + +
+ +## Notes + +- If an environment supports `Symbol.iterator`, the returned iterator is iterable. +- If provided a generic `array`, the returned iterator does **not** ignore holes. To achieve greater performance for sparse arrays, use a custom iterator. +- A returned iterator does **not** copy a provided array-like `object`. To ensure iterable reproducibility, copy a provided array-like `object` **before** creating an iterator. Otherwise, any changes to the contents of an array-like `object` will be reflected in the returned iterator. +- In environments supporting `Symbol.iterator`, the function **explicitly** does **not** invoke an array's `@@iterator` method, regardless of whether this method is defined. To convert an array to an implementation defined iterator, invoke this method directly. + +
+ + + + + +
+ +## Examples + + + +```javascript +var Float64Array = require( '@stdlib/array/float64' ); +var inmap = require( '@stdlib/utils/inmap' ); +var randu = require( '@stdlib/random/base/randu' ); +var arrayview2iterator = require( '@stdlib/array/to-view-iterator' ); + +function scale( v, i ) { + return v * (i+1); +} + +// Create an array filled with random numbers: +var arr = inmap( new Float64Array( 100 ), randu ); + +// Create an iterator from an array view which scales iterated values: +var it = arrayview2iterator( arr, 40, 60, scale ); + +// Perform manual iteration... +var v; +while ( true ) { + v = it.next(); + if ( v.done ) { + break; + } + console.log( v.value ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/to-view-iterator/benchmark/benchmark.js b/to-view-iterator/benchmark/benchmark.js new file mode 100644 index 00000000..29f5eba2 --- /dev/null +++ b/to-view-iterator/benchmark/benchmark.js @@ -0,0 +1,109 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isnan = require( '@stdlib/math/base/assert/is-nan' ); +var isIteratorLike = require( '@stdlib/assert/is-iterator-like' ); +var pkg = require( './../package.json' ).name; +var arrayview2iterator = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var values; + var iter; + var i; + + values = [ 1, 2, 3, 4 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + values[ 0 ] = i; + iter = arrayview2iterator( values ); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isIteratorLike( iter ) ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::iteration', function benchmark( b ) { + var values; + var iter; + var z; + var i; + + values = []; + values.length = b.iterations; + + iter = arrayview2iterator( values ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + z = iter.next().value; + if ( z !== void 0 ) { + b.fail( 'should be undefined' ); + } + } + b.toc(); + if ( z !== void 0 ) { + b.fail( 'should be undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::iteration,map', function benchmark( b ) { + var values; + var iter; + var z; + var i; + + values = []; + values.length = b.iterations; + + iter = arrayview2iterator( values, transform ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + z = iter.next().value; + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( isnan( z ) ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function transform( v, i ) { + return i; + } +}); diff --git a/to-view-iterator/docs/repl.txt b/to-view-iterator/docs/repl.txt new file mode 100644 index 00000000..2ee8fc55 --- /dev/null +++ b/to-view-iterator/docs/repl.txt @@ -0,0 +1,63 @@ + +{{alias}}( src[, begin[, end]][, mapFcn[, thisArg]] ) + Returns an iterator which iterates over the elements of an array-like + object view. + + When invoked, an input function is provided four arguments: + + - value: iterated value + - index: iterated value index + - n: iteration count (zero-based) + - src: source array-like object + + If an environment supports Symbol.iterator, the returned iterator is + iterable. + + If an environment supports Symbol.iterator, the function explicitly does not + not invoke an array's `@@iterator` method, regardless of whether this method + is defined. To convert an array to an implementation defined iterator, + invoke this method directly. + + Parameters + ---------- + src: ArrayLikeObject + Array-like object from which to create the iterator. + + begin: integer (optional) + Starting index (inclusive). When negative, determined relative to the + last element. Default: 0. + + end: integer (optional) + Ending index (non-inclusive). When negative, determined relative to the + last element. Default: src.length. + + mapFcn: Function (optional) + Function to invoke for each iterated value. + + thisArg: any (optional) + Execution context. + + Returns + ------- + iterator: Object + Iterator. + + iterator.next(): Function + Returns an iterator protocol-compliant object containing the next + iterated value (if one exists) and a boolean flag indicating whether the + iterator is finished. + + iterator.return( [value] ): Function + Finishes an iterator and returns a provided value. + + Examples + -------- + > var it = {{alias}}( [ 1, 2, 3, 4 ], 1, 3 ); + > var v = it.next().value + 2 + > v = it.next().value + 3 + + See Also + -------- + diff --git a/to-view-iterator/docs/types/index.d.ts b/to-view-iterator/docs/types/index.d.ts new file mode 100644 index 00000000..c0fba842 --- /dev/null +++ b/to-view-iterator/docs/types/index.d.ts @@ -0,0 +1,149 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/// + +import { Iterator as Iter, IterableIterator } from '@stdlib/types/iter'; +import { ArrayLike } from '@stdlib/types/array'; + +// Define a union type representing both iterable and non-iterable iterators: +type Iterator = Iter | IterableIterator; + +/** +* Map function invoked for each iterated value. +* +* @returns iterator value +*/ +type Nullary = () => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @returns iterator value +*/ +type Unary = ( value: any ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @returns iterator value +*/ +type Binary = ( value: any, index: number ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @param src - source array-like object +* @returns iterator value +*/ +type Tertiary = ( value: any, index: number, src: ArrayLike ) => any; + +/** +* Map function invoked for each iterated value. +* +* @param value - iterated value +* @param index - iterated value index +* @param src - source array-like object +* @returns iterator value +*/ +type MapFunction = Nullary | Unary | Binary | Tertiary; + +/** +* Returns an iterator which iterates over each element in an array-like object view. +* +* @param src - input value +* @param mapFcn - function to invoke for each iterated value +* @param thisArg - execution context +* @returns iterator +* +* @example +* function fcn( v ) { +* return v * 10.0; +* } + +* var iter = arrayview2iterator( [ 1, 2, 3, 4 ], fcn ); +* +* var v = iter.next().value; +* // returns 10 +* +* v = iter.next().value; +* // returns 20 +* +* var bool = iter.next().done; +* // returns false +*/ +declare function arrayview2iterator( src: ArrayLike, mapFcn?: MapFunction, thisArg?: any ): Iterator; // tslint:disable-line:max-line-length + +/** +* Returns an iterator which iterates over each element in an array-like object view. +* +* @param src - input value +* @param begin - starting index (inclusive) (default: 0) +* @param mapFcn - function to invoke for each iterated value +* @param thisArg - execution context +* @returns iterator +* +* @example +* var iter = arrayview2iterator( [ 1, 2, 3, 4 ], 1 ); +* +* var v = iter.next().value; +* // returns 2 +* +* v = iter.next().value; +* // returns 3 +* +* var bool = iter.next().done; +* // returns false +*/ +declare function arrayview2iterator( src: ArrayLike, begin: number, mapFcn?: MapFunction, thisArg?: any ): Iterator; // tslint:disable-line:max-line-length + +/** +* Returns an iterator which iterates over each element in an array-like object view. +* +* @param src - input value +* @param begin - starting index (inclusive) (default: 0) +* @param end - ending index (non-inclusive) (default: src.length) +* @param mapFcn - function to invoke for each iterated value +* @param thisArg - execution context +* @returns iterator +* +* @example +* var iter = arrayview2iterator( [ 1, 2, 3, 4 ], 1, 3 ); +* +* var v = iter.next().value; +* // returns 2 +* +* v = iter.next().value; +* // returns 3 +* +* var bool = iter.next().done; +* // returns true +*/ +declare function arrayview2iterator( src: ArrayLike, begin: number, end: number, mapFcn?: MapFunction, thisArg?: any ): Iterator; // tslint:disable-line:max-line-length + + +// EXPORTS // + +export = arrayview2iterator; diff --git a/to-view-iterator/docs/types/test.ts b/to-view-iterator/docs/types/test.ts new file mode 100644 index 00000000..1ee78dd4 --- /dev/null +++ b/to-view-iterator/docs/types/test.ts @@ -0,0 +1,86 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import arrayview2iterator = require( './index' ); + +/** +* Multiplies a value by 10. +* +* @param v - iterated value +* @returns new value +*/ +function times10( v: number ): number { + return v * 10.0; +} + + +// TESTS // + +// The function returns an iterator... +{ + arrayview2iterator( [ 1, 2, 3, 4 ] ); // $ExpectType Iterator + arrayview2iterator( [ 1, 2, 3, 4 ], 1, 2, times10 ); // $ExpectType Iterator + arrayview2iterator( [ 1, 2, 3, 4 ], 1, 2, times10, {} ); // $ExpectType Iterator +} + +// The compiler throws an error if the function is provided a first argument which is not array-like... +{ + arrayview2iterator( 123 ); // $ExpectError + arrayview2iterator( true ); // $ExpectError + arrayview2iterator( false ); // $ExpectError + arrayview2iterator( {} ); // $ExpectError + arrayview2iterator( null ); // $ExpectError + arrayview2iterator( undefined ); // $ExpectError +} + +// The compiler throws an error if the function is provided a second argument which is not a number or function... +{ + arrayview2iterator( [ 1, 2, 3, 4 ], 'abc' ); // $ExpectError + arrayview2iterator( [ 1, 2, 3, 4 ], [] ); // $ExpectError + arrayview2iterator( [ 1, 2, 3, 4 ], {} ); // $ExpectError + arrayview2iterator( [ 1, 2, 3, 4 ], true ); // $ExpectError + arrayview2iterator( [ 1, 2, 3, 4 ], false ); // $ExpectError + arrayview2iterator( [ 1, 2, 3, 4 ], null ); // $ExpectError +} + +// The compiler throws an error if the function is provided a third argument which is not number or function... +{ + arrayview2iterator( [ 1, 2, 3, 4 ], 1, 'abc' ); // $ExpectError + arrayview2iterator( [ 1, 2, 3, 4 ], 1, [] ); // $ExpectError + arrayview2iterator( [ 1, 2, 3, 4 ], 1, {} ); // $ExpectError + arrayview2iterator( [ 1, 2, 3, 4 ], 1, true ); // $ExpectError + arrayview2iterator( [ 1, 2, 3, 4 ], 1, false ); // $ExpectError + arrayview2iterator( [ 1, 2, 3, 4 ], 1, null ); // $ExpectError +} + +// The compiler throws an error if the function is provided a fourth argument which is not a function... +{ + arrayview2iterator( [ 1, 2, 3, 4 ], 0, 2, 'abc' ); // $ExpectError + arrayview2iterator( [ 1, 2, 3, 4 ], 0, 2, 123 ); // $ExpectError + arrayview2iterator( [ 1, 2, 3, 4 ], 0, 2, [] ); // $ExpectError + arrayview2iterator( [ 1, 2, 3, 4 ], 0, 2, {} ); // $ExpectError + arrayview2iterator( [ 1, 2, 3, 4 ], 0, 2, true ); // $ExpectError + arrayview2iterator( [ 1, 2, 3, 4 ], 0, 2, false ); // $ExpectError + arrayview2iterator( [ 1, 2, 3, 4 ], 0, 2, null ); // $ExpectError +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + arrayview2iterator(); // $ExpectError + arrayview2iterator( [ 1, 2, 3, 4 ], 1, 2, times10, {}, 123 ); // $ExpectError +} diff --git a/to-view-iterator/examples/index.js b/to-view-iterator/examples/index.js new file mode 100644 index 00000000..8b1deb13 --- /dev/null +++ b/to-view-iterator/examples/index.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var Float64Array = require( '@stdlib/array/float64' ); +var inmap = require( '@stdlib/utils/inmap' ); +var randu = require( '@stdlib/random/base/randu' ); +var arrayview2iterator = require( './../lib' ); + +function scale( v, i ) { + return v * (i+1); +} + +// Create an array filled with random numbers: +var arr = inmap( new Float64Array( 100 ), randu ); + +// Create an iterator from an array view which scales iterated values: +var it = arrayview2iterator( arr, 40, 60, scale ); + +// Perform manual iteration... +var v; +while ( true ) { + v = it.next(); + if ( v.done ) { + break; + } + console.log( v.value ); +} diff --git a/to-view-iterator/lib/index.js b/to-view-iterator/lib/index.js new file mode 100644 index 00000000..29bf2666 --- /dev/null +++ b/to-view-iterator/lib/index.js @@ -0,0 +1,48 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Create an iterator from an array-like object view. +* +* @module @stdlib/array/to-view-iterator +* +* @example +* var arrayview2iterator = require( '@stdlib/array/to-view-iterator' ); +* +* var iter = arrayview2iterator( [ 1, 2, 3, 4 ], 1, 3 ); +* +* var v = iter.next().value; +* // returns 2 +* +* v = iter.next().value; +* // returns 3 +* +* var bool = iter.next().done; +* // returns true +*/ + +// MODULES // + +var iterator = require( './main.js' ); + + +// EXPORTS // + +module.exports = iterator; diff --git a/to-view-iterator/lib/main.js b/to-view-iterator/lib/main.js new file mode 100644 index 00000000..93e6ceae --- /dev/null +++ b/to-view-iterator/lib/main.js @@ -0,0 +1,217 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var isCollection = require( '@stdlib/assert/is-collection' ); +var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; +var iteratorSymbol = require( '@stdlib/symbol/iterator' ); + + +// MAIN // + +/** +* Returns an iterator which iterates over each element in an array-like object view. +* +* @param {Collection} src - input value +* @param {integer} [begin=0] - starting index (inclusive) +* @param {integer} [end=src.length] - ending index (non-inclusive) +* @param {Function} [mapFcn] - function to invoke for each iterated value +* @param {*} [thisArg] - execution context +* @throws {TypeError} first argument must be an array-like object +* @throws {TypeError} second argument must be either an integer (starting index) or a function +* @throws {TypeError} third argument must be either an integer (ending index) or a function +* @throws {TypeError} fourth argument must be a function +* @returns {Iterator} iterator +* +* @example +* var iter = arrayview2iterator( [ 1, 2, 3, 4 ], 1, 3 ); +* +* var v = iter.next().value; +* // returns 2 +* +* v = iter.next().value; +* // returns 3 +* +* var bool = iter.next().done; +* // returns true +*/ +function arrayview2iterator( src ) { + var thisArg; + var begin; + var nargs; + var iter; + var FLG; + var fcn; + var end; + var i; + if ( !isCollection( src ) ) { + throw new TypeError( 'invalid argument. First argument must be an array-like object. Value: `' + src + '`.' ); + } + nargs = arguments.length; + if ( nargs === 1 ) { + begin = 0; + end = src.length; + } else if ( nargs === 2 ) { + if ( isFunction( arguments[ 1 ] ) ) { + begin = 0; + fcn = arguments[ 1 ]; + } else { + begin = arguments[ 1 ]; + } + end = src.length; + } else if ( nargs === 3 ) { + if ( isFunction( arguments[ 1 ] ) ) { + begin = 0; + end = src.length; + fcn = arguments[ 1 ]; + thisArg = arguments[ 2 ]; + } else if ( isFunction( arguments[ 2 ] ) ) { + begin = arguments[ 1 ]; + end = src.length; + fcn = arguments[ 2 ]; + } else { + begin = arguments[ 1 ]; + end = arguments[ 2 ]; + } + } else { // nargs >= 4 + begin = arguments[ 1 ]; + end = arguments[ 2 ]; + fcn = arguments[ 3 ]; + if ( !isFunction( fcn ) ) { + throw new TypeError( 'invalid argument. Fourth argument must be a function. Value: `' + fcn + '`.' ); + } + thisArg = arguments[ 4 ]; + } + if ( !isInteger( begin ) ) { + throw new TypeError( 'invalid argument. Second argument must be either an integer (starting index) or a callback function. Value: `' + begin + '`.' ); + } + if ( !isInteger( end ) ) { + throw new TypeError( 'invalid argument. Third argument must be either an integer (ending index) or a callback function. Value: `' + end + '`.' ); + } + if ( end < 0 ) { + end = src.length + end; + if ( end < 0 ) { + end = 0; + } + } else if ( end > src.length ) { + end = src.length; + } + if ( begin < 0 ) { + begin = src.length + begin; + if ( begin < 0 ) { + begin = 0; + } + } + i = begin - 1; + + // Create an iterator protocol-compliant object: + iter = {}; + if ( fcn ) { + setReadOnly( iter, 'next', next1 ); + } else { + setReadOnly( iter, 'next', next2 ); + } + setReadOnly( iter, 'return', finish ); + + // If an environment supports `Symbol.iterator`, make the iterator iterable: + if ( iteratorSymbol ) { + setReadOnly( iter, iteratorSymbol, factory ); + } + return iter; + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next1() { + i += 1; + if ( FLG || i >= end ) { + return { + 'done': true + }; + } + return { + 'value': fcn.call( thisArg, src[ i ], i, i-begin, src ), + 'done': false + }; + } + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next2() { + i += 1; + if ( FLG || i >= end ) { + return { + 'done': true + }; + } + return { + 'value': src[ i ], + 'done': false + }; + } + + /** + * Finishes an iterator. + * + * @private + * @param {*} [value] - value to return + * @returns {Object} iterator protocol-compliant object + */ + function finish( value ) { + FLG = true; + if ( arguments.length ) { + return { + 'value': value, + 'done': true + }; + } + return { + 'done': true + }; + } + + /** + * Returns a new iterator. + * + * @private + * @returns {Iterator} iterator + */ + function factory() { + if ( fcn ) { + return arrayview2iterator( src, begin, end, fcn, thisArg ); + } + return arrayview2iterator( src, begin, end ); + } +} + + +// EXPORTS // + +module.exports = arrayview2iterator; diff --git a/to-view-iterator/package.json b/to-view-iterator/package.json new file mode 100644 index 00000000..fe5cffa5 --- /dev/null +++ b/to-view-iterator/package.json @@ -0,0 +1,72 @@ +{ + "name": "@stdlib/array/to-view-iterator", + "version": "0.0.0", + "description": "Create an iterator from an array-like object view.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "utils", + "util", + "utilities", + "utility", + "typed", + "array", + "arr", + "view", + "slice", + "typed-array", + "typed array", + "iterator", + "iterate", + "iteration", + "iter", + "to", + "convert" + ] +} diff --git a/to-view-iterator/test/test.js b/to-view-iterator/test/test.js new file mode 100644 index 00000000..82e305f6 --- /dev/null +++ b/to-view-iterator/test/test.js @@ -0,0 +1,1490 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2019 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var iteratorSymbol = require( '@stdlib/symbol/iterator' ); +var noop = require( '@stdlib/utils/noop' ); +var arrayview2iterator = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.equal( typeof arrayview2iterator, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iterator( value ); + }; + } +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object (begin)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iterator( value, 1 ); + }; + } +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object (begin+callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iterator( value, 1, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object (begin+end)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iterator( value, 1, 3 ); + }; + } +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object (begin+end+callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iterator( value, 1, 3, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a first argument which is not an array-like object (callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iterator( value, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a second argument which is neither an integer nor a function', function test( t ) { + var values; + var i; + + values = [ + '5', + 3.14, + NaN, + true, + false, + null, + void 0, + [], + {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iterator( [ 1, 2, 3, 4 ], value ); + }; + } +}); + +tape( 'the function throws an error if provided a second argument which is not an integer (callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 3.14, + NaN, + true, + false, + null, + void 0, + [], + {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iterator( [ 1, 2, 3, 4 ], value, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a third argument which is neither an integer nor a function', function test( t ) { + var values; + var i; + + values = [ + '5', + 3.14, + NaN, + true, + false, + null, + void 0, + [], + {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iterator( [ 1, 2, 3, 4 ], 1, value ); + }; + } +}); + +tape( 'the function throws an error if provided a third argument which is not an integer (callback)', function test( t ) { + var values; + var i; + + values = [ + '5', + 3.14, + NaN, + true, + false, + null, + void 0, + [], + {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iterator( [ 1, 2, 3, 4 ], 1, value, noop ); + }; + } +}); + +tape( 'the function throws an error if provided a fourth argument which is not a function', function test( t ) { + var values; + var i; + + values = [ + '5', + 5, + 3.14, + NaN, + true, + false, + null, + void 0, + [], + {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + arrayview2iterator( [ 1, 2, 3, 4 ], 1, 3, value ); + }; + } +}); + +tape( 'the function returns an iterator protocol-compliant object', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 1, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iterator( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (begin)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iterator( values, 2 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < 2; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (begin+end)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iterator( values, 1, 3 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < 2; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (begin+end)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iterator( values, 1, 3000 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-1; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (begin<0)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iterator( values, -3 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-1; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (begin<0)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 1, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iterator( values, -300 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (begin<0+end)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iterator( values, -3, 3 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (begin+end<0)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iterator( values, 1, -1 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (begin+end<0)', function test( t ) { + var expected; + var actual; + var values; + var it; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'done': true + } + ]; + + it = arrayview2iterator( values, 0, -3000 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (begin<0+end<0)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + expected = [ + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iterator( values, -3, -1 ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object (array-like object)', function test( t ) { + var expected; + var actual; + var values; + var it; + var r; + var i; + + values = { + 'length': 4, + '0': 1, + '1': 2, + '2': 3, + '3': 4 + }; + expected = [ + { + 'value': 1, + 'done': false + }, + { + 'value': 2, + 'done': false + }, + { + 'value': 3, + 'done': false + }, + { + 'value': 4, + 'done': false + }, + { + 'done': true + } + ]; + + it = arrayview2iterator( values ); + t.equal( it.next.length, 0, 'has zero arity' ); + + actual = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + actual.push( r ); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + actual.push( it.next() ); + + t.deepEqual( actual, expected, 'returns expected values' ); + t.end(); +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + + it = arrayview2iterator( values, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (context)', function test( t ) { + var expected; + var values; + var ctx; + var it; + var r; + var i; + + ctx = { + 'count': 0 + }; + values = [ 1, 2, 3, 4 ]; + + it = arrayview2iterator( values, scale, ctx ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.equal( ctx.count, values.length, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + this.count += 1; // eslint-disable-line no-invalid-this + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (begin)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + + it = arrayview2iterator( values, 1, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length-1; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length-1, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (begin<0)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + + it = arrayview2iterator( values, -3, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length-1; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length-1, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (begin+end)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + + it = arrayview2iterator( values, 1, 3, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length-2, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (begin<0+end)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + + it = arrayview2iterator( values, -3, 3, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length-2, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (begin<0+end<0)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + + it = arrayview2iterator( values, -3, -1, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length-2, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (begin+end<0)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = [ 1, 2, 3, 4 ]; + + it = arrayview2iterator( values, 1, -1, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length-2; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length-2, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the function returns an iterator protocol-compliant object which supports invoking a provided function for each iterated value (array-like)', function test( t ) { + var expected; + var values; + var it; + var r; + var i; + + values = { + 'length': 4, + '0': 1, + '1': 2, + '2': 3, + '3': 4 + }; + + it = arrayview2iterator( values, scale ); + t.equal( it.next.length, 0, 'has zero arity' ); + + expected = []; + for ( i = 0; i < values.length; i++ ) { + r = it.next(); + t.equal( r.value, expected[ i ], 'returns expected value' ); + t.equal( typeof r.done, 'boolean', 'returns a boolean' ); + } + t.equal( expected.length, values.length, 'has expected length' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + v *= i + 1; + expected.push( v ); + return v; + } +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (no argument)', function test( t ) { + var it; + var r; + + it = arrayview2iterator( [ 1, 2, 3, 4 ] ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (no argument; callback)', function test( t ) { + var it; + var r; + + it = arrayview2iterator( [ 1, 2, 3, 4 ], scale ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (argument)', function test( t ) { + var it; + var r; + + it = arrayview2iterator( [ 1, 2, 3, 4 ] ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return( 'finished' ); + t.equal( r.value, 'finished', 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); +}); + +tape( 'the returned iterator has a `return` method for closing an iterator (argument; callback)', function test( t ) { + var it; + var r; + + it = arrayview2iterator( [ 1, 2, 3, 4 ], scale ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.next(); + t.equal( typeof r.value, 'number', 'returns a number' ); + t.equal( r.done, false, 'returns expected value' ); + + r = it.return( 'finished' ); + t.equal( r.value, 'finished', 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + r = it.next(); + t.equal( r.value, void 0, 'returns expected value' ); + t.equal( r.done, true, 'returns expected value' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable', function test( t ) { + var arrayview2iterator; + var values; + var it1; + var it2; + var i; + + arrayview2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = arrayview2iterator( values ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable (begin)', function test( t ) { + var arrayview2iterator; + var values; + var it1; + var it2; + var i; + + arrayview2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = arrayview2iterator( values, 1 ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable (begin+end)', function test( t ) { + var arrayview2iterator; + var values; + var it1; + var it2; + var i; + + arrayview2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = arrayview2iterator( values, 1, 3 ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable (callback)', function test( t ) { + var arrayview2iterator; + var values; + var it1; + var it2; + var i; + + arrayview2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = arrayview2iterator( values, scale ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); + + function scale( v ) { + return v * 10.0; + } +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable (begin+callback)', function test( t ) { + var arrayview2iterator; + var values; + var it1; + var it2; + var i; + + arrayview2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = arrayview2iterator( values, 1, scale ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); + + function scale( v ) { + return v * 10.0; + } +}); + +tape( 'if an environment supports `Symbol.iterator`, the returned iterator is iterable (begin+end+callback)', function test( t ) { + var arrayview2iterator; + var values; + var it1; + var it2; + var i; + + arrayview2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': '__ITERATOR_SYMBOL__' + }); + + values = [ 1, 2, 3, 4 ]; + + it1 = arrayview2iterator( values, 1, 3, scale ); + t.equal( typeof it1[ '__ITERATOR_SYMBOL__' ], 'function', 'has method' ); + t.equal( it1[ '__ITERATOR_SYMBOL__' ].length, 0, 'has zero arity' ); + + it2 = it1[ '__ITERATOR_SYMBOL__' ](); + t.equal( typeof it2, 'object', 'returns an object' ); + t.equal( typeof it2.next, 'function', 'has method' ); + t.equal( typeof it2.return, 'function', 'has method' ); + + for ( i = 0; i < values.length; i++ ) { + t.equal( it2.next().value, it1.next().value, 'returns expected value' ); + } + t.end(); + + function scale( v ) { + return v * 10.0; + } +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable"', function test( t ) { + var arrayview2iterator; + var it; + + arrayview2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = arrayview2iterator( [ 1, 2, 3, 4 ] ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable" (begin)', function test( t ) { + var arrayview2iterator; + var it; + + arrayview2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = arrayview2iterator( [ 1, 2, 3, 4 ], 1 ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable" (begin+end)', function test( t ) { + var arrayview2iterator; + var it; + + arrayview2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = arrayview2iterator( [ 1, 2, 3, 4 ], 1, 3 ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable" (callback)', function test( t ) { + var arrayview2iterator; + var it; + + arrayview2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = arrayview2iterator( [ 1, 2, 3, 4 ], scale ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable" (begin+callback)', function test( t ) { + var arrayview2iterator; + var it; + + arrayview2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = arrayview2iterator( [ 1, 2, 3, 4 ], 1, scale ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); + +tape( 'if an environment does not support `Symbol.iterator`, the returned iterator is not "iterable" (begin+end+callback)', function test( t ) { + var arrayview2iterator; + var it; + + arrayview2iterator = proxyquire( './../lib/main.js', { + '@stdlib/symbol/iterator': false + }); + + it = arrayview2iterator( [ 1, 2, 3, 4 ], 1, 3, scale ); + t.equal( it[ iteratorSymbol ], void 0, 'does not have property' ); + + t.end(); + + function scale( v, i ) { + return v * (i+1); + } +}); diff --git a/typed-complex-ctors/README.md b/typed-complex-ctors/README.md new file mode 100644 index 00000000..ca4a4d72 --- /dev/null +++ b/typed-complex-ctors/README.md @@ -0,0 +1,116 @@ + + +# Constructors + +> Complex typed array constructors. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var ctors = require( '@stdlib/array/typed-complex-ctors' ); +``` + +#### ctors( dtype ) + +Returns a complex typed array constructor for a specified data type. + +```javascript +var ctor = ctors( 'complex128' ); +// returns +``` + +The function returns constructors for the following data types: + +- `complex64`: single-precision floating-point complex numbers. +- `complex128`: double-precision floating-point complex numbers. + +If provided an unknown or unsupported data type, the function returns `null`. + +```javascript +var ctor = ctors( 'float64' ); +// returns null +``` + +
+ + + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var dtypes = require( '@stdlib/array/typed-complex-dtypes' ); +var ctors = require( '@stdlib/array/typed-complex-ctors' ); + +var DTYPES = dtypes(); +var ctor; +var i; + +for ( i = 0; i < DTYPES.length; i++ ) { + ctor = ctors( DTYPES[ i ] ); + console.log( ctor ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/typed-complex-ctors/benchmark/benchmark.js b/typed-complex-ctors/benchmark/benchmark.js new file mode 100644 index 00000000..9ebe3a2c --- /dev/null +++ b/typed-complex-ctors/benchmark/benchmark.js @@ -0,0 +1,54 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var dtypes = require( '@stdlib/array/typed-complex-dtypes' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var pkg = require( './../package.json' ).name; +var ctors = require( './../lib' ); + + +// VARIABLES // + +var DTYPES = dtypes(); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var ctor; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + ctor = ctors( DTYPES[ i%DTYPES.length ] ); + if ( typeof ctor !== 'function' ) { + b.fail( 'should return a function' ); + } + } + b.toc(); + if ( !isFunction( ctor ) ) { + b.fail( 'should return a function' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/typed-complex-ctors/docs/repl.txt b/typed-complex-ctors/docs/repl.txt new file mode 100644 index 00000000..26678259 --- /dev/null +++ b/typed-complex-ctors/docs/repl.txt @@ -0,0 +1,29 @@ + +{{alias}}( dtype ) + Returns a complex typed array constructor. + + The function returns constructors for the following data types: + + - complex64: single-precision floating-point complex numbers. + - complex128: double-precision floating-point complex numbers. + + Parameters + ---------- + dtype: string + Data type. + + Returns + ------- + out: Function|null + Complex typed array constructor. + + Examples + -------- + > var ctor = {{alias}}( 'complex64' ) + + > ctor = {{alias}}( 'float32' ) + null + + See Also + -------- + diff --git a/typed-complex-ctors/docs/types/index.d.ts b/typed-complex-ctors/docs/types/index.d.ts new file mode 100644 index 00000000..b342893b --- /dev/null +++ b/typed-complex-ctors/docs/types/index.d.ts @@ -0,0 +1,40 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/** +* Returns a complex typed array constructor. +* +* @param dtype - data type +* @returns constructor or null +* +* @example +* var ctor = ctors( 'complex128' ); +* // returns +* +* @example +* var ctor = ctors( 'float64' ); +* // returns null +*/ +declare function ctors( dtype: string ): Function | null; + + +// EXPORTS // + +export = ctors; diff --git a/typed-complex-ctors/docs/types/test.ts b/typed-complex-ctors/docs/types/test.ts new file mode 100644 index 00000000..f23c6afd --- /dev/null +++ b/typed-complex-ctors/docs/types/test.ts @@ -0,0 +1,33 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import ctors = require( './index' ); + +// TESTS // + +// The function returns a function or null.. +{ + ctors( 'complex128' ); // $ExpectType Function | null + ctors( 'float' ); // $ExpectType Function | null +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + ctors(); // $ExpectError + ctors( 'complex128', 3 ); // $ExpectError +} diff --git a/typed-complex-ctors/examples/index.js b/typed-complex-ctors/examples/index.js new file mode 100644 index 00000000..e212f098 --- /dev/null +++ b/typed-complex-ctors/examples/index.js @@ -0,0 +1,31 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var dtypes = require( '@stdlib/array/typed-complex-dtypes' ); +var ctors = require( './../lib' ); + +var DTYPES = dtypes(); +var ctor; +var i; + +for ( i = 0; i < DTYPES.length; i++ ) { + ctor = ctors( DTYPES[ i ] ); + console.log( ctor ); +} diff --git a/typed-complex-ctors/lib/ctors.js b/typed-complex-ctors/lib/ctors.js new file mode 100644 index 00000000..5bdf1566 --- /dev/null +++ b/typed-complex-ctors/lib/ctors.js @@ -0,0 +1,38 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var Complex128Array = require( '@stdlib/array/complex128' ); +var Complex64Array = require( '@stdlib/array/complex64' ); + + +// MAIN // + +// Mapping from data types to constructors... +var ctors = { + 'complex128': Complex128Array, + 'complex64': Complex64Array +}; + + +// EXPORTS // + +module.exports = ctors; diff --git a/typed-complex-ctors/lib/index.js b/typed-complex-ctors/lib/index.js new file mode 100644 index 00000000..8d160d9b --- /dev/null +++ b/typed-complex-ctors/lib/index.js @@ -0,0 +1,43 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Complex typed array constructors. +* +* @module @stdlib/array/typed-complex-ctors +* +* @example +* var ctors = require( '@stdlib/array/typed-complex-ctors' ); +* +* var ctor = ctors( 'complex128' ); +* // returns +* +* ctor = ctors( 'float64' ); +* // returns null +*/ + +// MODULES // + +var ctors = require( './main.js' ); + + +// EXPORTS // + +module.exports = ctors; diff --git a/typed-complex-ctors/lib/main.js b/typed-complex-ctors/lib/main.js new file mode 100644 index 00000000..83f8cc72 --- /dev/null +++ b/typed-complex-ctors/lib/main.js @@ -0,0 +1,49 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var table = require( './ctors.js' ); + + +// MAIN // + +/** +* Returns a complex typed array constructor. +* +* @param {string} dtype - data type +* @returns {(Function|null)} constructor or null +* +* @example +* var ctor = ctors( 'complex128' ); +* // returns +* +* @example +* var ctor = ctors( 'float64' ); +* // returns null +*/ +function ctors( dtype ) { + return table[ dtype ] || null; +} + + +// EXPORTS // + +module.exports = ctors; diff --git a/typed-complex-ctors/package.json b/typed-complex-ctors/package.json new file mode 100644 index 00000000..128401b9 --- /dev/null +++ b/typed-complex-ctors/package.json @@ -0,0 +1,76 @@ +{ + "name": "@stdlib/array/typed-complex-ctors", + "version": "0.0.0", + "description": "Complex typed array constructors.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "array", + "typed array", + "typed-array", + "typed", + "dtypes", + "dtype", + "data", + "type", + "complex", + "cmplx", + "structure", + "constructors", + "constructor", + "ctors", + "ctor", + "utilities", + "utility", + "utils", + "util" + ], + "__stdlib__": {} +} diff --git a/typed-complex-ctors/test/test.js b/typed-complex-ctors/test/test.js new file mode 100644 index 00000000..28261103 --- /dev/null +++ b/typed-complex-ctors/test/test.js @@ -0,0 +1,107 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var dtypes = require( '@stdlib/array/typed-complex-dtypes' ); +var Complex128Array = require( '@stdlib/array/complex128' ); +var Complex64Array = require( '@stdlib/array/complex64' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var ctors = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctors, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function returns complex typed array constructors', function test( t ) { + var expected; + var dtypes; + var ctor; + var i; + + dtypes = [ + 'complex128', + 'complex64' + ]; + expected = [ + Complex128Array, + Complex64Array + ]; + for ( i = 0; i < dtypes.length; i++ ) { + ctor = ctors( dtypes[ i ] ); + t.strictEqual( ctor, expected[ i ], 'returns expected value for ' + dtypes[ i ] ); + } + t.end(); +}); + +tape( 'the function returns a constructor for each supported complex typed array data type', function test( t ) { + var DTYPES; + var ctor; + var i; + + DTYPES = dtypes(); + for ( i = 0; i < DTYPES.length; i++ ) { + ctor = ctors( DTYPES[ i ] ); + + // Note: this is a weak test for a "constructor" + t.strictEqual( isFunction( ctor ), true, 'returns a function for ' + DTYPES[ i ] ); + } + t.end(); +}); + +tape( 'if provided an unknown/unsupported data type, the function returns `null`', function test( t ) { + var dtypes; + var i; + + dtypes = [ + 'binary', + 'buffer', + 'buf', + 'generic', + 'float', + 'double', + 'single', + 'int', + 'integer', + 'uint', + 'uinteger', + 'byte', + 'bits', + 'float64', + 'float32', + 'uint32', + 'int32', + 'uint16', + 'int16', + 'uint8', + 'uint8c', + 'int8' + ]; + for ( i = 0; i < dtypes.length; i++ ) { + t.strictEqual( ctors( dtypes[i] ), null, 'returns expected value for ' + dtypes[ i ] ); + } + t.end(); +}); diff --git a/typed-complex-dtypes/README.md b/typed-complex-dtypes/README.md new file mode 100644 index 00000000..58a25f45 --- /dev/null +++ b/typed-complex-dtypes/README.md @@ -0,0 +1,122 @@ + + +# Data Types + +> List of complex typed array data types. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var dtypes = require( '@stdlib/array/typed-complex-dtypes' ); +``` + +#### dtypes() + +Returns a list of complex typed array data types. + +```javascript +var out = dtypes(); +// returns [ 'complex64', 'complex128' ] +``` + +The output `array` contains the following data types: + +- `complex64`: single-precision floating-point complex numbers. +- `complex128`: double-precision floating-point complex numbers. + +
+ + + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var indexOf = require( '@stdlib/utils/index-of' ); +var dtypes = require( '@stdlib/array/typed-complex-dtypes' ); + +var DTYPES = dtypes(); +var bool; + +function isdtype( str ) { + if ( indexOf( DTYPES, str ) === -1 ) { + return false; + } + return true; +} + +bool = isdtype( 'complex64' ); +// returns true + +bool = isdtype( 'complex128' ); +// returns true + +bool = isdtype( 'uint8' ); +// returns false + +bool = isdtype( 'beep' ); +// returns false +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/typed-complex-dtypes/benchmark/benchmark.js b/typed-complex-dtypes/benchmark/benchmark.js new file mode 100644 index 00000000..5a4dc938 --- /dev/null +++ b/typed-complex-dtypes/benchmark/benchmark.js @@ -0,0 +1,48 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives; +var pkg = require( './../package.json' ).name; +var dtypes = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = dtypes(); + if ( out.length !== 2 ) { + b.fail( 'should return an array of length 2' ); + } + } + b.toc(); + if ( !isStringArray( out ) ) { + b.fail( 'should return an array of strings' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/typed-complex-dtypes/docs/repl.txt b/typed-complex-dtypes/docs/repl.txt new file mode 100644 index 00000000..fc4b8f87 --- /dev/null +++ b/typed-complex-dtypes/docs/repl.txt @@ -0,0 +1,22 @@ + +{{alias}}() + Returns a list of complex typed array data types. + + The output array contains the following data types: + + - complex64: single-precision floating-point complex numbers. + - complex128: double-precision floating-point complex numbers. + + Returns + ------- + out: Array + List of complex typed array data types. + + Examples + -------- + > var out = {{alias}}() + + + See Also + -------- + diff --git a/typed-complex-dtypes/docs/types/index.d.ts b/typed-complex-dtypes/docs/types/index.d.ts new file mode 100644 index 00000000..88c9b1ef --- /dev/null +++ b/typed-complex-dtypes/docs/types/index.d.ts @@ -0,0 +1,35 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/** +* Returns a list of complex typed array data types. +* +* @returns list of complex typed array data types +* +* @example +* var list = dtypes(); +* // returns [ 'complex64', 'complex128' ] +*/ +declare function dtypes(): Array; + + +// EXPORTS // + +export = dtypes; diff --git a/typed-complex-dtypes/docs/types/test.ts b/typed-complex-dtypes/docs/types/test.ts new file mode 100644 index 00000000..a80e01d2 --- /dev/null +++ b/typed-complex-dtypes/docs/types/test.ts @@ -0,0 +1,32 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import dtypes = require( './index' ); + +// TESTS // + +// The function returns a string array.. +{ + dtypes(); // $ExpectType string[] +} + +// The compiler throws an error if the function is provided arguments... +{ + dtypes( 1 ); // $ExpectError + dtypes( 1, 2 ); // $ExpectError +} diff --git a/typed-complex-dtypes/examples/index.js b/typed-complex-dtypes/examples/index.js new file mode 100644 index 00000000..d3c89dd4 --- /dev/null +++ b/typed-complex-dtypes/examples/index.js @@ -0,0 +1,48 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var indexOf = require( '@stdlib/utils/index-of' ); +var dtypes = require( './../lib' ); + +var DTYPES = dtypes(); +var bool; + +function isdtype( str ) { + if ( indexOf( DTYPES, str ) === -1 ) { + return false; + } + return true; +} + +bool = isdtype( 'complex64' ); +console.log( bool ); +// => true + +bool = isdtype( 'complex128' ); +console.log( bool ); +// => true + +bool = isdtype( 'uint16' ); +console.log( bool ); +// => false + +bool = isdtype( 'beep' ); +console.log( bool ); +// => false diff --git a/typed-complex-dtypes/lib/dtypes.json b/typed-complex-dtypes/lib/dtypes.json new file mode 100644 index 00000000..52bb4a17 --- /dev/null +++ b/typed-complex-dtypes/lib/dtypes.json @@ -0,0 +1,4 @@ +[ + "complex64", + "complex128" +] diff --git a/typed-complex-dtypes/lib/index.js b/typed-complex-dtypes/lib/index.js new file mode 100644 index 00000000..ac60acbd --- /dev/null +++ b/typed-complex-dtypes/lib/index.js @@ -0,0 +1,40 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Return a list of complex typed array data types. +* +* @module @stdlib/array/typed-complex-dtypes +* +* @example +* var dtypes = require( '@stdlib/array/typed-complex-dtypes' ); +* +* var list = dtypes(); +* // returns [ 'complex64', 'complex128' ] +*/ + +// MODULES // + +var dtypes = require( './main.js' ); + + +// EXPORTS // + +module.exports = dtypes; diff --git a/typed-complex-dtypes/lib/main.js b/typed-complex-dtypes/lib/main.js new file mode 100644 index 00000000..3701cc0d --- /dev/null +++ b/typed-complex-dtypes/lib/main.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var DTYPES = require( './dtypes.json' ); + + +// MAIN // + +/** +* Returns a list of complex typed array data types. +* +* @returns {StringArray} list of complex typed array data types +* +* @example +* var list = dtypes(); +* // returns [ 'complex64', 'complex128' ] +*/ +function dtypes() { + return DTYPES.slice(); +} + + +// EXPORTS // + +module.exports = dtypes; diff --git a/typed-complex-dtypes/package.json b/typed-complex-dtypes/package.json new file mode 100644 index 00000000..6676c7ce --- /dev/null +++ b/typed-complex-dtypes/package.json @@ -0,0 +1,69 @@ +{ + "name": "@stdlib/array/typed-complex-dtypes", + "version": "0.0.0", + "description": "List of complex typed array data types.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "typed", + "array", + "complex", + "cmplx", + "dtypes", + "dtype", + "data", + "type", + "utilities", + "utility", + "utils", + "util" + ], + "__stdlib__": {} +} diff --git a/typed-complex-dtypes/test/test.js b/typed-complex-dtypes/test/test.js new file mode 100644 index 00000000..1b546ff3 --- /dev/null +++ b/typed-complex-dtypes/test/test.js @@ -0,0 +1,47 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var dtypes = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof dtypes, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function returns a list of complex typed array data types', function test( t ) { + var expected; + var actual; + + expected = [ + 'complex64', + 'complex128' + ]; + actual = dtypes(); + + t.deepEqual( actual, expected, 'returns expected value' ); + t.end(); +}); diff --git a/typed-ctors/README.md b/typed-ctors/README.md new file mode 100644 index 00000000..014fc70c --- /dev/null +++ b/typed-ctors/README.md @@ -0,0 +1,123 @@ + + +# Constructors + +> Typed array constructors. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var ctors = require( '@stdlib/array/typed-ctors' ); +``` + +#### ctors( dtype ) + +Returns a typed array constructor for a specified data type. + +```javascript +var ctor = ctors( 'float64' ); +// returns +``` + +The function returns constructors for the following data types: + +- `float32`: single-precision floating-point numbers. +- `float64`: double-precision floating-point numbers. +- `int16`: signed 16-bit integers. +- `int32`: signed 32-bit integers. +- `int8`: signed 8-bit integers. +- `uint16`: unsigned 16-bit integers. +- `uint32`: unsigned 32-bit integers. +- `uint8`: unsigned 8-bit integers. +- `uint8c`: unsigned clamped 8-bit integers. + +If provided an unknown or unsupported data type, the function returns `null`. + +```javascript +var ctor = ctors( 'float' ); +// returns null +``` + +
+ + + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var dtypes = require( '@stdlib/array/typed-dtypes' ); +var ctors = require( '@stdlib/array/typed-ctors' ); + +var DTYPES = dtypes(); +var ctor; +var i; + +for ( i = 0; i < DTYPES.length; i++ ) { + ctor = ctors( DTYPES[ i ] ); + console.log( ctor ); +} +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/typed-ctors/benchmark/benchmark.js b/typed-ctors/benchmark/benchmark.js new file mode 100644 index 00000000..8e22b67b --- /dev/null +++ b/typed-ctors/benchmark/benchmark.js @@ -0,0 +1,54 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var dtypes = require( '@stdlib/array/typed-dtypes' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var pkg = require( './../package.json' ).name; +var ctors = require( './../lib' ); + + +// VARIABLES // + +var DTYPES = dtypes(); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var ctor; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + ctor = ctors( DTYPES[ i%DTYPES.length ] ); + if ( typeof ctor !== 'function' ) { + b.fail( 'should return a function' ); + } + } + b.toc(); + if ( !isFunction( ctor ) ) { + b.fail( 'should return a function' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/typed-ctors/docs/repl.txt b/typed-ctors/docs/repl.txt new file mode 100644 index 00000000..335f22ad --- /dev/null +++ b/typed-ctors/docs/repl.txt @@ -0,0 +1,36 @@ + +{{alias}}( dtype ) + Returns a typed array constructor. + + The function returns constructors for the following data types: + + - float32: single-precision floating-point numbers. + - float64: double-precision floating-point numbers. + - int16: signed 16-bit integers. + - int32: signed 32-bit integers. + - int8: signed 8-bit integers. + - uint16: unsigned 16-bit integers. + - uint32: unsigned 32-bit integers. + - uint8: unsigned 8-bit integers. + - uint8c: unsigned clamped 8-bit integers. + + Parameters + ---------- + dtype: string + Data type. + + Returns + ------- + out: Function|null + Typed array constructor. + + Examples + -------- + > var ctor = {{alias}}( 'float64' ) + + > ctor = {{alias}}( 'float' ) + null + + See Also + -------- + diff --git a/typed-ctors/docs/types/index.d.ts b/typed-ctors/docs/types/index.d.ts new file mode 100644 index 00000000..c6df6ecf --- /dev/null +++ b/typed-ctors/docs/types/index.d.ts @@ -0,0 +1,40 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/** +* Returns a typed array constructor. +* +* @param dtype - data type +* @returns constructor or null +* +* @example +* var ctor = ctors( 'float64' ); +* // returns +* +* @example +* var ctor = ctors( 'float' ); +* // returns null +*/ +declare function ctors( dtype: string ): Function | null; + + +// EXPORTS // + +export = ctors; diff --git a/typed-ctors/docs/types/test.ts b/typed-ctors/docs/types/test.ts new file mode 100644 index 00000000..d853f896 --- /dev/null +++ b/typed-ctors/docs/types/test.ts @@ -0,0 +1,33 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import ctors = require( './index' ); + +// TESTS // + +// The function returns a function or null.. +{ + ctors( 'float64' ); // $ExpectType Function | null + ctors( 'float' ); // $ExpectType Function | null +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + ctors(); // $ExpectError + ctors( 'int32', 3 ); // $ExpectError +} diff --git a/typed-ctors/examples/index.js b/typed-ctors/examples/index.js new file mode 100644 index 00000000..77646dfc --- /dev/null +++ b/typed-ctors/examples/index.js @@ -0,0 +1,31 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var dtypes = require( '@stdlib/array/typed-dtypes' ); +var ctors = require( './../lib' ); + +var DTYPES = dtypes(); +var ctor; +var i; + +for ( i = 0; i < DTYPES.length; i++ ) { + ctor = ctors( DTYPES[ i ] ); + console.log( ctor ); +} diff --git a/typed-ctors/lib/ctors.js b/typed-ctors/lib/ctors.js new file mode 100644 index 00000000..62c26535 --- /dev/null +++ b/typed-ctors/lib/ctors.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var Float64Array = require( '@stdlib/array/float64' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Int8Array = require( '@stdlib/array/int8' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); + + +// MAIN // + +// Mapping from data types to constructors... +var ctors = { + 'float64': Float64Array, + 'float32': Float32Array, + 'int16': Int16Array, + 'int32': Int32Array, + 'int8': Int8Array, + 'uint16': Uint16Array, + 'uint32': Uint32Array, + 'uint8': Uint8Array, + 'uint8c': Uint8ClampedArray +}; + + +// EXPORTS // + +module.exports = ctors; diff --git a/typed-ctors/lib/index.js b/typed-ctors/lib/index.js new file mode 100644 index 00000000..b7b83312 --- /dev/null +++ b/typed-ctors/lib/index.js @@ -0,0 +1,43 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Typed array constructors. +* +* @module @stdlib/array/typed-ctors +* +* @example +* var ctors = require( '@stdlib/array/typed-ctors' ); +* +* var ctor = ctors( 'float64' ); +* // returns +* +* ctor = ctors( 'int' ); +* // returns null +*/ + +// MODULES // + +var ctors = require( './main.js' ); + + +// EXPORTS // + +module.exports = ctors; diff --git a/typed-ctors/lib/main.js b/typed-ctors/lib/main.js new file mode 100644 index 00000000..d045f901 --- /dev/null +++ b/typed-ctors/lib/main.js @@ -0,0 +1,49 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var table = require( './ctors.js' ); + + +// MAIN // + +/** +* Returns a typed array constructor. +* +* @param {string} dtype - data type +* @returns {(Function|null)} constructor or null +* +* @example +* var ctor = ctors( 'float64' ); +* // returns +* +* @example +* var ctor = ctors( 'float' ); +* // returns null +*/ +function ctors( dtype ) { + return table[ dtype ] || null; +} + + +// EXPORTS // + +module.exports = ctors; diff --git a/typed-ctors/package.json b/typed-ctors/package.json new file mode 100644 index 00000000..1ce679c2 --- /dev/null +++ b/typed-ctors/package.json @@ -0,0 +1,74 @@ +{ + "name": "@stdlib/array/typed-ctors", + "version": "0.0.0", + "description": "Typed array constructors.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "array", + "typed array", + "typed-array", + "typed", + "dtypes", + "dtype", + "data", + "type", + "structure", + "constructors", + "constructor", + "ctors", + "ctor", + "utilities", + "utility", + "utils", + "util" + ], + "__stdlib__": {} +} diff --git a/typed-ctors/test/test.js b/typed-ctors/test/test.js new file mode 100644 index 00000000..60248b0d --- /dev/null +++ b/typed-ctors/test/test.js @@ -0,0 +1,119 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var dtypes = require( '@stdlib/array/typed-dtypes' ); +var Float64Array = require( '@stdlib/array/float64' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Int8Array = require( '@stdlib/array/int8' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var ctors = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctors, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function returns typed array constructors', function test( t ) { + var expected; + var dtypes; + var ctor; + var i; + + dtypes = [ + 'float64', + 'float32', + 'int16', + 'int32', + 'int8', + 'uint16', + 'uint32', + 'uint8', + 'uint8c' + ]; + expected = [ + Float64Array, + Float32Array, + Int16Array, + Int32Array, + Int8Array, + Uint16Array, + Uint32Array, + Uint8Array, + Uint8ClampedArray + ]; + for ( i = 0; i < dtypes.length; i++ ) { + ctor = ctors( dtypes[ i ] ); + t.strictEqual( ctor, expected[ i ], 'returns expected value for ' + dtypes[ i ] ); + } + t.end(); +}); + +tape( 'the function returns a constructor for each supported typed array data type', function test( t ) { + var DTYPES; + var ctor; + var i; + + DTYPES = dtypes(); + for ( i = 0; i < DTYPES.length; i++ ) { + ctor = ctors( DTYPES[ i ] ); + + // Note: this is a weak test for a "constructor" + t.strictEqual( isFunction( ctor ), true, 'returns a function for ' + DTYPES[ i ] ); + } + t.end(); +}); + +tape( 'if provided an unknown/unsupported data type, the function returns `null`', function test( t ) { + var dtypes; + var i; + + dtypes = [ + 'binary', + 'buffer', + 'buf', + 'generic', + 'float', + 'double', + 'single', + 'int', + 'integer', + 'uint', + 'uinteger', + 'byte', + 'bits' + ]; + for ( i = 0; i < dtypes.length; i++ ) { + t.strictEqual( ctors( dtypes[i] ), null, 'returns expected value for ' + dtypes[ i ] ); + } + t.end(); +}); diff --git a/typed-dtypes/README.md b/typed-dtypes/README.md new file mode 100644 index 00000000..fc227862 --- /dev/null +++ b/typed-dtypes/README.md @@ -0,0 +1,129 @@ + + +# Data Types + +> List of typed array data types. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var dtypes = require( '@stdlib/array/typed-dtypes' ); +``` + +#### dtypes() + +Returns a list of typed array data types. + +```javascript +var out = dtypes(); +// returns [ 'float32', 'float64', 'int16', 'int32', 'int8', 'uint16', 'uint32', 'uint8', 'uint8c' ] +``` + +The output `array` contains the following data types: + +- `float32`: single-precision floating-point numbers. +- `float64`: double-precision floating-point numbers. +- `int16`: signed 16-bit integers. +- `int32`: signed 32-bit integers. +- `int8`: signed 8-bit integers. +- `uint16`: unsigned 16-bit integers. +- `uint32`: unsigned 32-bit integers. +- `uint8`: unsigned 8-bit integers. +- `uint8c`: unsigned clamped 8-bit integers. + +
+ + + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var indexOf = require( '@stdlib/utils/index-of' ); +var dtypes = require( '@stdlib/array/typed-dtypes' ); + +var DTYPES = dtypes(); +var bool; + +function isdtype( str ) { + if ( indexOf( DTYPES, str ) === -1 ) { + return false; + } + return true; +} + +bool = isdtype( 'float64' ); +// returns true + +bool = isdtype( 'int16' ); +// returns true + +bool = isdtype( 'uint8' ); +// returns true + +bool = isdtype( 'beep' ); +// returns false +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/typed-dtypes/benchmark/benchmark.js b/typed-dtypes/benchmark/benchmark.js new file mode 100644 index 00000000..ba32525f --- /dev/null +++ b/typed-dtypes/benchmark/benchmark.js @@ -0,0 +1,48 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives; +var pkg = require( './../package.json' ).name; +var dtypes = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = dtypes(); + if ( out.length !== 9 ) { + b.fail( 'should return an array of length 9' ); + } + } + b.toc(); + if ( !isStringArray( out ) ) { + b.fail( 'should return an array of strings' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/typed-dtypes/docs/repl.txt b/typed-dtypes/docs/repl.txt new file mode 100644 index 00000000..7388bc13 --- /dev/null +++ b/typed-dtypes/docs/repl.txt @@ -0,0 +1,29 @@ + +{{alias}}() + Returns a list of typed array data types. + + The output array contains the following data types: + + - float32: single-precision floating-point numbers. + - float64: double-precision floating-point numbers. + - int16: signed 16-bit integers. + - int32: signed 32-bit integers. + - int8: signed 8-bit integers. + - uint16: unsigned 16-bit integers. + - uint32: unsigned 32-bit integers. + - uint8: unsigned 8-bit integers. + - uint8c: unsigned clamped 8-bit integers. + + Returns + ------- + out: Array + List of typed array data types. + + Examples + -------- + > var out = {{alias}}() + + + See Also + -------- + diff --git a/typed-dtypes/docs/types/index.d.ts b/typed-dtypes/docs/types/index.d.ts new file mode 100644 index 00000000..36e41108 --- /dev/null +++ b/typed-dtypes/docs/types/index.d.ts @@ -0,0 +1,35 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +/** +* Returns a list of typed array data types. +* +* @returns list of typed array data types +* +* @example +* var list = dtypes(); +* // returns [ 'float32', 'float64', 'int16', 'int32', 'int8', 'uint16', 'uint32', 'uint8', 'uint8c' ] +*/ +declare function dtypes(): Array; + + +// EXPORTS // + +export = dtypes; diff --git a/typed-dtypes/docs/types/test.ts b/typed-dtypes/docs/types/test.ts new file mode 100644 index 00000000..a80e01d2 --- /dev/null +++ b/typed-dtypes/docs/types/test.ts @@ -0,0 +1,32 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import dtypes = require( './index' ); + +// TESTS // + +// The function returns a string array.. +{ + dtypes(); // $ExpectType string[] +} + +// The compiler throws an error if the function is provided arguments... +{ + dtypes( 1 ); // $ExpectError + dtypes( 1, 2 ); // $ExpectError +} diff --git a/typed-dtypes/examples/index.js b/typed-dtypes/examples/index.js new file mode 100644 index 00000000..441447aa --- /dev/null +++ b/typed-dtypes/examples/index.js @@ -0,0 +1,48 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var indexOf = require( '@stdlib/utils/index-of' ); +var dtypes = require( './../lib' ); + +var DTYPES = dtypes(); +var bool; + +function isdtype( str ) { + if ( indexOf( DTYPES, str ) === -1 ) { + return false; + } + return true; +} + +bool = isdtype( 'float64' ); +console.log( bool ); +// => true + +bool = isdtype( 'int8' ); +console.log( bool ); +// => true + +bool = isdtype( 'uint16' ); +console.log( bool ); +// => true + +bool = isdtype( 'beep' ); +console.log( bool ); +// => false diff --git a/typed-dtypes/lib/dtypes.json b/typed-dtypes/lib/dtypes.json new file mode 100644 index 00000000..e6e79bc7 --- /dev/null +++ b/typed-dtypes/lib/dtypes.json @@ -0,0 +1,11 @@ +[ + "float32", + "float64", + "int16", + "int32", + "int8", + "uint16", + "uint32", + "uint8", + "uint8c" +] diff --git a/typed-dtypes/lib/index.js b/typed-dtypes/lib/index.js new file mode 100644 index 00000000..2ec58352 --- /dev/null +++ b/typed-dtypes/lib/index.js @@ -0,0 +1,40 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Return a list of typed array data types. +* +* @module @stdlib/array/typed-dtypes +* +* @example +* var dtypes = require( '@stdlib/array/typed-dtypes' ); +* +* var list = dtypes(); +* // returns [ 'float32', 'float64', 'int16', 'int32', 'int8', 'uint16', 'uint32', 'uint8', 'uint8c' ] +*/ + +// MODULES // + +var dtypes = require( './main.js' ); + + +// EXPORTS // + +module.exports = dtypes; diff --git a/typed-dtypes/lib/main.js b/typed-dtypes/lib/main.js new file mode 100644 index 00000000..a07d90e2 --- /dev/null +++ b/typed-dtypes/lib/main.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var DTYPES = require( './dtypes.json' ); + + +// MAIN // + +/** +* Returns a list of typed array data types. +* +* @returns {StringArray} list of typed array data types +* +* @example +* var list = dtypes(); +* // returns [ 'float32', 'float64', 'int16', 'int32', 'int8', 'uint16', 'uint32', 'uint8', 'uint8c' ] +*/ +function dtypes() { + return DTYPES.slice(); +} + + +// EXPORTS // + +module.exports = dtypes; diff --git a/typed-dtypes/package.json b/typed-dtypes/package.json new file mode 100644 index 00000000..e54c50f1 --- /dev/null +++ b/typed-dtypes/package.json @@ -0,0 +1,67 @@ +{ + "name": "@stdlib/array/typed-dtypes", + "version": "0.0.0", + "description": "List of typed array data types.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "typed", + "array", + "dtypes", + "dtype", + "data", + "type", + "utilities", + "utility", + "utils", + "util" + ], + "__stdlib__": {} +} diff --git a/typed-dtypes/test/test.js b/typed-dtypes/test/test.js new file mode 100644 index 00000000..8dc7ed09 --- /dev/null +++ b/typed-dtypes/test/test.js @@ -0,0 +1,54 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var dtypes = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof dtypes, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function returns a list of typed array data types', function test( t ) { + var expected; + var actual; + + expected = [ + 'float32', + 'float64', + 'int16', + 'int32', + 'int8', + 'uint16', + 'uint32', + 'uint8', + 'uint8c' + ]; + actual = dtypes(); + + t.deepEqual( actual, expected, 'returns expected value' ); + t.end(); +}); diff --git a/typed/README.md b/typed/README.md new file mode 100644 index 00000000..5a20b3ec --- /dev/null +++ b/typed/README.md @@ -0,0 +1,193 @@ + + +# Typed Arrays + +> Create a typed array. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var typedarray = require( '@stdlib/array/typed' ); +``` + +#### typedarray( \[dtype] ) + +Creates a [typed array][mdn-typed-array] having a specified data type `dtype`. + +```javascript +var arr = typedarray(); +// returns +``` + +The function recognizes the following data types: + +- `float64`: double-precision floating-point numbers (IEEE 754) +- `float32`: single-precision floating-point numbers (IEEE 754) +- `int32`: 32-bit two's complement signed integers +- `uint32`: 32-bit unsigned integers +- `int16`: 16-bit two's complement signed integers +- `uint16`: 16-bit unsigned integers +- `int8`: 8-bit two's complement signed integers +- `uint8`: 8-bit unsigned integers +- `uint8c`: 8-bit unsigned integers clamped to `0-255` + +By default, the output [typed array][mdn-typed-array] data type is `float64`. To specify an alternative data type, provide a `dtype` argument. + +```javascript +var arr = typedarray( 'int32' ); +// returns +``` + +#### typedarray( length\[, dtype] ) + +Returns a [typed array][mdn-typed-array] having a specified `length`. + +```javascript +var arr1 = typedarray( 5 ); +// returns [ 0.0, 0.0, 0.0, 0.0, 0.0 ] + +var arr2 = typedarray( 5, 'uint8' ); +// returns [ 0, 0, 0, 0, 0 ] +``` + +#### typedarray( typedarray\[, dtype] ) + +Creates a [typed array][mdn-typed-array] from another [typed array][mdn-typed-array]. + +```javascript +var arr1 = typedarray( [ 5.0, -3.0, 2.0 ] ); +// returns [ 5.0, -3.0, 2.0 ] + +var arr2 = typedarray( arr1 ); +// returns [ 5.0, -3.0, 2.0 ] + +var arr3 = typedarray( arr1, 'int32' ); +// returns [ 5, -3, 2 ] +``` + +#### typedarray( obj\[, dtype] ) + +Creates a [typed array][mdn-typed-array] from an array-like `object` or iterable. + +```javascript +var arr1 = typedarray( [ 0.5, 0.5, 0.5 ] ); +// returns [ 0.5, 0.5, 0.5 ] + +var arr2 = typedarray( [ 0.5, 0.5, 0.5 ], 'float32' ); +// returns [ 0.5, 0.5, 0.5 ] +``` + +#### typedarray( buffer\[, byteOffset\[, length]]\[, dtype] ) + +Returns a [typed array][mdn-typed-array] view of an [`ArrayBuffer`][mdn-arraybuffer]. + +```javascript +var ArrayBuffer = require( '@stdlib/array/buffer' ); +var buf = new ArrayBuffer( 32 ); + +var arr1 = typedarray( buf ); +// returns [ 0.0, 0.0, 0.0, 0.0 ] + +var arr2 = typedarray( buf, 'float32' ); +// returns [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ] + +var arr3 = typedarray( buf, 16 ); +// returns [ 0.0, 0.0 ] + +var arr4 = typedarray( buf, 16, 'float32' ); +// returns [ 0.0, 0.0, 0.0, 0.0 ] + +var arr5 = typedarray( buf, 16, 1 ); +// returns [ 0.0 ] + +var arr6 = typedarray( buf, 10, 4, 'int16' ); +// returns [ 0, 0, 0, 0 ] +``` + +
+ + + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var randu = require( '@stdlib/random/base/randu' ); +var typedarray = require( '@stdlib/array/typed' ); + +var arr; +var i; + +arr = typedarray( 100, 'float64' ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = randu() * 100.0; +} +console.log( arr ); +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/typed/benchmark/benchmark.js b/typed/benchmark/benchmark.js new file mode 100644 index 00000000..d989beaa --- /dev/null +++ b/typed/benchmark/benchmark.js @@ -0,0 +1,209 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0 ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=float64', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0, 'float64' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=float32', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0, 'float32' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=int32', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0, 'int32' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint32', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0, 'uint32' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=int16', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0, 'int16' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint16', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0, 'uint16' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=int8', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0, 'int8' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint8', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0, 'uint8' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+':dtype=uint8c', function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( 0, 'uint8c' ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/typed/benchmark/benchmark.length.float32.js b/typed/benchmark/benchmark.length.float32.js new file mode 100644 index 00000000..316a3d1e --- /dev/null +++ b/typed/benchmark/benchmark.length.float32.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( len, 'float32' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':dtype=float32,len='+len, f ); + } +} + +main(); diff --git a/typed/benchmark/benchmark.length.float64.js b/typed/benchmark/benchmark.length.float64.js new file mode 100644 index 00000000..3693b12a --- /dev/null +++ b/typed/benchmark/benchmark.length.float64.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( len, 'float64' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':dtype=float64,len='+len, f ); + } +} + +main(); diff --git a/typed/benchmark/benchmark.length.int16.js b/typed/benchmark/benchmark.length.int16.js new file mode 100644 index 00000000..39946d32 --- /dev/null +++ b/typed/benchmark/benchmark.length.int16.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( len, 'int16' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':dtype=int16,len='+len, f ); + } +} + +main(); diff --git a/typed/benchmark/benchmark.length.int32.js b/typed/benchmark/benchmark.length.int32.js new file mode 100644 index 00000000..32a75125 --- /dev/null +++ b/typed/benchmark/benchmark.length.int32.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( len, 'int32' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':dtype=int32,len='+len, f ); + } +} + +main(); diff --git a/typed/benchmark/benchmark.length.int8.js b/typed/benchmark/benchmark.length.int8.js new file mode 100644 index 00000000..fdd4fa3a --- /dev/null +++ b/typed/benchmark/benchmark.length.int8.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( len, 'int8' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':dtype=int8,len='+len, f ); + } +} + +main(); diff --git a/typed/benchmark/benchmark.length.uint16.js b/typed/benchmark/benchmark.length.uint16.js new file mode 100644 index 00000000..1c92537b --- /dev/null +++ b/typed/benchmark/benchmark.length.uint16.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( len, 'uint16' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':dtype=uint16,len='+len, f ); + } +} + +main(); diff --git a/typed/benchmark/benchmark.length.uint32.js b/typed/benchmark/benchmark.length.uint32.js new file mode 100644 index 00000000..069fbf2a --- /dev/null +++ b/typed/benchmark/benchmark.length.uint32.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( len, 'uint32' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':dtype=uint32,len='+len, f ); + } +} + +main(); diff --git a/typed/benchmark/benchmark.length.uint8.js b/typed/benchmark/benchmark.length.uint8.js new file mode 100644 index 00000000..74f2179f --- /dev/null +++ b/typed/benchmark/benchmark.length.uint8.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( len, 'uint8' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':dtype=uint8,len='+len, f ); + } +} + +main(); diff --git a/typed/benchmark/benchmark.length.uint8c.js b/typed/benchmark/benchmark.length.uint8c.js new file mode 100644 index 00000000..3b11bd99 --- /dev/null +++ b/typed/benchmark/benchmark.length.uint8c.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isTypedArray = require( '@stdlib/assert/is-typed-array' ); +var pkg = require( './../package.json' ).name; +var typedarray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = typedarray( len, 'uint8c' ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isTypedArray( arr ) ) { + b.fail( 'should return a typed array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':dtype=uint8c,len='+len, f ); + } +} + +main(); diff --git a/typed/docs/repl.txt b/typed/docs/repl.txt new file mode 100644 index 00000000..0a9881ff --- /dev/null +++ b/typed/docs/repl.txt @@ -0,0 +1,139 @@ + +{{alias}}( [dtype] ) + Creates a typed array. + + The function supports the following data types: + + - float64: double-precision floating-point numbers (IEEE 754) + - float32: single-precision floating-point numbers (IEEE 754) + - int32: 32-bit two's complement signed integers + - uint32: 32-bit unsigned integers + - int16: 16-bit two's complement signed integers + - uint16: 16-bit unsigned integers + - int8: 8-bit two's complement signed integers + - uint8: 8-bit unsigned integers + - uint8c: 8-bit unsigned integers clamped to 0-255 + + The default typed array data type is `float64`. + + Parameters + ---------- + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray + A typed array. + + Examples + -------- + > var arr = {{alias}}() + + > arr = {{alias}}( 'float32' ) + + + +{{alias}}( length[, dtype] ) + Returns a typed array having a specified length. + + Parameters + ---------- + length: integer + Typed array length. + + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray + A typed array. + + Examples + -------- + > var arr = {{alias}}( 5 ) + [ 0.0, 0.0, 0.0, 0.0, 0.0 ] + > arr = {{alias}}( 5, 'int32' ) + [ 0, 0, 0, 0, 0 ] + + +{{alias}}( typedarray[, dtype] ) + Creates a typed array from another typed array. + + Parameters + ---------- + typedarray: TypedArray + Typed array from which to generate another typed array. + + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray + A typed array. + + Examples + -------- + > var arr1 = {{alias}}( [ 0.5, 0.5, 0.5 ] ); + > var arr2 = {{alias}}( arr1, 'float32' ) + [ 0.5, 0.5, 0.5 ] + + +{{alias}}( obj[, dtype] ) + Creates a typed array from an array-like object or iterable. + + Parameters + ---------- + obj: Object + Array-like object or iterable from which to generate a typed array. + + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray + A typed array. + + Examples + -------- + > var arr1 = [ 0.5, 0.5, 0.5 ]; + > var arr2 = {{alias}}( arr1, 'float32' ) + [ 0.5, 0.5, 0.5 ] + + +{{alias}}( buffer[, byteOffset[, length]][, dtype] ) + Returns a typed array view of an ArrayBuffer. + + Parameters + ---------- + buffer: ArrayBuffer + Underlying ArrayBuffer. + + byteOffset: integer (optional) + Integer byte offset specifying the location of the first typed array + element. Default: 0. + + length: integer (optional) + View length. If not provided, the view spans from the byteOffset to + the end of the underlying ArrayBuffer. + + dtype: string (optional) + Data type. Default: 'float64'. + + Returns + ------- + out: TypedArray + A typed array. + + Examples + -------- + > var buf = new {{alias:@stdlib/array/buffer}}( 16 ); + > var arr = {{alias}}( buf, 0, 4, 'float32' ) + [ 0.0, 0.0, 0.0, 0.0 ] + + See Also + -------- + diff --git a/typed/docs/types/index.d.ts b/typed/docs/types/index.d.ts new file mode 100644 index 00000000..971f468c --- /dev/null +++ b/typed/docs/types/index.d.ts @@ -0,0 +1,182 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +// tslint:disable:unified-signatures + +/// + +import { ArrayLike, TypedArray } from '@stdlib/types/array'; +import ArrayBuffer = require( '@stdlib/array/buffer' ); + +type DType = 'float64' | 'float32' | 'int32' | 'uint32' | 'int16' | 'uint16' | 'int8' | 'uint8' | 'uint8c'; // tslint:disable-line:max-line-length + +/** +* Creates a typed array. +* +* @param dtype - data type (default: 'float64') +* @returns typed array +* +* @example +* var arr = typedarray(); +* // returns +* +* @example +* var arr = typedarray( 'float32'); +* // returns +*/ +declare function typedarray( dtype?: DType ): TypedArray; + +/** +* Creates a typed array. +* +* @param length - typed array length +* @param dtype - data type (default: 'float64') +* @returns typed array +* +* @example +* var arr = typedarray( 2 ); +* // returns [ 0.0, 0.0 ] +* +* @example +* var arr = typedarray( 2, 'float32' ); +* // returns [ 0.0, 0.0 ] +*/ +declare function typedarray( length: number, dtype?: DType ): TypedArray; + +/** +* Creates a typed array. +* +* @param typedarray - typed array from which to generate another typed array +* @param dtype - data type (default: 'float64') +* @returns typed array +* +* @example +* var arr = typedarray( new Float64Array( 2 ) ); +* // returns [ 0.0, 0.0 ] +* +* @example +* var arr = typedarray( new Float64Array( 2 ), 'float32' ); +* // returns [ 0.0, 0.0 ] +* +* @example +* var arr1 = typedarray( [ 5, 3 ], 'int32' ); +* var arr2 = typedarray( arr1 ); +* // returns [ 5.0, 3.0 ] +* +* @example +* var arr1 = typedarray( [ 5, 3 ], 'int32' ); +* var arr2 = typedarray( arr1, 'uint32' ); +* // returns [ 5, 3 ] +*/ +declare function typedarray( typedarray: TypedArray, dtype?: DType ): TypedArray; // tslint:disable-line:max-line-length + +/** +* Creates a typed array. +* +* @param obj - array-like object or iterable from which to generate a typed array +* @param dtype - data type (default: 'float64') +* @returns typed array +* +* @example +* var arr = typedarray( [ 0.5, 0.5 ] ); +* // returns [ 0.5, 0.5 ] +* +* @example +* var arr = typedarray( [ 5, -3 ], 'int32' ); +* // returns [ 5, -3 ] +*/ +declare function typedarray( obj: ArrayLike | Iterable, dtype?: DType ): TypedArray; // tslint:disable-line:max-line-length + +/** +* Creates a typed array. +* +* @param buffer - underlying ArrayBuffer +* @param dtype - data type (default: 'float64') +* @returns typed array +* +* @example +* var ArrayBuffer = require( `@stdlib/array/buffer` ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = typedarray( buf ); +* // returns [ 0.0, 0.0 ] +* +* @example +* var ArrayBuffer = require( `@stdlib/array/buffer` ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = typedarray( buf, 'float32' ); +* // returns [ 0.0, 0.0, 0.0, 0.0 ] +*/ +declare function typedarray( buffer: ArrayBuffer, dtype?: DType ): TypedArray; + +/** +* Creates a typed array. +* +* @param buffer - underlying ArrayBuffer +* @param byteOffset - integer byte offset specifying the location of the first typed array element (default: 0) +* @param dtype - data type (default: 'float64') +* @returns typed array +* +* @example +* var ArrayBuffer = require( `@stdlib/array/buffer` ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = typedarray( buf, 8 ); +* // returns [ 0.0 ] +* +* @example +* var ArrayBuffer = require( `@stdlib/array/buffer` ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = typedarray( buf, 8, 'float32' ); +* // returns [ 0.0, 0.0 ] +*/ +declare function typedarray( buffer: ArrayBuffer, byteOffset?: number, dtype?: DType ): TypedArray; // tslint:disable-line:max-line-length + +/** +* Creates a typed array. +* +* @param buffer - underlying ArrayBuffer +* @param byteOffset - integer byte offset specifying the location of the first typed array element (default: 0) +* @param length - view length; if not provided, the view spans from the byteOffset to the end of the underlying ArrayBuffer +* @param dtype - data type (default: 'float64') +* @returns typed array +* +* @example +* var ArrayBuffer = require( `@stdlib/array/buffer` ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = typedarray( buf, 8, 2 ); +* // returns [ 0.0, 0.0 ] +* +* @example +* var ArrayBuffer = require( `@stdlib/array/buffer` ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = typedarray( buf, 8, 2, 'int32' ); +* // returns [ 0, 0 ] +*/ +declare function typedarray( buffer: ArrayBuffer, byteOffset?: number, length?: number, dtype?: DType ): TypedArray; // tslint:disable-line:max-line-length + + +// EXPORTS // + +export = typedarray; diff --git a/typed/docs/types/test.ts b/typed/docs/types/test.ts new file mode 100644 index 00000000..5d019190 --- /dev/null +++ b/typed/docs/types/test.ts @@ -0,0 +1,45 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import typedarray = require( './index' ); + + +// TESTS // + +// The function returns a typed array.. +{ + typedarray(); // $ExpectType TypedArray + typedarray( 'float32' ); // $ExpectType TypedArray + typedarray( 10, 'float32' ); // $ExpectType TypedArray + typedarray( [ 1, 2, 3 ], 'int32' ); // $ExpectType TypedArray +} + +// The compiler throws an error if the function is provided a first argument which is not a data type, number, array-like object, or typed array... +{ + typedarray( true ); // $ExpectError + typedarray( false ); // $ExpectError + typedarray( {} ); // $ExpectError + typedarray( null ); // $ExpectError + typedarray( ( x: number ): number => x ); // $ExpectError +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + const buf = new ArrayBuffer( 32 ); + typedarray( buf, 8, 2, 'int32', {} ); // $ExpectError +} diff --git a/typed/examples/index.js b/typed/examples/index.js new file mode 100644 index 00000000..33b455e5 --- /dev/null +++ b/typed/examples/index.js @@ -0,0 +1,31 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var randu = require( '@stdlib/random/base/randu' ); +var typedarray = require( './../lib' ); + +var arr; +var i; + +arr = typedarray( 100, 'float64' ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = randu() * 100.0; +} +console.log( arr ); diff --git a/typed/lib/index.js b/typed/lib/index.js new file mode 100644 index 00000000..36bdbec0 --- /dev/null +++ b/typed/lib/index.js @@ -0,0 +1,126 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Create a typed array. +* +* @module @stdlib/array/typed +* +* @example +* var typedarray = require( '@stdlib/array/typed' ); +* +* var arr = typedarray(); +* // returns +* +* @example +* var typedarray = require( '@stdlib/array/typed' ); +* +* var arr = typedarray( 2 ); +* // returns [ 0.0, 0.0 ] +* +* @example +* var typedarray = require( '@stdlib/array/typed' ); +* +* var arr = typedarray( 2, 'float32' ); +* // returns [ 0.0, 0.0 ] +* +* @example +* var typedarray = require( '@stdlib/array/typed' ); +* +* var arr = typedarray( [ 0.5, 0.5 ] ); +* // returns [ 0.5, 0.5 ] +* +* @example +* var typedarray = require( '@stdlib/array/typed' ); +* +* var arr = typedarray( [ 5, -3 ], 'int32' ); +* // returns [ 5, -3 ] +* +* @example +* var typedarray = require( '@stdlib/array/typed' ); +* +* var arr1 = typedarray( [ 5, 3 ], 'int32' ); +* var arr2 = typedarray( arr1 ); +* // returns [ 5.0, 3.0 ] +* +* @example +* var typedarray = require( '@stdlib/array/typed' ); +* +* var arr1 = typedarray( [ 5, 3 ], 'int32' ); +* var arr2 = typedarray( arr1, 'uint32' ); +* // returns [ 5, 3 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* var typedarray = require( '@stdlib/array/typed' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = typedarray( buf ); +* // returns [ 0.0, 0.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* var typedarray = require( '@stdlib/array/typed' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = typedarray( buf, 'float32' ); +* // returns [ 0.0, 0.0, 0.0, 0.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* var typedarray = require( '@stdlib/array/typed' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = typedarray( buf, 8 ); +* // returns [ 0.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* var typedarray = require( '@stdlib/array/typed' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = typedarray( buf, 8, 'float32' ); +* // returns [ 0.0, 0.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* var typedarray = require( '@stdlib/array/typed' ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = typedarray( buf, 8, 2 ); +* // returns [ 0.0, 0.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* var typedarray = require( '@stdlib/array/typed' ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = typedarray( buf, 8, 2, 'int32' ); +* // returns [ 0, 0 ] +*/ + +// MODULES // + +var typedarray = require( './main.js' ); + + +// EXPORTS // + +module.exports = typedarray; diff --git a/typed/lib/main.js b/typed/lib/main.js new file mode 100644 index 00000000..8bcda31c --- /dev/null +++ b/typed/lib/main.js @@ -0,0 +1,142 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isString = require( '@stdlib/assert/is-string' ).isPrimitive; +var ctors = require( '@stdlib/array/typed-ctors' ); + + +// MAIN // + +/** +* Creates a typed array. +* +* @param {(NonNegativeInteger|TypedArray|ArrayLikeObject|ArrayBuffer)} [arg] - a length, typed array, array-like object, or buffer +* @param {NonNegativeInteger} [byteOffset=0] - byte offset +* @param {NonNegativeInteger} [length] - view length +* @param {string} [dtype="float64"] - data type +* @throws {TypeError} must provide a recognized data type +* @returns {TypedArray} typed array +* +* @example +* var arr = typedarray(); +* // returns +* +* @example +* var arr = typedarray( 2 ); +* // returns [ 0.0, 0.0 ] +* +* @example +* var arr = typedarray( 2, 'float32' ); +* // returns [ 0.0, 0.0 ] +* +* @example +* var arr = typedarray( [ 0.5, 0.5 ] ); +* // returns [ 0.5, 0.5 ] +* +* @example +* var arr = typedarray( [ 5, -3 ], 'int32' ); +* // returns [ 5, -3 ] +* +* @example +* var arr1 = typedarray( [ 5, 3 ], 'int32' ); +* var arr2 = typedarray( arr1 ); +* // returns [ 5.0, 3.0 ] +* +* @example +* var arr1 = typedarray( [ 5, 3 ], 'int32' ); +* var arr2 = typedarray( arr1, 'uint32' ); +* // returns [ 5, 3 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = typedarray( buf ); +* // returns [ 0.0, 0.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = typedarray( buf, 'float32' ); +* // returns [ 0.0, 0.0, 0.0, 0.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = typedarray( buf, 8 ); +* // returns [ 0.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* +* var buf = new ArrayBuffer( 16 ); +* var arr = typedarray( buf, 8, 'float32' ); +* // returns [ 0.0, 0.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = typedarray( buf, 8, 2 ); +* // returns [ 0.0, 0.0 ] +* +* @example +* var ArrayBuffer = require( '@stdlib/array/buffer' ); +* +* var buf = new ArrayBuffer( 32 ); +* var arr = typedarray( buf, 8, 2, 'int32' ); +* // returns [ 0, 0 ] +*/ +function typedarray() { + var nargs; + var dtype; + var ctor; + + nargs = arguments.length; + if ( nargs && isString( arguments[ nargs-1 ] ) ) { + nargs -= 1; + dtype = arguments[ nargs ]; + } else { + dtype = 'float64'; + } + ctor = ctors( dtype ); + if ( ctor === null ) { + throw new TypeError( 'invalid argument. Must provide a recognized data type. Value: `'+dtype+'`.' ); + } + if ( nargs <= 0 ) { + return new ctor( 0 ); + } + if ( nargs === 1 ) { + return new ctor( arguments[0] ); + } + if ( nargs === 2 ) { + return new ctor( arguments[0], arguments[1] ); + } + return new ctor( arguments[0], arguments[1], arguments[2] ); +} + + +// EXPORTS // + +module.exports = typedarray; diff --git a/typed/package.json b/typed/package.json new file mode 100644 index 00000000..ddb3422a --- /dev/null +++ b/typed/package.json @@ -0,0 +1,96 @@ +{ + "name": "@stdlib/array/typed", + "version": "0.0.0", + "description": "Create a typed array.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structure", + "typed", + "array", + "typed array", + "typed-array", + "vector", + "ndarray", + "matrix", + "float64array", + "float32array", + "int32array", + "uint32array", + "int16array", + "uint16array", + "int8array", + "uint8array", + "uint8clampedarray", + "float64", + "double", + "precision", + "double-precision", + "single", + "float", + "single-precision", + "float32", + "ieee754", + "integer", + "int32", + "signed", + "unsigned", + "uint32", + "int16", + "uint16", + "int8", + "uint8", + "uint8c", + "clamped", + "short", + "long" + ] +} diff --git a/typed/test/test.js b/typed/test/test.js new file mode 100644 index 00000000..9befbbf8 --- /dev/null +++ b/typed/test/test.js @@ -0,0 +1,1005 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var Float64Array = require( '@stdlib/array/float64' ); +var Float32Array = require( '@stdlib/array/float32' ); +var Int32Array = require( '@stdlib/array/int32' ); +var Uint32Array = require( '@stdlib/array/uint32' ); +var Int16Array = require( '@stdlib/array/int16' ); +var Uint16Array = require( '@stdlib/array/uint16' ); +var Int8Array = require( '@stdlib/array/int8' ); +var Uint8Array = require( '@stdlib/array/uint8' ); +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); +var ArrayBuffer = require( '@stdlib/array/buffer' ); +var instanceOf = require( '@stdlib/assert/instance-of' ); +var typedarray = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof typedarray, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error if provided an unrecognized data type (only argument)', function test( t ) { + var values; + var i; + + values = [ + '5', + 'beep', + 'typedarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarray( value ); + }; + } +}); + +tape( 'the function throws an error if provided an unrecognized data type (length)', function test( t ) { + var values; + var i; + + values = [ + '5', + 'beep', + 'typedarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarray( 10, value ); + }; + } +}); + +tape( 'the function throws an error if provided an unrecognized data type (typed array)', function test( t ) { + var values; + var i; + + values = [ + '5', + 'beep', + 'typedarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarray( new Float64Array( 10 ), value ); + }; + } +}); + +tape( 'the function throws an error if provided an unrecognized data type (array-like object)', function test( t ) { + var values; + var i; + + values = [ + '5', + 'beep', + 'typedarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarray( [ 1, 2, 3 ], value ); + }; + } +}); + +tape( 'the function throws an error if provided an unrecognized data type (ArrayBuffer)', function test( t ) { + var values; + var i; + + values = [ + '5', + 'beep', + 'typedarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarray( new ArrayBuffer( 16 ), value ); + }; + } +}); + +tape( 'the function throws an error if provided an unrecognized data type (ArrayBuffer, byteOffset)', function test( t ) { + var values; + var i; + + values = [ + '5', + 'beep', + 'typedarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarray( new ArrayBuffer( 16 ), 0, value ); + }; + } +}); + +tape( 'the function throws an error if provided an unrecognized data type (ArrayBuffer, byteOffset, length)', function test( t ) { + var values; + var i; + + values = [ + '5', + 'beep', + 'typedarray', + 'Int32', + 'Uint32', + 'Int16', + 'Uint16', + 'Int8', + 'Uint8', + 'Uint8c', + 'uint8_clamped', + 'Float64', + 'Float32', + 'FLOAT64', + 'FLOAT32' + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + typedarray( new ArrayBuffer( 16 ), 0, 1, value ); + }; + } +}); + +tape( 'the function returns a typed array (default)', function test( t ) { + var arr = typedarray(); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float64)', function test( t ) { + var arr = typedarray( 'float64' ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float32)', function test( t ) { + var arr = typedarray( 'float32' ); + t.strictEqual( instanceOf( arr, Float32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int32)', function test( t ) { + var arr = typedarray( 'int32' ); + t.strictEqual( instanceOf( arr, Int32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint32)', function test( t ) { + var arr = typedarray( 'uint32' ); + t.strictEqual( instanceOf( arr, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int16)', function test( t ) { + var arr = typedarray( 'int16' ); + t.strictEqual( instanceOf( arr, Int16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint16)', function test( t ) { + var arr = typedarray( 'uint16' ); + t.strictEqual( instanceOf( arr, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int8)', function test( t ) { + var arr = typedarray( 'int8' ); + t.strictEqual( instanceOf( arr, Int8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8)', function test( t ) { + var arr = typedarray( 'uint8' ); + t.strictEqual( instanceOf( arr, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8c)', function test( t ) { + var arr = typedarray( 'uint8c' ); + t.strictEqual( instanceOf( arr, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( arr.length, 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (default, length)', function test( t ) { + var arr = typedarray( 10 ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float64, length)', function test( t ) { + var arr = typedarray( 10, 'float64' ); + t.strictEqual( instanceOf( arr, Float64Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float32, length)', function test( t ) { + var arr = typedarray( 10, 'float32' ); + t.strictEqual( instanceOf( arr, Float32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int32, length)', function test( t ) { + var arr = typedarray( 10, 'int32' ); + t.strictEqual( instanceOf( arr, Int32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint32, length)', function test( t ) { + var arr = typedarray( 10, 'uint32' ); + t.strictEqual( instanceOf( arr, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int16, length)', function test( t ) { + var arr = typedarray( 10, 'int16' ); + t.strictEqual( instanceOf( arr, Int16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint16, length)', function test( t ) { + var arr = typedarray( 10, 'uint16' ); + t.strictEqual( instanceOf( arr, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int8, length)', function test( t ) { + var arr = typedarray( 10, 'int8' ); + t.strictEqual( instanceOf( arr, Int8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8, length)', function test( t ) { + var arr = typedarray( 10, 'uint8' ); + t.strictEqual( instanceOf( arr, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8c, length)', function test( t ) { + var arr = typedarray( 10, 'uint8c' ); + t.strictEqual( instanceOf( arr, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( arr.length, 10, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (default, array)', function test( t ) { + var arr = [ 1.0, 2.0, 3.0 ]; + var out = typedarray( arr ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float64, array)', function test( t ) { + var arr = [ 1.0, 2.0, 3.0 ]; + var out = typedarray( arr, 'float64' ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float32, array)', function test( t ) { + var arr = [ 1.0, 2.0, 3.0 ]; + var out = typedarray( arr, 'float32' ); + t.strictEqual( instanceOf( out, Float32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int32, array)', function test( t ) { + var arr = [ 1.0, 2.0, 3.0 ]; + var out = typedarray( arr, 'int32' ); + t.strictEqual( instanceOf( out, Int32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint32, array)', function test( t ) { + var arr = [ 1.0, 2.0, 3.0 ]; + var out = typedarray( arr, 'uint32' ); + t.strictEqual( instanceOf( out, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int16, array)', function test( t ) { + var arr = [ 1.0, 2.0, 3.0 ]; + var out = typedarray( arr, 'int16' ); + t.strictEqual( instanceOf( out, Int16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint16, array)', function test( t ) { + var arr = [ 1.0, 2.0, 3.0 ]; + var out = typedarray( arr, 'uint16' ); + t.strictEqual( instanceOf( out, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int8, array)', function test( t ) { + var arr = [ 1.0, 2.0, 3.0 ]; + var out = typedarray( arr, 'int8' ); + t.strictEqual( instanceOf( out, Int8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8, array)', function test( t ) { + var arr = [ 1.0, 2.0, 3.0 ]; + var out = typedarray( arr, 'uint8' ); + t.strictEqual( instanceOf( out, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8c, array)', function test( t ) { + var arr = [ 1.0, 2.0, 3.0 ]; + var out = typedarray( arr, 'uint8c' ); + t.strictEqual( instanceOf( out, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (default, typed array)', function test( t ) { + var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + var out = typedarray( arr ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float64, typed array)', function test( t ) { + var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + var out = typedarray( arr, 'float64' ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float32, typed array)', function test( t ) { + var arr = new Uint32Array( [ 1.0, 2.0, 3.0 ] ); + var out = typedarray( arr, 'float32' ); + t.strictEqual( instanceOf( out, Float32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int32, typed array)', function test( t ) { + var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + var out = typedarray( arr, 'int32' ); + t.strictEqual( instanceOf( out, Int32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint32, typed array)', function test( t ) { + var arr = new Uint8ClampedArray( [ 1.0, 2.0, 3.0 ] ); + var out = typedarray( arr, 'uint32' ); + t.strictEqual( instanceOf( out, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int16, typed array)', function test( t ) { + var arr = new Float64Array( [ 1.0, 2.0, 3.0 ] ); + var out = typedarray( arr, 'int16' ); + t.strictEqual( instanceOf( out, Int16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint16, typed array)', function test( t ) { + var arr = new Int8Array( [ 1.0, 2.0, 3.0 ] ); + var out = typedarray( arr, 'uint16' ); + t.strictEqual( instanceOf( out, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int8, typed array)', function test( t ) { + var arr = new Int16Array( [ 1.0, 2.0, 3.0 ] ); + var out = typedarray( arr, 'int8' ); + t.strictEqual( instanceOf( out, Int8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8, typed array)', function test( t ) { + var arr = new Int32Array( [ 1.0, 2.0, 3.0 ] ); + var out = typedarray( arr, 'uint8' ); + t.strictEqual( instanceOf( out, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8c, typed array)', function test( t ) { + var arr = new Float32Array( [ 1.0, 2.0, 3.0 ] ); + var out = typedarray( arr, 'uint8c' ); + t.strictEqual( instanceOf( out, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], arr[ 0 ], 'returns expected value' ); + t.strictEqual( out[ 1 ], arr[ 1 ], 'returns expected value' ); + t.strictEqual( out[ 2 ], arr[ 2 ], 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (default, arraybuffer)', function test( t ) { + var buf = new ArrayBuffer( 8 ); + var out = typedarray( buf ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 1, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0.0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float64, arraybuffer)', function test( t ) { + var buf = new ArrayBuffer( 8 ); + var out = typedarray( buf, 'float64' ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 1, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0.0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float32, arraybuffer)', function test( t ) { + var buf = new ArrayBuffer( 8 ); + var out = typedarray( buf, 'float32' ); + t.strictEqual( instanceOf( out, Float32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 2, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0.0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0.0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int32, arraybuffer)', function test( t ) { + var buf = new ArrayBuffer( 8 ); + var out = typedarray( buf, 'int32' ); + t.strictEqual( instanceOf( out, Int32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 2, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint32, arraybuffer)', function test( t ) { + var buf = new ArrayBuffer( 8 ); + var out = typedarray( buf, 'uint32' ); + t.strictEqual( instanceOf( out, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 2, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int16, arraybuffer)', function test( t ) { + var buf = new ArrayBuffer( 8 ); + var out = typedarray( buf, 'int16' ); + t.strictEqual( instanceOf( out, Int16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 4, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.strictEqual( out[ 2 ], 0, 'returns expected value' ); + t.strictEqual( out[ 3 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint16, arraybuffer)', function test( t ) { + var buf = new ArrayBuffer( 8 ); + var out = typedarray( buf, 'uint16' ); + t.strictEqual( instanceOf( out, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 4, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.strictEqual( out[ 2 ], 0, 'returns expected value' ); + t.strictEqual( out[ 3 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int8, arraybuffer)', function test( t ) { + var buf = new ArrayBuffer( 8 ); + var out = typedarray( buf, 'int8' ); + t.strictEqual( instanceOf( out, Int8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 8, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.strictEqual( out[ 2 ], 0, 'returns expected value' ); + t.strictEqual( out[ 3 ], 0, 'returns expected value' ); + t.strictEqual( out[ 4 ], 0, 'returns expected value' ); + t.strictEqual( out[ 5 ], 0, 'returns expected value' ); + t.strictEqual( out[ 6 ], 0, 'returns expected value' ); + t.strictEqual( out[ 7 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8, arraybuffer)', function test( t ) { + var buf = new ArrayBuffer( 8 ); + var out = typedarray( buf, 'uint8' ); + t.strictEqual( instanceOf( out, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 8, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.strictEqual( out[ 2 ], 0, 'returns expected value' ); + t.strictEqual( out[ 3 ], 0, 'returns expected value' ); + t.strictEqual( out[ 4 ], 0, 'returns expected value' ); + t.strictEqual( out[ 5 ], 0, 'returns expected value' ); + t.strictEqual( out[ 6 ], 0, 'returns expected value' ); + t.strictEqual( out[ 7 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8c, arraybuffer)', function test( t ) { + var buf = new ArrayBuffer( 8 ); + var out = typedarray( buf, 'uint8c' ); + t.strictEqual( instanceOf( out, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( out.length, 8, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.strictEqual( out[ 2 ], 0, 'returns expected value' ); + t.strictEqual( out[ 3 ], 0, 'returns expected value' ); + t.strictEqual( out[ 4 ], 0, 'returns expected value' ); + t.strictEqual( out[ 5 ], 0, 'returns expected value' ); + t.strictEqual( out[ 6 ], 0, 'returns expected value' ); + t.strictEqual( out[ 7 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (default, arraybuffer, byteoffset)', function test( t ) { + var buf = new ArrayBuffer( 32 ); + var out = typedarray( buf, 8 ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0.0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0.0, 'returns expected value' ); + t.strictEqual( out[ 2 ], 0.0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float64, arraybuffer, byteoffset)', function test( t ) { + var buf = new ArrayBuffer( 32 ); + var out = typedarray( buf, 8, 'float64' ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0.0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0.0, 'returns expected value' ); + t.strictEqual( out[ 2 ], 0.0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float32, arraybuffer, byteoffset)', function test( t ) { + var buf = new ArrayBuffer( 16 ); + var out = typedarray( buf, 4, 'float32' ); + t.strictEqual( instanceOf( out, Float32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0.0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0.0, 'returns expected value' ); + t.strictEqual( out[ 2 ], 0.0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int32, arraybuffer, byteoffset)', function test( t ) { + var buf = new ArrayBuffer( 16 ); + var out = typedarray( buf, 4, 'int32' ); + t.strictEqual( instanceOf( out, Int32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.strictEqual( out[ 2 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint32, arraybuffer, byteoffset)', function test( t ) { + var buf = new ArrayBuffer( 16 ); + var out = typedarray( buf, 4, 'uint32' ); + t.strictEqual( instanceOf( out, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 3, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.strictEqual( out[ 2 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int16, arraybuffer, byteoffset)', function test( t ) { + var buf = new ArrayBuffer( 16 ); + var out = typedarray( buf, 4, 'int16' ); + t.strictEqual( instanceOf( out, Int16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 6, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.strictEqual( out[ 2 ], 0, 'returns expected value' ); + t.strictEqual( out[ 3 ], 0, 'returns expected value' ); + t.strictEqual( out[ 4 ], 0, 'returns expected value' ); + t.strictEqual( out[ 5 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint16, arraybuffer, byteoffset)', function test( t ) { + var buf = new ArrayBuffer( 16 ); + var out = typedarray( buf, 4, 'uint16' ); + t.strictEqual( instanceOf( out, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 6, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.strictEqual( out[ 2 ], 0, 'returns expected value' ); + t.strictEqual( out[ 3 ], 0, 'returns expected value' ); + t.strictEqual( out[ 4 ], 0, 'returns expected value' ); + t.strictEqual( out[ 5 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int8, arraybuffer, byteoffset)', function test( t ) { + var buf = new ArrayBuffer( 16 ); + var out = typedarray( buf, 4, 'int8' ); + t.strictEqual( instanceOf( out, Int8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 12, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.strictEqual( out[ 2 ], 0, 'returns expected value' ); + t.strictEqual( out[ 3 ], 0, 'returns expected value' ); + t.strictEqual( out[ 4 ], 0, 'returns expected value' ); + t.strictEqual( out[ 5 ], 0, 'returns expected value' ); + t.strictEqual( out[ 6 ], 0, 'returns expected value' ); + t.strictEqual( out[ 7 ], 0, 'returns expected value' ); + t.strictEqual( out[ 8 ], 0, 'returns expected value' ); + t.strictEqual( out[ 9 ], 0, 'returns expected value' ); + t.strictEqual( out[ 10 ], 0, 'returns expected value' ); + t.strictEqual( out[ 11 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8, arraybuffer, byteoffset)', function test( t ) { + var buf = new ArrayBuffer( 16 ); + var out = typedarray( buf, 4, 'uint8' ); + t.strictEqual( instanceOf( out, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 12, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.strictEqual( out[ 2 ], 0, 'returns expected value' ); + t.strictEqual( out[ 3 ], 0, 'returns expected value' ); + t.strictEqual( out[ 4 ], 0, 'returns expected value' ); + t.strictEqual( out[ 5 ], 0, 'returns expected value' ); + t.strictEqual( out[ 6 ], 0, 'returns expected value' ); + t.strictEqual( out[ 7 ], 0, 'returns expected value' ); + t.strictEqual( out[ 8 ], 0, 'returns expected value' ); + t.strictEqual( out[ 9 ], 0, 'returns expected value' ); + t.strictEqual( out[ 10 ], 0, 'returns expected value' ); + t.strictEqual( out[ 11 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8c, arraybuffer, byteoffset)', function test( t ) { + var buf = new ArrayBuffer( 16 ); + var out = typedarray( buf, 4, 'uint8c' ); + t.strictEqual( instanceOf( out, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( out.length, 12, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.strictEqual( out[ 2 ], 0, 'returns expected value' ); + t.strictEqual( out[ 3 ], 0, 'returns expected value' ); + t.strictEqual( out[ 4 ], 0, 'returns expected value' ); + t.strictEqual( out[ 5 ], 0, 'returns expected value' ); + t.strictEqual( out[ 6 ], 0, 'returns expected value' ); + t.strictEqual( out[ 7 ], 0, 'returns expected value' ); + t.strictEqual( out[ 8 ], 0, 'returns expected value' ); + t.strictEqual( out[ 9 ], 0, 'returns expected value' ); + t.strictEqual( out[ 10 ], 0, 'returns expected value' ); + t.strictEqual( out[ 11 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (default, arraybuffer, byteoffset, length)', function test( t ) { + var buf = new ArrayBuffer( 32 ); + var out = typedarray( buf, 8, 2 ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 2, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0.0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0.0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float64, arraybuffer, byteoffset, length)', function test( t ) { + var buf = new ArrayBuffer( 32 ); + var out = typedarray( buf, 8, 2, 'float64' ); + t.strictEqual( instanceOf( out, Float64Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 2, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0.0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0.0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=float32, arraybuffer, byteoffset, length)', function test( t ) { + var buf = new ArrayBuffer( 16 ); + var out = typedarray( buf, 4, 2, 'float32' ); + t.strictEqual( instanceOf( out, Float32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 2, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0.0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0.0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int32, arraybuffer, byteoffset, length)', function test( t ) { + var buf = new ArrayBuffer( 16 ); + var out = typedarray( buf, 4, 2, 'int32' ); + t.strictEqual( instanceOf( out, Int32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 2, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint32, arraybuffer, byteoffset, length)', function test( t ) { + var buf = new ArrayBuffer( 16 ); + var out = typedarray( buf, 4, 2, 'uint32' ); + t.strictEqual( instanceOf( out, Uint32Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 2, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int16, arraybuffer, byteoffset, length)', function test( t ) { + var buf = new ArrayBuffer( 16 ); + var out = typedarray( buf, 4, 2, 'int16' ); + t.strictEqual( instanceOf( out, Int16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 2, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint16, arraybuffer, byteoffset, length)', function test( t ) { + var buf = new ArrayBuffer( 16 ); + var out = typedarray( buf, 4, 2, 'uint16' ); + t.strictEqual( instanceOf( out, Uint16Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 2, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=int8, arraybuffer, byteoffset, length)', function test( t ) { + var buf = new ArrayBuffer( 16 ); + var out = typedarray( buf, 4, 2, 'int8' ); + t.strictEqual( instanceOf( out, Int8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 2, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8, arraybuffer, byteoffset, length)', function test( t ) { + var buf = new ArrayBuffer( 16 ); + var out = typedarray( buf, 4, 2, 'uint8' ); + t.strictEqual( instanceOf( out, Uint8Array ), true, 'returns expected value' ); + t.strictEqual( out.length, 2, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.end(); +}); + +tape( 'the function returns a typed array (dtype=uint8c, arraybuffer, byteoffset, length)', function test( t ) { + var buf = new ArrayBuffer( 16 ); + var out = typedarray( buf, 4, 2, 'uint8c' ); + t.strictEqual( instanceOf( out, Uint8ClampedArray ), true, 'returns expected value' ); + t.strictEqual( out.length, 2, 'returns expected value' ); + t.strictEqual( out[ 0 ], 0, 'returns expected value' ); + t.strictEqual( out[ 1 ], 0, 'returns expected value' ); + t.end(); +}); diff --git a/uint16/README.md b/uint16/README.md new file mode 100644 index 00000000..27ae4f2c --- /dev/null +++ b/uint16/README.md @@ -0,0 +1,1431 @@ + + +# Uint16Array + +> [Typed array][mdn-typed-array] constructor which returns a [typed array][mdn-typed-array] representing an array of 16-bit unsigned integers in the platform byte order. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var Uint16Array = require( '@stdlib/array/uint16' ); +``` + +#### Uint16Array() + +A [typed array][mdn-typed-array] constructor which returns a [typed array][mdn-typed-array] representing an array of 16-bit unsigned integers in the platform byte order. + + + +```javascript +var arr = new Uint16Array(); +// returns +``` + +#### Uint16Array( length ) + +Returns a [typed array][mdn-typed-array] having a specified length. + + + +```javascript +var arr = new Uint16Array( 5 ); +// returns [ 0, 0, 0, 0, 0 ] +``` + +#### Uint16Array( typedarray ) + +Creates a [typed array][mdn-typed-array] from another [typed array][mdn-typed-array]. + + + +```javascript +var Float32Array = require( '@stdlib/array/float32' ); + +var arr1 = new Float32Array( [ 5.0, 5.0, 5.0 ] ); +var arr2 = new Uint16Array( arr1 ); +// returns [ 5, 5, 5 ] +``` + +#### Uint16Array( obj ) + +Creates a [typed array][mdn-typed-array] from an array-like `object` or iterable. + + + +```javascript +var arr = new Uint16Array( [ 5.0, 5.0, 5.0 ] ); +// returns [ 5, 5, 5 ] +``` + +#### Uint16Array( buffer\[, byteOffset\[, length]] ) + +Returns a [typed array][mdn-typed-array] view of an [`ArrayBuffer`][@stdlib/array/buffer]. + + + +```javascript +var ArrayBuffer = require( '@stdlib/array/buffer' ); + +var buf = new ArrayBuffer( 8 ); +var arr = new Uint16Array( buf, 0, 4 ); +// returns [ 0, 0, 0, 0 ] +``` + +* * * + +### Properties + + + +#### Uint16Array.BYTES_PER_ELEMENT + +Number of bytes per view element. + + + +```javascript +var nbytes = Uint16Array.BYTES_PER_ELEMENT; +// returns 2 +``` + + + +#### Uint16Array.name + +[Typed array][mdn-typed-array] constructor name. + + + +```javascript +var str = Uint16Array.name; +// returns 'Uint16Array' +``` + + + +#### Uint16Array.prototype.buffer + +**Read-only** property which returns the [`ArrayBuffer`][@stdlib/array/buffer] referenced by the [typed array][mdn-typed-array]. + + + +```javascript +var arr = new Uint16Array( 5 ); +var buf = arr.buffer; +// returns +``` + + + +#### Uint16Array.prototype.byteLength + +**Read-only** property which returns the length (in bytes) of the [typed array][mdn-typed-array]. + + + +```javascript +var arr = new Uint16Array( 5 ); +var byteLength = arr.byteLength; +// returns 10 +``` + + + +#### Uint16Array.prototype.byteOffset + +**Read-only** property which returns the offset (in bytes) of the [typed array][mdn-typed-array] from the start of its [`ArrayBuffer`][@stdlib/array/buffer]. + + + +```javascript +var arr = new Uint16Array( 5 ); +var byteOffset = arr.byteOffset; +// returns 0 +``` + + + +#### Uint16Array.prototype.BYTES_PER_ELEMENT + +Number of bytes per view element. + + + +```javascript +var arr = new Uint16Array( 5 ); +var nbytes = arr.BYTES_PER_ELEMENT; +// returns 2 +``` + + + +#### Uint16Array.prototype.length + +**Read-only** property which returns the number of view elements. + + + +```javascript +var arr = new Uint16Array( 5 ); +var len = arr.length; +// returns 5 +``` + +* * * + +### Methods + + + +#### Uint16Array.from( src\[, map\[, thisArg]] ) + +Creates a new typed array from an array-like `object` or an iterable. + +```javascript +var arr = Uint16Array.from( [ 1, 2 ] ); +// returns [ 1, 2 ] +``` + +To invoke a function for each `src` value, provide a callback function. + +```javascript +function mapFcn( v ) { + return v * 2; +} + +var arr = Uint16Array.from( [ 1, 2 ], mapFcn ); +// returns [ 2, 4 ] +``` + +A callback function is provided two arguments: + +- `value`: source value +- `index`: source index + +To set the callback execution context, provide a `thisArg`. + +```javascript +function mapFcn( v ) { + this.count += 1; + return v * 2; +} + +var ctx = { + 'count': 0 +}; + +var arr = Uint16Array.from( [ 1, 2 ], mapFcn, ctx ); +// returns [ 2, 4 ] + +var n = ctx.count; +// returns 2 +``` + + + +#### Uint16Array.of( element0\[, element1\[, ...elementN]] ) + +Creates a new typed array from a variable number of arguments. + +```javascript +var arr = Uint16Array.of( 1, 2 ); +// returns [ 1, 2 ] +``` + + + +#### Uint16Array.prototype.copyWithin( target, start\[, end] ) + +Copies a sequence of elements within an array starting at `start` and ending at `end` (non-inclusive) to the position starting at `target`. + + + +```javascript +var arr = new Uint16Array( [ 1, 2, 3, 4, 5 ] ); + +// Copy the last two elements to the first two elements: +arr.copyWithin( 0, 3 ); + +var v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 5 +``` + +By default, `end` equals the number of array elements (i.e., one more than the last array index). To limit the sequence length, provide an `end` argument. + + + +```javascript +var arr = new Uint16Array( [ 1, 2, 3, 4, 5 ] ); + +// Copy the first two elements to the last two elements: +arr.copyWithin( 3, 0, 2 ); + +var v = arr[ 3 ]; +// returns 1 + +v = arr[ 4 ]; +// returns 2 +``` + +When a `target`, `start`, and/or `end` index is negative, the respective index is determined relative to the last array element. The following example achieves the same behavior as the previous example: + + + +```javascript +var arr = new Uint16Array( [ 1, 2, 3, 4, 5 ] ); + +// Copy the first two elements to the last two elements: +arr.copyWithin( -2, -5, -3 ); + +var v = arr[ 3 ]; +// returns 1 + +v = arr[ 4 ]; +// returns 2 +``` + + + +#### Uint16Array.prototype.entries() + +Returns an iterator for iterating over array key-value pairs. + + + +```javascript +var arr = new Uint16Array( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.entries(); + +// Iterate over key-value pairs... +var v = it.next().value; +// returns [ 0, 1 ] + +v = it.next().value; +// returns [ 1, 2 ] + +var bool = it.next().done; +// returns true +``` + + + +#### Uint16Array.prototype.every( predicate\[, thisArg] ) + +Tests whether all array elements pass a test implemented by a `predicate` function. + + + +```javascript +function predicate( v ) { + return ( v <= 1 ); +} + +var arr = new Uint16Array( [ 1, 2 ] ); + +var bool = arr.every( predicate ); +// returns false +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 1 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint16Array( [ 1, 2 ] ); + +var bool = arr.every( predicate, ctx ); +// returns true + +var n = ctx.count; +// returns 2 +``` + + + +#### Uint16Array.prototype.fill( value\[, start\[, end]] ) + +Fills an array from a `start` index to an `end` index (non-inclusive) with a provided `value`. + + + +```javascript +var arr = new Uint16Array( 2 ); + +// Set all array elements to the same value: +arr.fill( 2 ); + +var v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 2 + +// Set all array elements starting from the first index to the same value: +arr.fill( 3, 1 ); + +v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 3 + +// Set all array elements, except the last element, to the same value: +arr.fill( 4, 0, arr.length-1 ); + +v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 3 +``` + +When a `start` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr = new Uint16Array( 2 ); + +// Set all array elements, except the last element, to the same value: +arr.fill( 2, -arr.length, -1 ); + +var v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 0 +``` + + + +#### Uint16Array.prototype.filter( predicate\[, thisArg] ) + +Creates a new array (of the same data type as the host array) which includes those elements for which a `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v >= 2 ); +} + +var arr1 = new Uint16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate ); +// returns [ 2, 3 ] +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns an empty array. + + + +```javascript +function predicate( v ) { + return ( v >= 10 ); +} + +var arr1 = new Uint16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate ); +// returns [] +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr1 = new Uint16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint16Array.prototype.find( predicate\[, thisArg] ) + +Returns the first array element for which a provided `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v > 2 ); +} + +var arr = new Uint16Array( [ 1, 2, 3 ] ); + +var v = arr.find( predicate ); +// returns 3 +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns `undefined`. + + + +```javascript +function predicate( v ) { + return ( v < 1 ); +} + +var arr = new Uint16Array( [ 1, 2, 3 ] ); + +var v = arr.find( predicate ); +// returns undefined +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v > 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint16Array( [ 1, 2, 3 ] ); + +var v = arr.find( predicate, ctx ); +// returns 3 + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint16Array.prototype.findIndex( predicate\[, thisArg] ) + +Returns the index of the first array element for which a provided `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v >= 3 ); +} + +var arr = new Uint16Array( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate ); +// returns 2 +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns `-1`. + + + +```javascript +function predicate( v ) { + return ( v < 1 ); +} + +var arr = new Uint16Array( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate ); +// returns -1 +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 3 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint16Array( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate, ctx ); +// returns 2 + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint16Array.prototype.forEach( fcn\[, thisArg] ) + +Invokes a callback for each array element. + + + +```javascript +var arr = new Uint16Array( [ 1, 2, 3 ] ); + +var str = ''; + +function fcn( v, i ) { + str += i + ':' + v; + if ( i < arr.length-1 ) { + str += ' '; + } +} + +arr.forEach( fcn ); + +console.log( str ); +// => '0:1 1:2 2:3' +``` + +The callback is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function fcn() { + this.count += 1; +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint16Array( [ 1, 2, 3 ] ); + +arr.forEach( fcn, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint16Array.prototype.includes( searchElement\[, fromIndex] ) + +Returns a `boolean` indicating whether an array includes a search element. + + + +```javascript +var arr = new Uint16Array( [ 1, 2, 3 ] ); + +var bool = arr.includes( 3 ); +// returns true + +bool = arr.includes( 0 ); +// returns false +``` + +By default, the method searches the entire array (`fromIndex = 0`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Uint16Array( [ 1, 2, 3 ] ); + +var bool = arr.includes( 1, 1 ); +// returns false +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Uint16Array( [ 1, 2, 3 ] ); + +bool = arr.includes( 1, -2 ); +// returns false +``` + + + +#### Uint16Array.prototype.indexOf( searchElement\[, fromIndex] ) + +Returns the index of the first array element strictly equal to a search element. + + + +```javascript +var arr = new Uint16Array( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 3 ); +// returns 2 + +idx = arr.indexOf( 0 ); +// returns -1 +``` + +By default, the method searches the entire array (`fromIndex = 0`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Uint16Array( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 1, 1 ); +// returns -1 +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Uint16Array( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 1, -2 ); +// returns -1 +``` + + + +#### Uint16Array.prototype.join( \[separator] ) + +Serializes an array by joining all array elements as a string. + + + +```javascript +var arr = new Uint16Array( [ 1, 2, 3 ] ); + +var str = arr.join(); +// returns '1,2,3' +``` + +By default, the method delineates array elements using a comma `,`. To specify a custom separator, provide a `separator` string. + + + +```javascript +var arr = new Uint16Array( [ 1, 2, 3 ] ); + +var str = arr.join( '|' ); +// returns '1|2|3' +``` + + + +#### Uint16Array.prototype.keys() + +Returns an iterator for iterating over array keys. + + + +```javascript +var arr = new Uint16Array( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.keys(); + +// Iterate over keys... +var v = it.next().value; +// returns 0 + +v = it.next().value; +// returns 1 + +var bool = it.next().done; +// returns true +``` + + + +#### Uint16Array.prototype.lastIndexOf( searchElement\[, fromIndex] ) + +Returns the index of the last array element strictly equal to a search element, iterating from right to left. + + + +```javascript +var arr = new Uint16Array( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0 ); +// returns 3 + +idx = arr.lastIndexOf( 3 ); +// returns -1 +``` + +By default, the method searches the entire array (`fromIndex = -1`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Uint16Array( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0, 2 ); +// returns 1 +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Uint16Array( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0, -3 ); +// returns 1 +``` + + + +#### Uint16Array.prototype.map( fcn\[, thisArg] ) + +Maps each array element to an element in a new array having the same data type as the host array. + + + +```javascript +function fcn( v ) { + return v * 2; +} + +var arr1 = new Uint16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.map( fcn ); +// returns [ 2, 4, 6 ] +``` + +A callback is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function fcn( v ) { + this.count += 1; + return v * 2; +} + +var ctx = { + 'count': 0 +}; + +var arr1 = new Uint16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.map( fcn, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint16Array.prototype.reduce( fcn\[, initialValue] ) + +Applies a function against an accumulator and each element in an array and returns the accumulated result. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Uint16Array( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn ); +// returns 12 +``` + +If not provided an initial value, the method invokes a provided function with the first array element as the first argument and the second array element as the second argument. + +If provided an initial value, the method invokes a provided function with the initial value as the first argument and the first array element as the second argument. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Uint16Array( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn, 0 ); +// returns 14 +``` + +A callback is provided four arguments: + +- `acc`: accumulated result +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + + + +#### Uint16Array.prototype.reduceRight( fcn\[, initialValue] ) + +Applies a function against an accumulator and each element in an array and returns the accumulated result, iterating from right to left. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Uint16Array( [ 2, 1, 3 ] ); + +var v = arr.reduceRight( fcn ); +// returns 8 +``` + +If not provided an initial value, the method invokes a provided function with the last array element as the first argument and the second-to-last array element as the second argument. + +If provided an initial value, the method invokes a provided function with the initial value as the first argument and the last array element as the second argument. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Uint16Array( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn, 0 ); +// returns 14 +``` + +A callback is provided four arguments: + +- `acc`: accumulated result +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + + + +#### Uint16Array.prototype.reverse() + +Reverses an array **in-place** (thus mutating the array on which the method is invoked). + + + +```javascript +var arr = new Uint16Array( [ 2, 0, 3 ] ); + +// Reverse the array: +arr.reverse(); + +var v = arr[ 0 ]; +// returns 3 + +v = arr[ 1 ]; +// returns 0 + +v = arr[ 2 ]; +// returns 2 +``` + + + +#### Uint16Array.prototype.set( arr\[, offset] ) + +Sets array elements. + + + +```javascript +var arr = new Uint16Array( [ 1, 2, 3 ] ); +// returns [ 1, 2, 3 ] + +// Set the first two array elements: +arr.set( [ 4, 5 ] ); + +var v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 5 +``` + +By default, the method starts writing values at the first array index. To specify an alternative index, provide an index `offset`. + + + +```javascript +var arr = new Uint16Array( [ 1, 2, 3 ] ); +// returns [ 1, 2, 3 ] + +// Set the last two array elements: +arr.set( [ 4, 5 ], 1 ); + +var v = arr[ 1 ]; +// returns 4 + +v = arr[ 2 ]; +// returns 5 +``` + + + +#### Uint16Array.prototype.slice( \[begin\[, end]] ) + +Copies array elements to a new array with the same underlying data type as the host array. + + + +```javascript +var arr1 = new Uint16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice(); + +var bool = ( arr1 === arr2 ); +// returns false + +bool = ( arr1.buffer === arr2.buffer ); +// returns false + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 + +v = arr2[ 2 ]; +// returns 3 +``` + +By default, the method copies elements beginning with the first array element. To specify an alternative array index at which to begin copying, provide a `begin` index (inclusive). + + + +```javascript +var arr1 = new Uint16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( 1 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 2 + +v = arr2[ 1 ]; +// returns 3 +``` + +By default, the method copies all array elements after `begin`. To specify an alternative array index at which to end copying, provide an `end` index (exclusive). + + + +```javascript +var arr1 = new Uint16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( 0, 2 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 +``` + +When a `begin` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr1 = new Uint16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( -arr1.length, -1 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 +``` + + + +#### Uint16Array.prototype.some( predicate\[, thisArg] ) + +Tests whether at least one array element passes a test implemented by a `predicate` function. + + + +```javascript +function predicate( v ) { + return ( v >= 2 ); +} + +var arr = new Uint16Array( [ 1, 2 ] ); + +var bool = arr.some( predicate ); +// returns true +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint16Array( [ 1, 1 ] ); + +var bool = arr.some( predicate, ctx ); +// returns false + +var n = ctx.count; +// returns 2 +``` + + + +#### Uint16Array.prototype.sort( \[compareFunction] ) + +Sorts an array **in-place** (thus mutating the array on which the method is invoked). + + + +```javascript +var arr = new Uint16Array( [ 2, 3, 0 ] ); + +// Sort the array (in ascending order): +arr.sort(); + +var v = arr[ 0 ]; +// returns 0 + +v = arr[ 1 ]; +// returns 2 + +v = arr[ 2 ]; +// returns 3 +``` + +By default, the method sorts array elements in ascending order. To impose a custom order, provide a `compareFunction`. + + + +```javascript +function descending( a, b ) { + return b - a; +} + +var arr = new Uint16Array( [ 2, 3, 0 ] ); + +// Sort the array (in descending order): +arr.sort( descending ); + +var v = arr[ 0 ]; +// returns 3 + +v = arr[ 1 ]; +// returns 2 + +v = arr[ 2 ]; +// returns 0 +``` + +The comparison function is provided two array elements, `a` and `b`, per invocation, and its return value determines the sort order as follows: + +- If the comparison function returns a value **less** than zero, then the method sorts `a` to an index lower than `b` (i.e., `a` should come **before** `b`). +- If the comparison function returns a value **greater** than zero, then the method sorts `a` to an index higher than `b` (i.e., `b` should come **before** `a`). +- If the comparison function returns **zero**, then the relative order of `a` and `b` _should_ remain unchanged. + + + +#### Uint16Array.prototype.subarray( \[begin\[, end]] ) + +Creates a new typed array view over the same underlying [`ArrayBuffer`][@stdlib/array/buffer] and with the same underlying data type as the host array. + + + +```javascript +var arr1 = new Uint16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray(); +// returns [ 1, 2, 3 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +By default, the method creates a typed array view beginning with the first array element. To specify an alternative array index at which to begin, provide a `begin` index (inclusive). + + + +```javascript +var arr1 = new Uint16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 1 ); +// returns [ 2, 3 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +By default, the method creates a typed array view which includes all array elements after `begin`. To limit the number of array elements after `begin`, provide an `end` index (exclusive). + + + +```javascript +var arr1 = new Uint16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 0, 2 ); +// returns [ 1, 2 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +When a `begin` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr1 = new Uint16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( -arr1.length, -1 ); +// returns [ 1, 2 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +If the method is unable to resolve indices to a non-empty array subsequence, the method returns an empty typed array. + + + +```javascript +var arr1 = new Uint16Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 10, -1 ); +// returns [] +``` + + + +#### Uint16Array.prototype.toLocaleString( \[locales\[, options]] ) + +Serializes an array as a locale-specific `string`. + + + +```javascript +var arr = new Uint16Array( [ 1, 2, 3 ] ); + +var str = arr.toLocaleString(); +// returns '1,2,3' +``` + + + +#### Uint16Array.prototype.toString() + +Serializes an array as a `string`. + + + +```javascript +var arr = new Uint16Array( [ 1, 2, 3 ] ); + +var str = arr.toString(); +// returns '1,2,3' +``` + + + +#### Uint16Array.prototype.values() + +Returns an iterator for iterating over array elements. + + + +```javascript +var arr = new Uint16Array( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.values(); + +// Iterate over array elements... +var v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 2 + +var bool = it.next().done; +// returns true +``` + +
+ + + +* * * + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var randu = require( '@stdlib/random/base/randu' ); +var round = require( '@stdlib/math/base/special/round' ); +var ctor = require( '@stdlib/array/uint16' ); + +var arr; +var i; + +arr = new ctor( 10 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = round( randu()*100.0 ); +} +console.log( arr ); +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/uint16/benchmark/benchmark.copy_within.js b/uint16/benchmark/benchmark.copy_within.js new file mode 100644 index 00000000..7c903c34 --- /dev/null +++ b/uint16/benchmark/benchmark.copy_within.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':copyWithin', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr[ 0 ] = v; + arr = arr.copyWithin( 1, 0 ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/benchmark/benchmark.copy_within.length.js b/uint16/benchmark/benchmark.copy_within.length.js new file mode 100644 index 00000000..84e9cd61 --- /dev/null +++ b/uint16/benchmark/benchmark.copy_within.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr[ 0 ] = v; + arr = arr.copyWithin( 1, 0 ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':copyWithin:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.data.js b/uint16/benchmark/benchmark.data.js new file mode 100644 index 00000000..fb912ea2 --- /dev/null +++ b/uint16/benchmark/benchmark.data.js @@ -0,0 +1,75 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::get,index', function benchmark( b ) { + var arr; + var N; + var v; + var i; + + arr = new Uint16Array( 2 ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr[ i%N ]; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::set,index', function benchmark( b ) { + var arr; + var N; + var i; + + arr = new Uint16Array( 2 ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ i%N ] = i; + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] || arr[ 1 ] !== arr[ 1 ] ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/benchmark/benchmark.entries.js b/uint16/benchmark/benchmark.entries.js new file mode 100644 index 00000000..072c7c53 --- /dev/null +++ b/uint16/benchmark/benchmark.entries.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':entries', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Uint16Array( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.entries(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/benchmark/benchmark.every.js b/uint16/benchmark/benchmark.every.js new file mode 100644 index 00000000..93a5d357 --- /dev/null +++ b/uint16/benchmark/benchmark.every.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':every', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); + +bench( pkg+'::this_context:every', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate, {} ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); diff --git a/uint16/benchmark/benchmark.every.length.js b/uint16/benchmark/benchmark.every.length.js new file mode 100644 index 00000000..3340d983 --- /dev/null +++ b/uint16/benchmark/benchmark.every.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value >= 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':every:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.fill.js b/uint16/benchmark/benchmark.fill.js new file mode 100644 index 00000000..f0983e0d --- /dev/null +++ b/uint16/benchmark/benchmark.fill.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':fill', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr = arr.fill( v ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/benchmark/benchmark.fill.length.js b/uint16/benchmark/benchmark.fill.length.js new file mode 100644 index 00000000..33877794 --- /dev/null +++ b/uint16/benchmark/benchmark.fill.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr = arr.fill( v ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':fill:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.filter.js b/uint16/benchmark/benchmark.filter.js new file mode 100644 index 00000000..e9d36969 --- /dev/null +++ b/uint16/benchmark/benchmark.filter.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint16Array = require( '@stdlib/assert/is-uint16array' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':filter', function benchmark( b ) { + var arr; + var out; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint16Array( out ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); + +bench( pkg+'::this_context:filter', function benchmark( b ) { + var arr; + var out; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate, {} ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint16Array( out ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); diff --git a/uint16/benchmark/benchmark.filter.length.js b/uint16/benchmark/benchmark.filter.length.js new file mode 100644 index 00000000..6941c0a6 --- /dev/null +++ b/uint16/benchmark/benchmark.filter.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint16Array = require( '@stdlib/assert/is-uint16array' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value >= 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint16Array( out ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':filter:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.find.js b/uint16/benchmark/benchmark.find.js new file mode 100644 index 00000000..1d347e49 --- /dev/null +++ b/uint16/benchmark/benchmark.find.js @@ -0,0 +1,82 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':find', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:find', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate, {} ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/uint16/benchmark/benchmark.find.length.js b/uint16/benchmark/benchmark.find.length.js new file mode 100644 index 00000000..b1cfa5ec --- /dev/null +++ b/uint16/benchmark/benchmark.find.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - tuple length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint16Array( len ); + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':find:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.find_index.js b/uint16/benchmark/benchmark.find_index.js new file mode 100644 index 00000000..c1e86611 --- /dev/null +++ b/uint16/benchmark/benchmark.find_index.js @@ -0,0 +1,82 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':findIndex', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:findIndex', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate, {} ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/uint16/benchmark/benchmark.find_index.length.js b/uint16/benchmark/benchmark.find_index.length.js new file mode 100644 index 00000000..83fd164a --- /dev/null +++ b/uint16/benchmark/benchmark.find_index.length.js @@ -0,0 +1,104 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':findIndex:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.for_each.js b/uint16/benchmark/benchmark.for_each.js new file mode 100644 index 00000000..67594f8d --- /dev/null +++ b/uint16/benchmark/benchmark.for_each.js @@ -0,0 +1,88 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':forEach', function benchmark( b ) { + var count; + var arr; + var N; + var i; + + arr = new Uint16Array( 2 ); + N = arr.length; + + count = 0; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn ); + if ( count !== N*(i+1) ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( count !== N*i ) { + b.fail( 'unexpected result' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn() { + count += 1; + } +}); + +bench( pkg+'::this_context:forEach', function benchmark( b ) { + var count; + var arr; + var N; + var i; + + arr = new Uint16Array( 2 ); + N = arr.length; + + count = 0; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn, {} ); + if ( count !== N*(i+1) ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( count !== N*i ) { + b.fail( 'unexpected result' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn() { + count += 1; + } +}); diff --git a/uint16/benchmark/benchmark.for_each.length.js b/uint16/benchmark/benchmark.for_each.length.js new file mode 100644 index 00000000..ed6ad3f5 --- /dev/null +++ b/uint16/benchmark/benchmark.for_each.length.js @@ -0,0 +1,106 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var count; + var arr; + + arr = new Uint16Array( len ); + count = 0; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn ); + if ( count !== count ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( count !== count ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } + + /** + * Callback invoked for each tuple element. + * + * @private + */ + function fcn() { + count += 1; + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':forEach:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.from.js b/uint16/benchmark/benchmark.from.js new file mode 100644 index 00000000..44de0b6f --- /dev/null +++ b/uint16/benchmark/benchmark.from.js @@ -0,0 +1,237 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var ITERATOR_SYMBOL = require( '@stdlib/symbol/iterator' ); +var isUint16Array = require( '@stdlib/assert/is-uint16array' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// VARIABLES // + +var opts = { + 'skip': ( ITERATOR_SYMBOL === null ) +}; + + +// MAIN // + +bench( pkg+'::typed_array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Uint16Array( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint16Array.from( buf ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint16Array( arr ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array,clbk:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Uint16Array( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint16Array.from( buf, clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint16Array( arr ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1; + } +}); + +bench( pkg+'::array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1, 2 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint16Array.from( buf ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint16Array( arr ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::array,clbk:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1, 2 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint16Array.from( buf, clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint16Array( arr ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1; + } +}); + +bench( pkg+'::iterable:from', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint16Array.from( createIterable() ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint16Array( arr ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out; + var i; + + out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + + i = 0; + + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + i += 1; + if ( i <= 2 ) { + return { + 'value': 0, + 'done': false + }; + } + return { + 'done': true + }; + } + } +}); + +bench( pkg+'::iterable,clbk:from:', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint16Array.from( createIterable(), clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint16Array( arr ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out; + var i; + + out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + + i = 0; + + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + i += 1; + if ( i <= 2 ) { + return { + 'value': 1, + 'done': false + }; + } + return { + 'done': true + }; + } + } + + function clbk( v ) { + return v + 1; + } +}); diff --git a/uint16/benchmark/benchmark.includes.js b/uint16/benchmark/benchmark.includes.js new file mode 100644 index 00000000..45b77212 --- /dev/null +++ b/uint16/benchmark/benchmark.includes.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':includes', function benchmark( b ) { + var bool; + var arr; + var v; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + bool = arr.includes( v ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/benchmark/benchmark.includes.length.js b/uint16/benchmark/benchmark.includes.length.js new file mode 100644 index 00000000..6bc43f18 --- /dev/null +++ b/uint16/benchmark/benchmark.includes.length.js @@ -0,0 +1,96 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + bool = arr.includes( v ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':includes:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.index_of.js b/uint16/benchmark/benchmark.index_of.js new file mode 100644 index 00000000..c3f4e865 --- /dev/null +++ b/uint16/benchmark/benchmark.index_of.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':indexOf', function benchmark( b ) { + var out; + var arr; + var v; + var i; + + arr = new Uint16Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.indexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/benchmark/benchmark.index_of.length.js b/uint16/benchmark/benchmark.index_of.length.js new file mode 100644 index 00000000..70ae6f9c --- /dev/null +++ b/uint16/benchmark/benchmark.index_of.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.indexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':indexOf:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.join.js b/uint16/benchmark/benchmark.join.js new file mode 100644 index 00000000..bc8234cf --- /dev/null +++ b/uint16/benchmark/benchmark.join.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':join', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i % 127; + out = arr.join(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/benchmark/benchmark.join.length.js b/uint16/benchmark/benchmark.join.length.js new file mode 100644 index 00000000..94f15eab --- /dev/null +++ b/uint16/benchmark/benchmark.join.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i % 127; + out = arr.join(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':join:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.js b/uint16/benchmark/benchmark.js new file mode 100644 index 00000000..85f605e3 --- /dev/null +++ b/uint16/benchmark/benchmark.js @@ -0,0 +1,47 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint16Array = require( '@stdlib/assert/is-uint16array' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new ctor( 0 ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isUint16Array( arr ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/benchmark/benchmark.keys.js b/uint16/benchmark/benchmark.keys.js new file mode 100644 index 00000000..d65e8f0f --- /dev/null +++ b/uint16/benchmark/benchmark.keys.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':keys', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.keys(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/benchmark/benchmark.last_index_of.js b/uint16/benchmark/benchmark.last_index_of.js new file mode 100644 index 00000000..318584ae --- /dev/null +++ b/uint16/benchmark/benchmark.last_index_of.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':lastIndexOf', function benchmark( b ) { + var out; + var arr; + var v; + var i; + + arr = new Uint16Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.lastIndexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/benchmark/benchmark.last_index_of.length.js b/uint16/benchmark/benchmark.last_index_of.length.js new file mode 100644 index 00000000..2f711a73 --- /dev/null +++ b/uint16/benchmark/benchmark.last_index_of.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.lastIndexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':lastIndexOf:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.length.js b/uint16/benchmark/benchmark.length.js new file mode 100644 index 00000000..a91be015 --- /dev/null +++ b/uint16/benchmark/benchmark.length.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint16Array = require( '@stdlib/assert/is-uint16array' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new ctor( len ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isUint16Array( arr ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.map.js b/uint16/benchmark/benchmark.map.js new file mode 100644 index 00000000..a6389e1d --- /dev/null +++ b/uint16/benchmark/benchmark.map.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint16Array = require( '@stdlib/assert/is-uint16array' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':map', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint16Array( out ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); + +bench( pkg+'::this_context:map', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn, {} ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint16Array( out ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/uint16/benchmark/benchmark.map.length.js b/uint16/benchmark/benchmark.map.length.js new file mode 100644 index 00000000..460ac068 --- /dev/null +++ b/uint16/benchmark/benchmark.map.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint16Array = require( '@stdlib/assert/is-uint16array' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Maps an array element to a new value. +* +* @private +* @param {*} value - array element +* @returns {*} new value +*/ +function fcn( value ) { + return value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint16Array( out ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':map:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.of.js b/uint16/benchmark/benchmark.of.js new file mode 100644 index 00000000..a82d4ffe --- /dev/null +++ b/uint16/benchmark/benchmark.of.js @@ -0,0 +1,48 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint16Array = require( '@stdlib/assert/is-uint16array' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':of', function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint16Array.of( i, 2 ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint16Array( arr ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/benchmark/benchmark.properties.js b/uint16/benchmark/benchmark.properties.js new file mode 100644 index 00000000..7805cb96 --- /dev/null +++ b/uint16/benchmark/benchmark.properties.js @@ -0,0 +1,145 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isArrayBuffer = require( '@stdlib/assert/is-arraybuffer' ); +var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::get:buffer', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.buffer; + if ( typeof v !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isArrayBuffer( v ) ) { + b.fail( 'should return an ArrayBuffer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteLength', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteLength; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteOffset', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteOffset; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:BYTES_PER_ELEMENT', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.BYTES_PER_ELEMENT; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:length', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.length; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/benchmark/benchmark.reduce.js b/uint16/benchmark/benchmark.reduce.js new file mode 100644 index 00000000..dd3dfdd1 --- /dev/null +++ b/uint16/benchmark/benchmark.reduce.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reduce', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( acc, v ) { + return acc + v + 1; + } +}); + +bench( pkg+'::initial_value:reduce', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn, 3 ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/uint16/benchmark/benchmark.reduce.length.js b/uint16/benchmark/benchmark.reduce.length.js new file mode 100644 index 00000000..1023c907 --- /dev/null +++ b/uint16/benchmark/benchmark.reduce.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Updates an accumulated value. +* +* @private +* @param {*} acc - accumulated value +* @param {*} value - array element +* @returns {*} accumulated value +*/ +function fcn( acc, value ) { + return acc + value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reduce:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.reduce_right.js b/uint16/benchmark/benchmark.reduce_right.js new file mode 100644 index 00000000..ec3f69b9 --- /dev/null +++ b/uint16/benchmark/benchmark.reduce_right.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reduceRight', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( acc, v ) { + return acc + v + 1; + } +}); + +bench( pkg+'::initial_value:reduceRight', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn, 3 ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/uint16/benchmark/benchmark.reduce_right.length.js b/uint16/benchmark/benchmark.reduce_right.length.js new file mode 100644 index 00000000..f2e544b7 --- /dev/null +++ b/uint16/benchmark/benchmark.reduce_right.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Updates an accumulated value. +* +* @private +* @param {*} acc - accumulated value +* @param {*} value - array element +* @returns {*} accumulated value +*/ +function fcn( acc, value ) { + return acc + value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reduceRight:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.reverse.js b/uint16/benchmark/benchmark.reverse.js new file mode 100644 index 00000000..4ead6ff8 --- /dev/null +++ b/uint16/benchmark/benchmark.reverse.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint16Array = require( '@stdlib/assert/is-uint16array' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reverse', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.reverse(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint16Array( out ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/benchmark/benchmark.reverse.length.js b/uint16/benchmark/benchmark.reverse.length.js new file mode 100644 index 00000000..653f41a3 --- /dev/null +++ b/uint16/benchmark/benchmark.reverse.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint16Array = require( '@stdlib/assert/is-uint16array' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.reverse(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint16Array( out ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reverse:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.set.js b/uint16/benchmark/benchmark.set.js new file mode 100644 index 00000000..1598ea32 --- /dev/null +++ b/uint16/benchmark/benchmark.set.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::array:set', function benchmark( b ) { + var values; + var buf; + var arr; + var N; + var v; + var i; + + values = []; + for ( i = 0; i < 10; i++ ) { + values.push( i ); + } + N = values.length; + + arr = new Uint16Array( 2 ); + buf = [ 0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = values[ i%N ]; + v = arr.set( buf ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array:set', function benchmark( b ) { + var values; + var buf; + var arr; + var N; + var v; + var i; + + values = new Uint16Array( 20 ); + N = values.length; + for ( i = 0; i < N; i++ ) { + values[ i ] = i; + } + + arr = new Uint16Array( 2 ); + buf = new Uint16Array( 1 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = values[ i%N ]; + v = arr.set( buf ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/benchmark/benchmark.set.length.js b/uint16/benchmark/benchmark.set.length.js new file mode 100644 index 00000000..be2a0c9f --- /dev/null +++ b/uint16/benchmark/benchmark.set.length.js @@ -0,0 +1,114 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randi = require( '@stdlib/random/base/randi' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var values; + var arr1; + var arr2; + var arr; + var N; + var i; + + arr1 = []; + arr2 = []; + for ( i = 0; i < len; i++ ) { + arr1.push( randi() ); + arr2.push( randi() ); + } + arr = new Uint16Array( len ); + + values = [ + arr1, + arr2 + ]; + N = values.length; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr.set( values[ i%N ] ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':set:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.slice.js b/uint16/benchmark/benchmark.slice.js new file mode 100644 index 00000000..e5c0dbb5 --- /dev/null +++ b/uint16/benchmark/benchmark.slice.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint16Array = require( '@stdlib/assert/is-uint16array' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':slice', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.slice(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint16Array( out ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/benchmark/benchmark.slice.length.js b/uint16/benchmark/benchmark.slice.length.js new file mode 100644 index 00000000..f5b60c8b --- /dev/null +++ b/uint16/benchmark/benchmark.slice.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint16Array = require( '@stdlib/assert/is-uint16array' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.slice(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint16Array( out ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':slice:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.some.js b/uint16/benchmark/benchmark.some.js new file mode 100644 index 00000000..6a9ede19 --- /dev/null +++ b/uint16/benchmark/benchmark.some.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':some', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:some', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate, {} ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/uint16/benchmark/benchmark.some.length.js b/uint16/benchmark/benchmark.some.length.js new file mode 100644 index 00000000..f5fc249e --- /dev/null +++ b/uint16/benchmark/benchmark.some.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':some:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.sort.js b/uint16/benchmark/benchmark.sort.js new file mode 100644 index 00000000..ce9f9124 --- /dev/null +++ b/uint16/benchmark/benchmark.sort.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var randi = require( '@stdlib/random/base/randi' ); +var isUint16Array = require( '@stdlib/assert/is-uint16array' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':sort', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint16Array( [ randi(), randi() ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = randi(); + out = arr.sort(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint16Array( out ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/benchmark/benchmark.sort.length.js b/uint16/benchmark/benchmark.sort.length.js new file mode 100644 index 00000000..5af89301 --- /dev/null +++ b/uint16/benchmark/benchmark.sort.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randi = require( '@stdlib/random/base/randi' ); +var isUint16Array = require( '@stdlib/assert/is-uint16array' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var data; + var arr; + var i; + + data = []; + for ( i = 0; i < len; i++ ) { + data.push( randi() ); + } + arr = new Uint16Array( data ); + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ i%len ] = randi(); + out = arr.sort(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint16Array( out ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':sort:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.subarray.js b/uint16/benchmark/benchmark.subarray.js new file mode 100644 index 00000000..ecfbb3e8 --- /dev/null +++ b/uint16/benchmark/benchmark.subarray.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint16Array = require( '@stdlib/assert/is-uint16array' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':subarray', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.subarray(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint16Array( out ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/benchmark/benchmark.subarray.length.js b/uint16/benchmark/benchmark.subarray.length.js new file mode 100644 index 00000000..b0931b06 --- /dev/null +++ b/uint16/benchmark/benchmark.subarray.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint16Array = require( '@stdlib/assert/is-uint16array' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.subarray(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint16Array( out ) ) { + b.fail( 'should return a Uint16Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':subarray:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.to_locale_string.js b/uint16/benchmark/benchmark.to_locale_string.js new file mode 100644 index 00000000..2afdc453 --- /dev/null +++ b/uint16/benchmark/benchmark.to_locale_string.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':toLocaleString', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toLocaleString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/benchmark/benchmark.to_locale_string.length.js b/uint16/benchmark/benchmark.to_locale_string.length.js new file mode 100644 index 00000000..f08d59c6 --- /dev/null +++ b/uint16/benchmark/benchmark.to_locale_string.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toLocaleString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':toLocaleString:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.to_string.js b/uint16/benchmark/benchmark.to_string.js new file mode 100644 index 00000000..4e731b56 --- /dev/null +++ b/uint16/benchmark/benchmark.to_string.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':toString', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/benchmark/benchmark.to_string.length.js b/uint16/benchmark/benchmark.to_string.length.js new file mode 100644 index 00000000..94478a00 --- /dev/null +++ b/uint16/benchmark/benchmark.to_string.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint16Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':toString:len='+len, f ); + } +} + +main(); diff --git a/uint16/benchmark/benchmark.values.js b/uint16/benchmark/benchmark.values.js new file mode 100644 index 00000000..5e39e6c1 --- /dev/null +++ b/uint16/benchmark/benchmark.values.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint16Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':values', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.values(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint16/docs/repl.txt b/uint16/docs/repl.txt new file mode 100644 index 00000000..43984e51 --- /dev/null +++ b/uint16/docs/repl.txt @@ -0,0 +1,953 @@ + +{{alias}}() + A typed array constructor which returns a typed array representing an array + of 16-bit unsigned integers in the platform byte order. + + Returns + ------- + out: Uint16Array + A typed array. + + Examples + -------- + > var arr = new {{alias}}() + + + +{{alias}}( length ) + Returns a typed array having a specified length. + + Parameters + ---------- + length: integer + Typed array length. + + Returns + ------- + out: Uint16Array + A typed array. + + Examples + -------- + > var arr = new {{alias}}( 5 ) + [ 0, 0, 0, 0, 0 ] + + +{{alias}}( typedarray ) + Creates a typed array from another typed array. + + Parameters + ---------- + typedarray: TypedArray + Typed array from which to generate another typed array. + + Returns + ------- + out: Uint16Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias:@stdlib/array/int32}}( [ 5, 5, 5 ] ); + > var arr2 = new {{alias}}( arr1 ) + [ 5, 5, 5 ] + + +{{alias}}( obj ) + Creates a typed array from an array-like object or iterable. + + Parameters + ---------- + obj: Object + Array-like object or iterable from which to generate a typed array. + + Returns + ------- + out: Uint16Array + A typed array. + + Examples + -------- + > var arr1 = [ 5.0, 5.0, 5.0 ]; + > var arr2 = new {{alias}}( arr1 ) + [ 5, 5, 5 ] + + +{{alias}}( buffer[, byteOffset[, length]] ) + Returns a typed array view of an ArrayBuffer. + + Parameters + ---------- + buffer: ArrayBuffer + Underlying ArrayBuffer. + + byteOffset: integer (optional) + Integer byte offset specifying the location of the first typed array + element. Default: 0. + + length: integer (optional) + View length. If not provided, the view spans from the byteOffset to + the end of the underlying ArrayBuffer. + + Returns + ------- + out: Uint16Array + A typed array. + + Examples + -------- + > var buf = new {{alias:@stdlib/array/buffer}}( 8 ); + > var arr = new {{alias}}( buf, 0, 4 ) + [ 0, 0, 0, 0 ] + + +{{alias}}.from( src[, map[, thisArg]] ) + Creates a new typed array from an array-like object or an iterable. + + A callback is provided the following arguments: + + - value: source value. + - index: source index. + + Parameters + ---------- + src: ArrayLike|Iterable + Source of array elements. + + map: Function (optional) + Callback to invoke for each source element. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Uint16Array + A typed array. + + Examples + -------- + > function mapFcn( v ) { return v * 2; }; + > var arr = {{alias}}.from( [ 1, 2 ], mapFcn ) + [ 2, 4 ] + + +{{alias}}.of( element0[, element1[, ...elementN]] ) + Creates a new typed array from a variable number of arguments. + + Parameters + ---------- + element0: number + Array element. + + element1: number (optional) + Array element. + + elementN: number (optional) + Array elements. + + Returns + ------- + out: Uint16Array + A typed array. + + Examples + -------- + > var arr = {{alias}}.of( 1, 2 ) + [ 1, 2 ] + + +{{alias}}.BYTES_PER_ELEMENT + Number of bytes per view element. + + Examples + -------- + > {{alias}}.BYTES_PER_ELEMENT + 2 + + +{{alias}}.name + Typed array constructor name. + + Examples + -------- + > {{alias}}.name + 'Uint16Array' + + +{{alias}}.prototype.buffer + Read-only property which returns the ArrayBuffer referenced by the typed + array. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.buffer + + + +{{alias}}.prototype.byteLength + Read-only property which returns the length (in bytes) of the typed array. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.byteLength + 10 + + +{{alias}}.prototype.byteOffset + Read-only property which returns the offset (in bytes) of the typed array + from the start of its ArrayBuffer. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.byteOffset + 0 + + +{{alias}}.prototype.BYTES_PER_ELEMENT + Number of bytes per view element. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.BYTES_PER_ELEMENT + 2 + + +{{alias}}.prototype.length + Read-only property which returns the number of view elements. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.length + 5 + + +{{alias}}.prototype.copyWithin( target, start[, end] ) + Copies a sequence of elements within the array starting at `start` and + ending at `end` (non-inclusive) to the position starting at `target`. + + Parameters + ---------- + target: integer + Target start index position. + + start: integer + Source start index position. + + end: integer (optional) + Source end index position. Default: out.length. + + Returns + ------- + out: Uint16Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3, 4, 5 ] ); + > arr.copyWithin( 3, 0, 2 ); + > arr[ 3 ] + 1 + > arr[ 4 ] + 2 + + +{{alias}}.prototype.entries() + Returns an iterator for iterating over array key-value pairs. + + Returns + ------- + iter: Iterator + Iterator for iterating over array key-value pairs. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.entries(); + > it.next().value + [ 0, 1 ] + > it.next().value + [ 1, 2 ] + > it.next().done + true + + +{{alias}}.prototype.every( predicate[, thisArg] ) + Tests whether all array elements pass a test implemented by a predicate + function. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. If a predicate function + returns a truthy value, an array element passes; otherwise, an array + element fails. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + bool: boolean + Boolean indicating whether all array elements pass. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > function predicate( v ) { return ( v <= 1 ); }; + > arr.every( predicate ) + false + + +{{alias}}.prototype.fill( value[, start[, end]] ) + Fills an array from a start index to an end index (non-inclusive) with a + provided value. + + Parameters + ---------- + value: number + Fill value. + + start: integer (optional) + Start index. If less than zero, the start index is resolved relative to + the last array element. Default: 0. + + end: integer (optional) + End index (non-inclusive). If less than zero, the end index is resolved + relative to the last array element. Default: out.length. + + Returns + ------- + out: Uint16Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > arr.fill( 3 ); + > arr[ 0 ] + 3 + > arr[ 1 ] + 3 + + +{{alias}}.prototype.filter( predicate[, thisArg] ) + Creates a new array which includes those elements for which a predicate + function returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + The returned array has the same data type as the host array. + + If a predicate function does not return a truthy value for any array + element, the method returns `null`. + + Parameters + ---------- + predicate: Function + Predicate function which filters array elements. If a predicate function + returns a truthy value, an array element is included in the output + array; otherwise, an array element is not included in the output array. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Uint16Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 1 ); }; + > var arr2 = arr1.filter( predicate ); + > arr2.length + 2 + + +{{alias}}.prototype.find( predicate[, thisArg] ) + Returns the first array element for which a provided predicate function + returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + If a predicate function never returns a truthy value, the method returns + `undefined`. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + value: number|undefined + Array element. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 2 ); }; + > var v = arr.find( predicate ) + 3 + + +{{alias}}.prototype.findIndex( predicate[, thisArg] ) + Returns the index of the first array element for which a provided predicate + function returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + If a predicate function never returns a truthy value, the method returns + `-1`. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + idx: integer + Array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 2 ); }; + > var idx = arr.findIndex( predicate ) + 2 + + +{{alias}}.prototype.forEach( fcn[, thisArg] ) + Invokes a callback for each array element. + + A provided function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + fcn: Function + Function to invoke for each array element. + + thisArg: Any (optional) + Callback execution context. + + Examples + -------- + > var arr = new {{alias}}( [ 3, 2, 1 ] ); + > var str = ' '; + > function fcn( v, i ) { str += i + ':' + v + ' '; }; + > arr.forEach( fcn ); + > str + ' 0:3 1:2 2:1 ' + + +{{alias}}.prototype.includes( searchElement[, fromIndex] ) + Returns a boolean indicating whether an array includes a search element. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: 0. + + Returns + ------- + bool: boolean + Boolean indicating whether an array includes a search element. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > var bool = arr.includes( 4 ) + false + > bool = arr.includes( 3 ) + true + + +{{alias}}.prototype.indexOf( searchElement[, fromIndex] ) + Returns the index of the first array element strictly equal to a search + element. + + If unable to locate a search element, the method returns `-1`. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: 0. + + Returns + ------- + idx: integer + Array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > var idx = arr.indexOf( 4 ) + -1 + > idx = arr.indexOf( 3 ) + 2 + + +{{alias}}.prototype.join( [separator] ) + Serializes an array by joining all array elements as a string. + + Parameters + ---------- + separator: string (optional) + String delineating array elements. Default: ','. + + Returns + ------- + str: string + Array serialized as a string. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.join( '|' ) + '1|2|3' + + +{{alias}}.prototype.keys() + Returns an iterator for iterating over array keys. + + Returns + ------- + iter: Iterator + Iterator for iterating over array keys. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.keys(); + > it.next().value + 0 + > it.next().value + 1 + > it.next().done + true + + +{{alias}}.prototype.lastIndexOf( searchElement[, fromIndex] ) + Returns the index of the last array element strictly equal to a search + element. + + The method iterates from the last array element to the first array element. + + If unable to locate a search element, the method returns `-1`. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: -1. + + Returns + ------- + idx: integer + array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 0, 2, 0, 1 ] ); + > var idx = arr.lastIndexOf( 3 ) + -1 + > idx = arr.lastIndexOf( 0 ) + 3 + + +{{alias}}.prototype.map( fcn[, thisArg] ) + Maps each array element to an element in a new typed array. + + A provided function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + The returned array has the same data type as the host array. + + Parameters + ---------- + fcn: Function + Function which maps array elements to elements in the new array. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Uint16Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( v ) { return v * 2; }; + > var arr2 = arr1.map( fcn ); + [ 2, 4, 6 ] + + +{{alias}}.prototype.reduce( fcn[, initialValue] ) + Applies a function against an accumulator and each element in an array and + returns the accumulated result. + + The provided function is provided the following arguments: + + - acc: accumulated result. + - value: current array element. + - index: index of the current array element. + - arr: array on which the method is invoked. + + If provided an initial value, the method invokes a provided function with + the initial value as the first argument and the first array element as the + second argument. + + If not provided an initial value, the method invokes a provided function + with the first array element as the first argument and the second array + element as the second argument. + + Parameters + ---------- + fcn: Function + Function to apply. + + initialValue: Any (optional) + Initial accumulation value. + + Returns + ------- + out: Any + Accumulated result. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( acc, v ) { return acc + (v*v); }; + > var v = arr.reduce( fcn, 0 ) + 14 + + +{{alias}}.prototype.reduceRight( fcn[, initialValue] ) + Applies a function against an accumulator and each element in an array and + returns the accumulated result, iterating from right to left. + + The provided function is provided the following arguments: + + - acc: accumulated result. + - value: current array element. + - index: index of the current array element. + - arr: array on which the method is invoked. + + If provided an initial value, the method invokes a provided function with + the initial value as the first argument and the last array element as the + second argument. + + If not provided an initial value, the method invokes a provided function + with the last array element as the first argument and the second-to-last + array element as the second argument. + + Parameters + ---------- + fcn: Function + Function to apply. + + initialValue: Any (optional) + Initial accumulation value. + + Returns + ------- + out: Any + Accumulated result. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( acc, v ) { return acc + (v*v); }; + > var v = arr.reduceRight( fcn, 0 ) + 14 + + +{{alias}}.prototype.reverse() + Reverses an array *in-place*. + + This method mutates the array on which the method is invoked. + + Returns + ------- + out: Uint16Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ) + [ 1, 2, 3 ] + > arr.reverse() + [ 3, 2, 1 ] + + +{{alias}}.prototype.set( arr[, offset] ) + Sets array elements. + + Parameters + ---------- + arr: ArrayLike + Source array containing array values to set. + + offset: integer (optional) + Array index at which to start writing values. Default: 0. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.set( [ 4, 4 ], 1 ); + > arr[ 1 ] + 4 + > arr[ 2 ] + 4 + + +{{alias}}.prototype.slice( [begin[, end]] ) + Copies array elements to a new array with the same underlying data type as + the host array. + + If the method is unable to resolve indices to a non-empty array subsequence, + the method returns `null`. + + Parameters + ---------- + begin: integer (optional) + Start element index (inclusive). If less than zero, the start index is + resolved relative to the last array element. Default: 0. + + end: integer (optional) + End element index (exclusive). If less than zero, the end index is + resolved relative to the last array element. Default: arr.length. + + Returns + ------- + out: Uint16Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > var arr2 = arr1.slice( 1 ); + > arr2.length + 2 + > arr2[ 0 ] + 1 + > arr2[ 1 ] + 2 + + +{{alias}}.prototype.some( predicate[, thisArg] ) + Tests whether at least one array element passes a test implemented by a + predicate function. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. If a predicate function + returns a truthy value, a array element passes; otherwise, an array + element fails. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + bool: boolean + Boolean indicating whether at least one array element passes. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > function predicate( v ) { return ( v > 1 ); }; + > arr.some( predicate ) + true + + +{{alias}}.prototype.sort( [compareFunction] ) + Sorts an array *in-place*. + + The comparison function is provided two array elements per invocation: `a` + and `b`. + + The comparison function return value determines the sort order as follows: + + - If the comparison function returns a value less than zero, then the method + sorts `a` to an index lower than `b` (i.e., `a` should come *before* `b`). + + - If the comparison function returns a value greater than zero, then the + method sorts `a` to an index higher than `b` (i.e., `b` should come *before* + `a`). + + - If the comparison function returns zero, then the relative order of `a` + and `b` should remain unchanged. + + This method mutates the array on which the method is invoked. + + Parameters + ---------- + compareFunction: Function (optional) + Function which specifies the sort order. The default sort order is + ascending order. + + Returns + ------- + out: Uint16Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 0, 2, 1 ] ); + > arr.sort() + [ 0, 1, 1, 2, 2 ] + + +{{alias}}.prototype.subarray( [begin[, end]] ) + Creates a new typed array over the same underlying ArrayBuffer and with the + same underlying data type as the host array. + + If the method is unable to resolve indices to a non-empty array subsequence, + the method returns an empty typed array. + + Parameters + ---------- + begin: integer (optional) + Start element index (inclusive). If less than zero, the start index is + resolved relative to the last array element. Default: 0. + + end: integer (optional) + End element index (exclusive). If less than zero, the end index is + resolved relative to the last array element. Default: arr.length. + + Returns + ------- + out: Uint16Array + A new typed array view. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3, 4, 5 ] ); + > var arr2 = arr1.subarray( 2 ) + [ 3, 4, 5 ] + + +{{alias}}.prototype.toLocaleString( [locales[, options]] ) + Serializes an array as a locale-specific string. + + Parameters + ---------- + locales: string|Array (optional) + A BCP 47 language tag, or an array of such tags. + + options: Object (optional) + Options. + + Returns + ------- + str: string + A typed array string representation. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.toLocaleString() + '1,2,3' + + +{{alias}}.prototype.toString() + Serializes an array as a string. + + Returns + ------- + str: string + A typed array string representation. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.toString() + '1,2,3' + + +{{alias}}.prototype.values() + Returns an iterator for iterating over array elements. + + Returns + ------- + iter: Iterator + Iterator for iterating over array elements. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.values(); + > it.next().value + 1 + > it.next().value + 2 + > it.next().done + true + + + See Also + -------- + diff --git a/uint16/docs/types/index.d.ts b/uint16/docs/types/index.d.ts new file mode 100644 index 00000000..c6081c4b --- /dev/null +++ b/uint16/docs/types/index.d.ts @@ -0,0 +1,26 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +// EXPORTS // + +/** +* Typed array constructor which returns a typed array representing an array of 16-bit unsigned integers in the platform byte order. +*/ +export = Uint16Array; diff --git a/uint16/docs/types/test.ts b/uint16/docs/types/test.ts new file mode 100644 index 00000000..53899384 --- /dev/null +++ b/uint16/docs/types/test.ts @@ -0,0 +1,37 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// tslint:disable: no-construct +// tslint:disable: no-unused-expression + +import Uint16Array = require( './index' ); + + +// TESTS // + +// The function returns a typed array instance... +{ + new Uint16Array( 10 ); // $ExpectType Uint16Array + new Uint16Array( [ 2, 5, 5, 7 ] ); // $ExpectType Uint16Array +} + +// The constructor function has to be invoked with `new`... +{ + Uint16Array( 10 ); // $ExpectError + Uint16Array( [ 2, 5, 5, 7 ] ); // $ExpectError +} diff --git a/uint16/examples/index.js b/uint16/examples/index.js new file mode 100644 index 00000000..d0978bec --- /dev/null +++ b/uint16/examples/index.js @@ -0,0 +1,32 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var randu = require( '@stdlib/random/base/randu' ); +var round = require( '@stdlib/math/base/special/round' ); +var ctor = require( './../lib' ); + +var arr; +var i; + +arr = new ctor( 10 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = round( randu()*100.0 ); +} +console.log( arr ); diff --git a/uint16/lib/index.js b/uint16/lib/index.js new file mode 100644 index 00000000..6ff9482c --- /dev/null +++ b/uint16/lib/index.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Typed array constructor which returns a typed array representing an array of 16-bit unsigned integers in the platform byte order. +* +* @module @stdlib/array/uint16 +* +* @example +* var ctor = require( '@stdlib/array/uint16' ); +* +* var arr = new ctor( 10 ); +* // returns +*/ + +// MODULES // + +var hasUint16ArraySupport = require( '@stdlib/assert/has-uint16array-support' ); +var builtin = require( './uint16array.js' ); +var polyfill = require( './polyfill.js' ); + + +// MAIN // + +var ctor; +if ( hasUint16ArraySupport() ) { + ctor = builtin; +} else { + ctor = polyfill; +} + + +// EXPORTS // + +module.exports = ctor; diff --git a/uint16/lib/polyfill.js b/uint16/lib/polyfill.js new file mode 100644 index 00000000..0d55e2b7 --- /dev/null +++ b/uint16/lib/polyfill.js @@ -0,0 +1,37 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// TODO: write polyfill + +// MAIN // + +/** +* Typed array which represents an array of 16-bit unsigned integers in the platform byte order. +* +* @throws {Error} not implemented +*/ +function polyfill() { + throw new Error( 'not implemented' ); +} + + +// EXPORTS // + +module.exports = polyfill; diff --git a/uint16/lib/uint16array.js b/uint16/lib/uint16array.js new file mode 100644 index 00000000..c6c4bcd9 --- /dev/null +++ b/uint16/lib/uint16array.js @@ -0,0 +1,28 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MAIN // + +var ctor = ( typeof Uint16Array === 'function' ) ? Uint16Array : void 0; // eslint-disable-line stdlib/require-globals + + +// EXPORTS // + +module.exports = ctor; diff --git a/uint16/package.json b/uint16/package.json new file mode 100644 index 00000000..67a4a877 --- /dev/null +++ b/uint16/package.json @@ -0,0 +1,70 @@ +{ + "name": "@stdlib/array/uint16", + "version": "0.0.0", + "description": "Uint16Array.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structure", + "array", + "typed", + "typed array", + "typed-array", + "uint16array", + "uint16", + "uint16_t", + "integer", + "int", + "uint", + "unsigned", + "short" + ] +} diff --git a/uint16/test/test.copy_within.js b/uint16/test/test.copy_within.js new file mode 100644 index 00000000..c8c3ab20 --- /dev/null +++ b/uint16/test/test.copy_within.js @@ -0,0 +1,320 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var hasProp = require( '@stdlib/assert/has-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var Uint16Array = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof Uint16Array, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'a typed array instance has a `copyWithin` method for copying a sequence of elements within a typed array', function test( t ) { + var arr = new Uint16Array( 2 ); + t.strictEqual( hasProp( arr, 'copyWithin' ), true, 'has property' ); + t.strictEqual( isFunction( arr.copyWithin ), true, 'has method' ); + t.end(); +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a typed array instance', function test( t ) { + var values; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0 ); + }; + } +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a typed array instance (end)', function test( t ) { + var values; + var arr; + var i; + + arr = new Uint16Array( 2 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0, 5 ); + }; + } +}); + +tape( 'the method copies a sequence of elements within a typed array', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint16Array( arr ); + p.copyWithin( 0, 3 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative target)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint16Array( arr ); + p.copyWithin( -p.length, 3 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative start)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint16Array( arr ); + p.copyWithin( 0, -2 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (end=length)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint16Array( arr ); + p.copyWithin( 0, 3, p.length ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (non-inclusive end)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint16Array( arr ); + p.copyWithin( 2, 0, 2 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative end)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint16Array( arr ); + p.copyWithin( 2, 0, -3 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (target >= length)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint16Array( arr ); + p.copyWithin( p.length, 3 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (target > start)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint16Array( arr ); + p.copyWithin( 2, 0 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + t.strictEqual( p[ 4 ], 2, 'returns expected value' ); + + t.end(); +}); diff --git a/uint16/test/test.js b/uint16/test/test.js new file mode 100644 index 00000000..4522fc92 --- /dev/null +++ b/uint16/test/test.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var hasUint16ArraySupport = require( '@stdlib/assert/has-uint16array-support' ); +var polyfill = require( './../lib/polyfill.js' ); +var ctor = require( './../lib' ); + + +// VARIABLES // + +var hasUint16Arrays = hasUint16ArraySupport(); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'if an environment supports `Uint16Array`, the export is an alias for `Uint16Array`', function test( t ) { + var Foo; + + Foo = proxyquire( './../lib', { + '@stdlib/assert/has-uint16array-support': isTrue, + './uint16array.js': Mock + }); + t.strictEqual( Foo, Mock, 'returns builtin' ); + + if ( hasUint16Arrays ) { + t.strictEqual( ctor, Uint16Array, 'is alias' ); // eslint-disable-line stdlib/require-globals + } + + t.end(); + + function Mock() { + return this; + } + + function isTrue() { + return true; + } +}); + +tape( 'if an environment does not support `Uint16Array`, the export is a polyfill', function test( t ) { + var Foo; + + Foo = proxyquire( './../lib', { + '@stdlib/assert/has-uint16array-support': isFalse + }); + + t.strictEqual( Foo, polyfill, 'returns polyfill' ); + t.end(); + + function isFalse() { + return false; + } +}); diff --git a/uint16/test/test.polyfill.js b/uint16/test/test.polyfill.js new file mode 100644 index 00000000..9d6fcb19 --- /dev/null +++ b/uint16/test/test.polyfill.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var ctor = require( './../lib/polyfill.js' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error when invoked', function test( t ) { + t.throws( foo, Error, 'throws an error' ); + t.end(); + + function foo() { + var f = new ctor(); // eslint-disable-line no-unused-vars + } +}); + +// TODO: tests diff --git a/uint32/README.md b/uint32/README.md new file mode 100644 index 00000000..82e38ac4 --- /dev/null +++ b/uint32/README.md @@ -0,0 +1,1431 @@ + + +# Uint32Array + +> [Typed array][mdn-typed-array] constructor which returns a [typed array][mdn-typed-array] representing an array of 32-bit unsigned integers in the platform byte order. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var Uint32Array = require( '@stdlib/array/uint32' ); +``` + +#### Uint32Array() + +A [typed array][mdn-typed-array] constructor which returns a [typed array][mdn-typed-array] representing an array of 32-bit unsigned integers in the platform byte order. + + + +```javascript +var arr = new Uint32Array(); +// returns +``` + +#### Uint32Array( length ) + +Returns a [typed array][mdn-typed-array] having a specified length. + + + +```javascript +var arr = new Uint32Array( 5 ); +// returns [ 0, 0, 0, 0, 0 ] +``` + +#### Uint32Array( typedarray ) + +Creates a [typed array][mdn-typed-array] from another [typed array][mdn-typed-array]. + + + +```javascript +var Float32Array = require( '@stdlib/array/float32' ); + +var arr1 = new Float32Array( [ 5.0, 5.0, 5.0 ] ); +var arr2 = new Uint32Array( arr1 ); +// returns [ 5, 5, 5 ] +``` + +#### Uint32Array( obj ) + +Creates a [typed array][mdn-typed-array] from an array-like `object` or iterable. + + + +```javascript +var arr = new Uint32Array( [ 5.0, 5.0, 5.0 ] ); +// returns [ 5, 5, 5 ] +``` + +#### Uint32Array( buffer\[, byteOffset\[, length]] ) + +Returns a [typed array][mdn-typed-array] view of an [`ArrayBuffer`][@stdlib/array/buffer]. + + + +```javascript +var ArrayBuffer = require( '@stdlib/array/buffer' ); + +var buf = new ArrayBuffer( 16 ); +var arr = new Uint32Array( buf, 0, 4 ); +// returns [ 0, 0, 0, 0 ] +``` + +* * * + +### Properties + + + +#### Uint32Array.BYTES_PER_ELEMENT + +Number of bytes per view element. + + + +```javascript +var nbytes = Uint32Array.BYTES_PER_ELEMENT; +// returns 4 +``` + + + +#### Uint32Array.name + +[Typed array][mdn-typed-array] constructor name. + + + +```javascript +var str = Uint32Array.name; +// returns 'Uint32Array' +``` + + + +#### Uint32Array.prototype.buffer + +**Read-only** property which returns the [`ArrayBuffer`][@stdlib/array/buffer] referenced by the [typed array][mdn-typed-array]. + + + +```javascript +var arr = new Uint32Array( 5 ); +var buf = arr.buffer; +// returns +``` + + + +#### Uint32Array.prototype.byteLength + +**Read-only** property which returns the length (in bytes) of the [typed array][mdn-typed-array]. + + + +```javascript +var arr = new Uint32Array( 5 ); +var byteLength = arr.byteLength; +// returns 20 +``` + + + +#### Uint32Array.prototype.byteOffset + +**Read-only** property which returns the offset (in bytes) of the [typed array][mdn-typed-array] from the start of its [`ArrayBuffer`][@stdlib/array/buffer]. + + + +```javascript +var arr = new Uint32Array( 5 ); +var byteOffset = arr.byteOffset; +// returns 0 +``` + + + +#### Uint32Array.prototype.BYTES_PER_ELEMENT + +Number of bytes per view element. + + + +```javascript +var arr = new Uint32Array( 5 ); +var nbytes = arr.BYTES_PER_ELEMENT; +// returns 4 +``` + + + +#### Uint32Array.prototype.length + +**Read-only** property which returns the number of view elements. + + + +```javascript +var arr = new Uint32Array( 5 ); +var len = arr.length; +// returns 5 +``` + +* * * + +### Methods + + + +#### Uint32Array.from( src\[, map\[, thisArg]] ) + +Creates a new typed array from an array-like `object` or an iterable. + +```javascript +var arr = Uint32Array.from( [ 1, 2 ] ); +// returns [ 1, 2 ] +``` + +To invoke a function for each `src` value, provide a callback function. + +```javascript +function mapFcn( v ) { + return v * 2; +} + +var arr = Uint32Array.from( [ 1, 2 ], mapFcn ); +// returns [ 2, 4 ] +``` + +A callback function is provided two arguments: + +- `value`: source value +- `index`: source index + +To set the callback execution context, provide a `thisArg`. + +```javascript +function mapFcn( v ) { + this.count += 1; + return v * 2; +} + +var ctx = { + 'count': 0 +}; + +var arr = Uint32Array.from( [ 1, 2 ], mapFcn, ctx ); +// returns [ 2, 4 ] + +var n = ctx.count; +// returns 2 +``` + + + +#### Uint32Array.of( element0\[, element1\[, ...elementN]] ) + +Creates a new typed array from a variable number of arguments. + +```javascript +var arr = Uint32Array.of( 1, 2 ); +// returns [ 1, 2 ] +``` + + + +#### Uint32Array.prototype.copyWithin( target, start\[, end] ) + +Copies a sequence of elements within an array starting at `start` and ending at `end` (non-inclusive) to the position starting at `target`. + + + +```javascript +var arr = new Uint32Array( [ 1, 2, 3, 4, 5 ] ); + +// Copy the last two elements to the first two elements: +arr.copyWithin( 0, 3 ); + +var v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 5 +``` + +By default, `end` equals the number of array elements (i.e., one more than the last array index). To limit the sequence length, provide an `end` argument. + + + +```javascript +var arr = new Uint32Array( [ 1, 2, 3, 4, 5 ] ); + +// Copy the first two elements to the last two elements: +arr.copyWithin( 3, 0, 2 ); + +var v = arr[ 3 ]; +// returns 1 + +v = arr[ 4 ]; +// returns 2 +``` + +When a `target`, `start`, and/or `end` index is negative, the respective index is determined relative to the last array element. The following example achieves the same behavior as the previous example: + + + +```javascript +var arr = new Uint32Array( [ 1, 2, 3, 4, 5 ] ); + +// Copy the first two elements to the last two elements: +arr.copyWithin( -2, -5, -3 ); + +var v = arr[ 3 ]; +// returns 1 + +v = arr[ 4 ]; +// returns 2 +``` + + + +#### Uint32Array.prototype.entries() + +Returns an iterator for iterating over array key-value pairs. + + + +```javascript +var arr = new Uint32Array( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.entries(); + +// Iterate over key-value pairs... +var v = it.next().value; +// returns [ 0, 1 ] + +v = it.next().value; +// returns [ 1, 2 ] + +var bool = it.next().done; +// returns true +``` + + + +#### Uint32Array.prototype.every( predicate\[, thisArg] ) + +Tests whether all array elements pass a test implemented by a `predicate` function. + + + +```javascript +function predicate( v ) { + return ( v <= 1 ); +} + +var arr = new Uint32Array( [ 1, 2 ] ); + +var bool = arr.every( predicate ); +// returns false +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 1 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint32Array( [ 1, 2 ] ); + +var bool = arr.every( predicate, ctx ); +// returns true + +var n = ctx.count; +// returns 2 +``` + + + +#### Uint32Array.prototype.fill( value\[, start\[, end]] ) + +Fills an array from a `start` index to an `end` index (non-inclusive) with a provided `value`. + + + +```javascript +var arr = new Uint32Array( 2 ); + +// Set all array elements to the same value: +arr.fill( 2 ); + +var v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 2 + +// Set all array elements starting from the first index to the same value: +arr.fill( 3, 1 ); + +v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 3 + +// Set all array elements, except the last element, to the same value: +arr.fill( 4, 0, arr.length-1 ); + +v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 3 +``` + +When a `start` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr = new Uint32Array( 2 ); + +// Set all array elements, except the last element, to the same value: +arr.fill( 2, -arr.length, -1 ); + +var v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 0 +``` + + + +#### Uint32Array.prototype.filter( predicate\[, thisArg] ) + +Creates a new array (of the same data type as the host array) which includes those elements for which a `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v >= 2 ); +} + +var arr1 = new Uint32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate ); +// returns [ 2, 3 ] +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns an empty array. + + + +```javascript +function predicate( v ) { + return ( v >= 10 ); +} + +var arr1 = new Uint32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate ); +// returns [] +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr1 = new Uint32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint32Array.prototype.find( predicate\[, thisArg] ) + +Returns the first array element for which a provided `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v > 2 ); +} + +var arr = new Uint32Array( [ 1, 2, 3 ] ); + +var v = arr.find( predicate ); +// returns 3 +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns `undefined`. + + + +```javascript +function predicate( v ) { + return ( v < 1 ); +} + +var arr = new Uint32Array( [ 1, 2, 3 ] ); + +var v = arr.find( predicate ); +// returns undefined +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v > 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint32Array( [ 1, 2, 3 ] ); + +var v = arr.find( predicate, ctx ); +// returns 3 + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint32Array.prototype.findIndex( predicate\[, thisArg] ) + +Returns the index of the first array element for which a provided `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v >= 3 ); +} + +var arr = new Uint32Array( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate ); +// returns 2 +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns `-1`. + + + +```javascript +function predicate( v ) { + return ( v < 1 ); +} + +var arr = new Uint32Array( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate ); +// returns -1 +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 3 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint32Array( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate, ctx ); +// returns 2 + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint32Array.prototype.forEach( fcn\[, thisArg] ) + +Invokes a callback for each array element. + + + +```javascript +var arr = new Uint32Array( [ 1, 2, 3 ] ); + +var str = ''; + +function fcn( v, i ) { + str += i + ':' + v; + if ( i < arr.length-1 ) { + str += ' '; + } +} + +arr.forEach( fcn ); + +console.log( str ); +// => '0:1 1:2 2:3' +``` + +The callback is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function fcn() { + this.count += 1; +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint32Array( [ 1, 2, 3 ] ); + +arr.forEach( fcn, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint32Array.prototype.includes( searchElement\[, fromIndex] ) + +Returns a `boolean` indicating whether an array includes a search element. + + + +```javascript +var arr = new Uint32Array( [ 1, 2, 3 ] ); + +var bool = arr.includes( 3 ); +// returns true + +bool = arr.includes( 0 ); +// returns false +``` + +By default, the method searches the entire array (`fromIndex = 0`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Uint32Array( [ 1, 2, 3 ] ); + +var bool = arr.includes( 1, 1 ); +// returns false +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Uint32Array( [ 1, 2, 3 ] ); + +bool = arr.includes( 1, -2 ); +// returns false +``` + + + +#### Uint32Array.prototype.indexOf( searchElement\[, fromIndex] ) + +Returns the index of the first array element strictly equal to a search element. + + + +```javascript +var arr = new Uint32Array( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 3 ); +// returns 2 + +idx = arr.indexOf( 0 ); +// returns -1 +``` + +By default, the method searches the entire array (`fromIndex = 0`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Uint32Array( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 1, 1 ); +// returns -1 +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Uint32Array( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 1, -2 ); +// returns -1 +``` + + + +#### Uint32Array.prototype.join( \[separator] ) + +Serializes an array by joining all array elements as a string. + + + +```javascript +var arr = new Uint32Array( [ 1, 2, 3 ] ); + +var str = arr.join(); +// returns '1,2,3' +``` + +By default, the method delineates array elements using a comma `,`. To specify a custom separator, provide a `separator` string. + + + +```javascript +var arr = new Uint32Array( [ 1, 2, 3 ] ); + +var str = arr.join( '|' ); +// returns '1|2|3' +``` + + + +#### Uint32Array.prototype.keys() + +Returns an iterator for iterating over array keys. + + + +```javascript +var arr = new Uint32Array( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.keys(); + +// Iterate over keys... +var v = it.next().value; +// returns 0 + +v = it.next().value; +// returns 1 + +var bool = it.next().done; +// returns true +``` + + + +#### Uint32Array.prototype.lastIndexOf( searchElement\[, fromIndex] ) + +Returns the index of the last array element strictly equal to a search element, iterating from right to left. + + + +```javascript +var arr = new Uint32Array( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0 ); +// returns 3 + +idx = arr.lastIndexOf( 3 ); +// returns -1 +``` + +By default, the method searches the entire array (`fromIndex = -1`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Uint32Array( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0, 2 ); +// returns 1 +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Uint32Array( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0, -3 ); +// returns 1 +``` + + + +#### Uint32Array.prototype.map( fcn\[, thisArg] ) + +Maps each array element to an element in a new array having the same data type as the host array. + + + +```javascript +function fcn( v ) { + return v * 2; +} + +var arr1 = new Uint32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.map( fcn ); +// returns [ 2, 4, 6 ] +``` + +A callback is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function fcn( v ) { + this.count += 1; + return v * 2; +} + +var ctx = { + 'count': 0 +}; + +var arr1 = new Uint32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.map( fcn, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint32Array.prototype.reduce( fcn\[, initialValue] ) + +Applies a function against an accumulator and each element in an array and returns the accumulated result. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Uint32Array( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn ); +// returns 12 +``` + +If not provided an initial value, the method invokes a provided function with the first array element as the first argument and the second array element as the second argument. + +If provided an initial value, the method invokes a provided function with the initial value as the first argument and the first array element as the second argument. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Uint32Array( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn, 0 ); +// returns 14 +``` + +A callback is provided four arguments: + +- `acc`: accumulated result +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + + + +#### Uint32Array.prototype.reduceRight( fcn\[, initialValue] ) + +Applies a function against an accumulator and each element in an array and returns the accumulated result, iterating from right to left. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Uint32Array( [ 2, 1, 3 ] ); + +var v = arr.reduceRight( fcn ); +// returns 8 +``` + +If not provided an initial value, the method invokes a provided function with the last array element as the first argument and the second-to-last array element as the second argument. + +If provided an initial value, the method invokes a provided function with the initial value as the first argument and the last array element as the second argument. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Uint32Array( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn, 0 ); +// returns 14 +``` + +A callback is provided four arguments: + +- `acc`: accumulated result +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + + + +#### Uint32Array.prototype.reverse() + +Reverses an array **in-place** (thus mutating the array on which the method is invoked). + + + +```javascript +var arr = new Uint32Array( [ 2, 0, 3 ] ); + +// Reverse the array: +arr.reverse(); + +var v = arr[ 0 ]; +// returns 3 + +v = arr[ 1 ]; +// returns 0 + +v = arr[ 2 ]; +// returns 2 +``` + + + +#### Uint32Array.prototype.set( arr\[, offset] ) + +Sets array elements. + + + +```javascript +var arr = new Uint32Array( [ 1, 2, 3 ] ); +// returns [ 1, 2, 3 ] + +// Set the first two array elements: +arr.set( [ 4, 5 ] ); + +var v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 5 +``` + +By default, the method starts writing values at the first array index. To specify an alternative index, provide an index `offset`. + + + +```javascript +var arr = new Uint32Array( [ 1, 2, 3 ] ); +// returns [ 1, 2, 3 ] + +// Set the last two array elements: +arr.set( [ 4, 5 ], 1 ); + +var v = arr[ 1 ]; +// returns 4 + +v = arr[ 2 ]; +// returns 5 +``` + + + +#### Uint32Array.prototype.slice( \[begin\[, end]] ) + +Copies array elements to a new array with the same underlying data type as the host array. + + + +```javascript +var arr1 = new Uint32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice(); + +var bool = ( arr1 === arr2 ); +// returns false + +bool = ( arr1.buffer === arr2.buffer ); +// returns false + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 + +v = arr2[ 2 ]; +// returns 3 +``` + +By default, the method copies elements beginning with the first array element. To specify an alternative array index at which to begin copying, provide a `begin` index (inclusive). + + + +```javascript +var arr1 = new Uint32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( 1 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 2 + +v = arr2[ 1 ]; +// returns 3 +``` + +By default, the method copies all array elements after `begin`. To specify an alternative array index at which to end copying, provide an `end` index (exclusive). + + + +```javascript +var arr1 = new Uint32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( 0, 2 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 +``` + +When a `begin` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr1 = new Uint32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( -arr1.length, -1 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 +``` + + + +#### Uint32Array.prototype.some( predicate\[, thisArg] ) + +Tests whether at least one array element passes a test implemented by a `predicate` function. + + + +```javascript +function predicate( v ) { + return ( v >= 2 ); +} + +var arr = new Uint32Array( [ 1, 2 ] ); + +var bool = arr.some( predicate ); +// returns true +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint32Array( [ 1, 1 ] ); + +var bool = arr.some( predicate, ctx ); +// returns false + +var n = ctx.count; +// returns 2 +``` + + + +#### Uint32Array.prototype.sort( \[compareFunction] ) + +Sorts an array **in-place** (thus mutating the array on which the method is invoked). + + + +```javascript +var arr = new Uint32Array( [ 2, 3, 0 ] ); + +// Sort the array (in ascending order): +arr.sort(); + +var v = arr[ 0 ]; +// returns 0 + +v = arr[ 1 ]; +// returns 2 + +v = arr[ 2 ]; +// returns 3 +``` + +By default, the method sorts array elements in ascending order. To impose a custom order, provide a `compareFunction`. + + + +```javascript +function descending( a, b ) { + return b - a; +} + +var arr = new Uint32Array( [ 2, 3, 0 ] ); + +// Sort the array (in descending order): +arr.sort( descending ); + +var v = arr[ 0 ]; +// returns 3 + +v = arr[ 1 ]; +// returns 2 + +v = arr[ 2 ]; +// returns 0 +``` + +The comparison function is provided two array elements, `a` and `b`, per invocation, and its return value determines the sort order as follows: + +- If the comparison function returns a value **less** than zero, then the method sorts `a` to an index lower than `b` (i.e., `a` should come **before** `b`). +- If the comparison function returns a value **greater** than zero, then the method sorts `a` to an index higher than `b` (i.e., `b` should come **before** `a`). +- If the comparison function returns **zero**, then the relative order of `a` and `b` _should_ remain unchanged. + + + +#### Uint32Array.prototype.subarray( \[begin\[, end]] ) + +Creates a new typed array view over the same underlying [`ArrayBuffer`][@stdlib/array/buffer] and with the same underlying data type as the host array. + + + +```javascript +var arr1 = new Uint32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray(); +// returns [ 1, 2, 3 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +By default, the method creates a typed array view beginning with the first array element. To specify an alternative array index at which to begin, provide a `begin` index (inclusive). + + + +```javascript +var arr1 = new Uint32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 1 ); +// returns [ 2, 3 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +By default, the method creates a typed array view which includes all array elements after `begin`. To limit the number of array elements after `begin`, provide an `end` index (exclusive). + + + +```javascript +var arr1 = new Uint32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 0, 2 ); +// returns [ 1, 2 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +When a `begin` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr1 = new Uint32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( -arr1.length, -1 ); +// returns [ 1, 2 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +If the method is unable to resolve indices to a non-empty array subsequence, the method returns an empty typed array. + + + +```javascript +var arr1 = new Uint32Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 10, -1 ); +// returns [] +``` + + + +#### Uint32Array.prototype.toLocaleString( \[locales\[, options]] ) + +Serializes an array as a locale-specific `string`. + + + +```javascript +var arr = new Uint32Array( [ 1, 2, 3 ] ); + +var str = arr.toLocaleString(); +// returns '1,2,3' +``` + + + +#### Uint32Array.prototype.toString() + +Serializes an array as a `string`. + + + +```javascript +var arr = new Uint32Array( [ 1, 2, 3 ] ); + +var str = arr.toString(); +// returns '1,2,3' +``` + + + +#### Uint32Array.prototype.values() + +Returns an iterator for iterating over array elements. + + + +```javascript +var arr = new Uint32Array( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.values(); + +// Iterate over array elements... +var v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 2 + +var bool = it.next().done; +// returns true +``` + +
+ + + +* * * + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var randu = require( '@stdlib/random/base/randu' ); +var round = require( '@stdlib/math/base/special/round' ); +var ctor = require( '@stdlib/array/uint32' ); + +var arr; +var i; + +arr = new ctor( 10 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = round( randu()*100.0 ); +} +console.log( arr ); +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/uint32/benchmark/benchmark.copy_within.js b/uint32/benchmark/benchmark.copy_within.js new file mode 100644 index 00000000..c9ddce74 --- /dev/null +++ b/uint32/benchmark/benchmark.copy_within.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':copyWithin', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr[ 0 ] = v; + arr = arr.copyWithin( 1, 0 ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/benchmark/benchmark.copy_within.length.js b/uint32/benchmark/benchmark.copy_within.length.js new file mode 100644 index 00000000..1822878d --- /dev/null +++ b/uint32/benchmark/benchmark.copy_within.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr[ 0 ] = v; + arr = arr.copyWithin( 1, 0 ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':copyWithin:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.data.js b/uint32/benchmark/benchmark.data.js new file mode 100644 index 00000000..e2999221 --- /dev/null +++ b/uint32/benchmark/benchmark.data.js @@ -0,0 +1,75 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::get,index', function benchmark( b ) { + var arr; + var N; + var v; + var i; + + arr = new Uint32Array( 2 ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr[ i%N ]; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::set,index', function benchmark( b ) { + var arr; + var N; + var i; + + arr = new Uint32Array( 2 ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ i%N ] = i; + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] || arr[ 1 ] !== arr[ 1 ] ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/benchmark/benchmark.entries.js b/uint32/benchmark/benchmark.entries.js new file mode 100644 index 00000000..b14d89bd --- /dev/null +++ b/uint32/benchmark/benchmark.entries.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':entries', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Uint32Array( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.entries(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/benchmark/benchmark.every.js b/uint32/benchmark/benchmark.every.js new file mode 100644 index 00000000..27e2f00d --- /dev/null +++ b/uint32/benchmark/benchmark.every.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':every', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); + +bench( pkg+'::this_context:every', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate, {} ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); diff --git a/uint32/benchmark/benchmark.every.length.js b/uint32/benchmark/benchmark.every.length.js new file mode 100644 index 00000000..92bc5336 --- /dev/null +++ b/uint32/benchmark/benchmark.every.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value >= 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':every:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.fill.js b/uint32/benchmark/benchmark.fill.js new file mode 100644 index 00000000..ad81b7bf --- /dev/null +++ b/uint32/benchmark/benchmark.fill.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':fill', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr = arr.fill( v ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/benchmark/benchmark.fill.length.js b/uint32/benchmark/benchmark.fill.length.js new file mode 100644 index 00000000..cd975c94 --- /dev/null +++ b/uint32/benchmark/benchmark.fill.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr = arr.fill( v ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':fill:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.filter.js b/uint32/benchmark/benchmark.filter.js new file mode 100644 index 00000000..2482f798 --- /dev/null +++ b/uint32/benchmark/benchmark.filter.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint32Array = require( '@stdlib/assert/is-uint32array' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':filter', function benchmark( b ) { + var arr; + var out; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint32Array( out ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); + +bench( pkg+'::this_context:filter', function benchmark( b ) { + var arr; + var out; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate, {} ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint32Array( out ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); diff --git a/uint32/benchmark/benchmark.filter.length.js b/uint32/benchmark/benchmark.filter.length.js new file mode 100644 index 00000000..9f0be6f7 --- /dev/null +++ b/uint32/benchmark/benchmark.filter.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint32Array = require( '@stdlib/assert/is-uint32array' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value >= 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint32Array( out ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':filter:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.find.js b/uint32/benchmark/benchmark.find.js new file mode 100644 index 00000000..ed2e4fd0 --- /dev/null +++ b/uint32/benchmark/benchmark.find.js @@ -0,0 +1,82 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':find', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:find', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate, {} ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/uint32/benchmark/benchmark.find.length.js b/uint32/benchmark/benchmark.find.length.js new file mode 100644 index 00000000..594f6f3a --- /dev/null +++ b/uint32/benchmark/benchmark.find.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - tuple length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint32Array( len ); + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':find:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.find_index.js b/uint32/benchmark/benchmark.find_index.js new file mode 100644 index 00000000..e724bed5 --- /dev/null +++ b/uint32/benchmark/benchmark.find_index.js @@ -0,0 +1,82 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':findIndex', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:findIndex', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate, {} ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/uint32/benchmark/benchmark.find_index.length.js b/uint32/benchmark/benchmark.find_index.length.js new file mode 100644 index 00000000..6cbba8ce --- /dev/null +++ b/uint32/benchmark/benchmark.find_index.length.js @@ -0,0 +1,104 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':findIndex:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.for_each.js b/uint32/benchmark/benchmark.for_each.js new file mode 100644 index 00000000..8b5ae015 --- /dev/null +++ b/uint32/benchmark/benchmark.for_each.js @@ -0,0 +1,88 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':forEach', function benchmark( b ) { + var count; + var arr; + var N; + var i; + + arr = new Uint32Array( 2 ); + N = arr.length; + + count = 0; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn ); + if ( count !== N*(i+1) ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( count !== N*i ) { + b.fail( 'unexpected result' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn() { + count += 1; + } +}); + +bench( pkg+'::this_context:forEach', function benchmark( b ) { + var count; + var arr; + var N; + var i; + + arr = new Uint32Array( 2 ); + N = arr.length; + + count = 0; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn, {} ); + if ( count !== N*(i+1) ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( count !== N*i ) { + b.fail( 'unexpected result' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn() { + count += 1; + } +}); diff --git a/uint32/benchmark/benchmark.for_each.length.js b/uint32/benchmark/benchmark.for_each.length.js new file mode 100644 index 00000000..d888fdf7 --- /dev/null +++ b/uint32/benchmark/benchmark.for_each.length.js @@ -0,0 +1,106 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var count; + var arr; + + arr = new Uint32Array( len ); + count = 0; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn ); + if ( count !== count ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( count !== count ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } + + /** + * Callback invoked for each tuple element. + * + * @private + */ + function fcn() { + count += 1; + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':forEach:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.from.js b/uint32/benchmark/benchmark.from.js new file mode 100644 index 00000000..4ff139df --- /dev/null +++ b/uint32/benchmark/benchmark.from.js @@ -0,0 +1,237 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var ITERATOR_SYMBOL = require( '@stdlib/symbol/iterator' ); +var isUint32Array = require( '@stdlib/assert/is-uint32array' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// VARIABLES // + +var opts = { + 'skip': ( ITERATOR_SYMBOL === null ) +}; + + +// MAIN // + +bench( pkg+'::typed_array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Uint32Array( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint32Array.from( buf ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint32Array( arr ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array,clbk:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Uint32Array( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint32Array.from( buf, clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint32Array( arr ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1; + } +}); + +bench( pkg+'::array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1, 2 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint32Array.from( buf ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint32Array( arr ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::array,clbk:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1, 2 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint32Array.from( buf, clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint32Array( arr ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1; + } +}); + +bench( pkg+'::iterable:from', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint32Array.from( createIterable() ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint32Array( arr ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out; + var i; + + out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + + i = 0; + + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + i += 1; + if ( i <= 2 ) { + return { + 'value': 0, + 'done': false + }; + } + return { + 'done': true + }; + } + } +}); + +bench( pkg+'::iterable,clbk:from:', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint32Array.from( createIterable(), clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint32Array( arr ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out; + var i; + + out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + + i = 0; + + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + i += 1; + if ( i <= 2 ) { + return { + 'value': 1, + 'done': false + }; + } + return { + 'done': true + }; + } + } + + function clbk( v ) { + return v + 1; + } +}); diff --git a/uint32/benchmark/benchmark.includes.js b/uint32/benchmark/benchmark.includes.js new file mode 100644 index 00000000..e161e273 --- /dev/null +++ b/uint32/benchmark/benchmark.includes.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':includes', function benchmark( b ) { + var bool; + var arr; + var v; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + bool = arr.includes( v ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/benchmark/benchmark.includes.length.js b/uint32/benchmark/benchmark.includes.length.js new file mode 100644 index 00000000..3472fabb --- /dev/null +++ b/uint32/benchmark/benchmark.includes.length.js @@ -0,0 +1,96 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + bool = arr.includes( v ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':includes:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.index_of.js b/uint32/benchmark/benchmark.index_of.js new file mode 100644 index 00000000..7f04d965 --- /dev/null +++ b/uint32/benchmark/benchmark.index_of.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':indexOf', function benchmark( b ) { + var out; + var arr; + var v; + var i; + + arr = new Uint32Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.indexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/benchmark/benchmark.index_of.length.js b/uint32/benchmark/benchmark.index_of.length.js new file mode 100644 index 00000000..9adbbeec --- /dev/null +++ b/uint32/benchmark/benchmark.index_of.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.indexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':indexOf:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.join.js b/uint32/benchmark/benchmark.join.js new file mode 100644 index 00000000..74605f53 --- /dev/null +++ b/uint32/benchmark/benchmark.join.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':join', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i % 127; + out = arr.join(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/benchmark/benchmark.join.length.js b/uint32/benchmark/benchmark.join.length.js new file mode 100644 index 00000000..8533a129 --- /dev/null +++ b/uint32/benchmark/benchmark.join.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i % 127; + out = arr.join(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':join:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.js b/uint32/benchmark/benchmark.js new file mode 100644 index 00000000..bcdf8691 --- /dev/null +++ b/uint32/benchmark/benchmark.js @@ -0,0 +1,47 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint32Array = require( '@stdlib/assert/is-uint32array' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new ctor( 0 ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isUint32Array( arr ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/benchmark/benchmark.keys.js b/uint32/benchmark/benchmark.keys.js new file mode 100644 index 00000000..e3d8e656 --- /dev/null +++ b/uint32/benchmark/benchmark.keys.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':keys', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.keys(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/benchmark/benchmark.last_index_of.js b/uint32/benchmark/benchmark.last_index_of.js new file mode 100644 index 00000000..dd0e5847 --- /dev/null +++ b/uint32/benchmark/benchmark.last_index_of.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':lastIndexOf', function benchmark( b ) { + var out; + var arr; + var v; + var i; + + arr = new Uint32Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.lastIndexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/benchmark/benchmark.last_index_of.length.js b/uint32/benchmark/benchmark.last_index_of.length.js new file mode 100644 index 00000000..03ab92e9 --- /dev/null +++ b/uint32/benchmark/benchmark.last_index_of.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.lastIndexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':lastIndexOf:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.length.js b/uint32/benchmark/benchmark.length.js new file mode 100644 index 00000000..75638104 --- /dev/null +++ b/uint32/benchmark/benchmark.length.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint32Array = require( '@stdlib/assert/is-uint32array' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new ctor( len ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isUint32Array( arr ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.map.js b/uint32/benchmark/benchmark.map.js new file mode 100644 index 00000000..b57414a6 --- /dev/null +++ b/uint32/benchmark/benchmark.map.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint32Array = require( '@stdlib/assert/is-uint32array' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':map', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint32Array( out ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); + +bench( pkg+'::this_context:map', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn, {} ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint32Array( out ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/uint32/benchmark/benchmark.map.length.js b/uint32/benchmark/benchmark.map.length.js new file mode 100644 index 00000000..0fed7073 --- /dev/null +++ b/uint32/benchmark/benchmark.map.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint32Array = require( '@stdlib/assert/is-uint32array' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Maps an array element to a new value. +* +* @private +* @param {*} value - array element +* @returns {*} new value +*/ +function fcn( value ) { + return value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint32Array( out ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':map:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.of.js b/uint32/benchmark/benchmark.of.js new file mode 100644 index 00000000..4b7f085c --- /dev/null +++ b/uint32/benchmark/benchmark.of.js @@ -0,0 +1,48 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint32Array = require( '@stdlib/assert/is-uint32array' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':of', function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint32Array.of( i, 2 ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint32Array( arr ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/benchmark/benchmark.properties.js b/uint32/benchmark/benchmark.properties.js new file mode 100644 index 00000000..75282035 --- /dev/null +++ b/uint32/benchmark/benchmark.properties.js @@ -0,0 +1,145 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isArrayBuffer = require( '@stdlib/assert/is-arraybuffer' ); +var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::get:buffer', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.buffer; + if ( typeof v !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isArrayBuffer( v ) ) { + b.fail( 'should return an ArrayBuffer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteLength', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteLength; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteOffset', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteOffset; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:BYTES_PER_ELEMENT', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.BYTES_PER_ELEMENT; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:length', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.length; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/benchmark/benchmark.reduce.js b/uint32/benchmark/benchmark.reduce.js new file mode 100644 index 00000000..1a8a0858 --- /dev/null +++ b/uint32/benchmark/benchmark.reduce.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reduce', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( acc, v ) { + return acc + v + 1; + } +}); + +bench( pkg+'::initial_value:reduce', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn, 3 ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/uint32/benchmark/benchmark.reduce.length.js b/uint32/benchmark/benchmark.reduce.length.js new file mode 100644 index 00000000..36d875fb --- /dev/null +++ b/uint32/benchmark/benchmark.reduce.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Updates an accumulated value. +* +* @private +* @param {*} acc - accumulated value +* @param {*} value - array element +* @returns {*} accumulated value +*/ +function fcn( acc, value ) { + return acc + value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reduce:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.reduce_right.js b/uint32/benchmark/benchmark.reduce_right.js new file mode 100644 index 00000000..22685d20 --- /dev/null +++ b/uint32/benchmark/benchmark.reduce_right.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reduceRight', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( acc, v ) { + return acc + v + 1; + } +}); + +bench( pkg+'::initial_value:reduceRight', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn, 3 ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/uint32/benchmark/benchmark.reduce_right.length.js b/uint32/benchmark/benchmark.reduce_right.length.js new file mode 100644 index 00000000..fcba6798 --- /dev/null +++ b/uint32/benchmark/benchmark.reduce_right.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Updates an accumulated value. +* +* @private +* @param {*} acc - accumulated value +* @param {*} value - array element +* @returns {*} accumulated value +*/ +function fcn( acc, value ) { + return acc + value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reduceRight:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.reverse.js b/uint32/benchmark/benchmark.reverse.js new file mode 100644 index 00000000..49e486c3 --- /dev/null +++ b/uint32/benchmark/benchmark.reverse.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint32Array = require( '@stdlib/assert/is-uint32array' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reverse', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.reverse(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint32Array( out ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/benchmark/benchmark.reverse.length.js b/uint32/benchmark/benchmark.reverse.length.js new file mode 100644 index 00000000..bc78f719 --- /dev/null +++ b/uint32/benchmark/benchmark.reverse.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint32Array = require( '@stdlib/assert/is-uint32array' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.reverse(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint32Array( out ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reverse:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.set.js b/uint32/benchmark/benchmark.set.js new file mode 100644 index 00000000..fdcd920d --- /dev/null +++ b/uint32/benchmark/benchmark.set.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::array:set', function benchmark( b ) { + var values; + var buf; + var arr; + var N; + var v; + var i; + + values = []; + for ( i = 0; i < 10; i++ ) { + values.push( i ); + } + N = values.length; + + arr = new Uint32Array( 2 ); + buf = [ 0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = values[ i%N ]; + v = arr.set( buf ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array:set', function benchmark( b ) { + var values; + var buf; + var arr; + var N; + var v; + var i; + + values = new Uint32Array( 20 ); + N = values.length; + for ( i = 0; i < N; i++ ) { + values[ i ] = i; + } + + arr = new Uint32Array( 2 ); + buf = new Uint32Array( 1 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = values[ i%N ]; + v = arr.set( buf ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/benchmark/benchmark.set.length.js b/uint32/benchmark/benchmark.set.length.js new file mode 100644 index 00000000..8d28e826 --- /dev/null +++ b/uint32/benchmark/benchmark.set.length.js @@ -0,0 +1,114 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randi = require( '@stdlib/random/base/randi' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var values; + var arr1; + var arr2; + var arr; + var N; + var i; + + arr1 = []; + arr2 = []; + for ( i = 0; i < len; i++ ) { + arr1.push( randi() ); + arr2.push( randi() ); + } + arr = new Uint32Array( len ); + + values = [ + arr1, + arr2 + ]; + N = values.length; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr.set( values[ i%N ] ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':set:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.slice.js b/uint32/benchmark/benchmark.slice.js new file mode 100644 index 00000000..00e73452 --- /dev/null +++ b/uint32/benchmark/benchmark.slice.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint32Array = require( '@stdlib/assert/is-uint32array' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':slice', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.slice(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint32Array( out ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/benchmark/benchmark.slice.length.js b/uint32/benchmark/benchmark.slice.length.js new file mode 100644 index 00000000..e46ac89f --- /dev/null +++ b/uint32/benchmark/benchmark.slice.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint32Array = require( '@stdlib/assert/is-uint32array' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.slice(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint32Array( out ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':slice:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.some.js b/uint32/benchmark/benchmark.some.js new file mode 100644 index 00000000..3abaeec2 --- /dev/null +++ b/uint32/benchmark/benchmark.some.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':some', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:some', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate, {} ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/uint32/benchmark/benchmark.some.length.js b/uint32/benchmark/benchmark.some.length.js new file mode 100644 index 00000000..8b8b2a53 --- /dev/null +++ b/uint32/benchmark/benchmark.some.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':some:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.sort.js b/uint32/benchmark/benchmark.sort.js new file mode 100644 index 00000000..dd4f6a24 --- /dev/null +++ b/uint32/benchmark/benchmark.sort.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var randi = require( '@stdlib/random/base/randi' ); +var isUint32Array = require( '@stdlib/assert/is-uint32array' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':sort', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint32Array( [ randi(), randi() ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = randi(); + out = arr.sort(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint32Array( out ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/benchmark/benchmark.sort.length.js b/uint32/benchmark/benchmark.sort.length.js new file mode 100644 index 00000000..c40b6ec9 --- /dev/null +++ b/uint32/benchmark/benchmark.sort.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randi = require( '@stdlib/random/base/randi' ); +var isUint32Array = require( '@stdlib/assert/is-uint32array' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var data; + var arr; + var i; + + data = []; + for ( i = 0; i < len; i++ ) { + data.push( randi() ); + } + arr = new Uint32Array( data ); + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ i%len ] = randi(); + out = arr.sort(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint32Array( out ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':sort:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.subarray.js b/uint32/benchmark/benchmark.subarray.js new file mode 100644 index 00000000..5014eb4d --- /dev/null +++ b/uint32/benchmark/benchmark.subarray.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint32Array = require( '@stdlib/assert/is-uint32array' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':subarray', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.subarray(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint32Array( out ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/benchmark/benchmark.subarray.length.js b/uint32/benchmark/benchmark.subarray.length.js new file mode 100644 index 00000000..1bca9ab4 --- /dev/null +++ b/uint32/benchmark/benchmark.subarray.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint32Array = require( '@stdlib/assert/is-uint32array' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.subarray(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint32Array( out ) ) { + b.fail( 'should return a Uint32Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':subarray:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.to_locale_string.js b/uint32/benchmark/benchmark.to_locale_string.js new file mode 100644 index 00000000..e947d2ad --- /dev/null +++ b/uint32/benchmark/benchmark.to_locale_string.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':toLocaleString', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toLocaleString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/benchmark/benchmark.to_locale_string.length.js b/uint32/benchmark/benchmark.to_locale_string.length.js new file mode 100644 index 00000000..a4da2c18 --- /dev/null +++ b/uint32/benchmark/benchmark.to_locale_string.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toLocaleString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':toLocaleString:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.to_string.js b/uint32/benchmark/benchmark.to_string.js new file mode 100644 index 00000000..78c524a4 --- /dev/null +++ b/uint32/benchmark/benchmark.to_string.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':toString', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/benchmark/benchmark.to_string.length.js b/uint32/benchmark/benchmark.to_string.length.js new file mode 100644 index 00000000..af13a8cc --- /dev/null +++ b/uint32/benchmark/benchmark.to_string.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint32Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':toString:len='+len, f ); + } +} + +main(); diff --git a/uint32/benchmark/benchmark.values.js b/uint32/benchmark/benchmark.values.js new file mode 100644 index 00000000..3854804a --- /dev/null +++ b/uint32/benchmark/benchmark.values.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint32Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':values', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.values(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint32/docs/repl.txt b/uint32/docs/repl.txt new file mode 100644 index 00000000..5547de00 --- /dev/null +++ b/uint32/docs/repl.txt @@ -0,0 +1,953 @@ + +{{alias}}() + A typed array constructor which returns a typed array representing an array + of 32-bit unsigned integers in the platform byte order. + + Returns + ------- + out: Uint32Array + A typed array. + + Examples + -------- + > var arr = new {{alias}}() + + + +{{alias}}( length ) + Returns a typed array having a specified length. + + Parameters + ---------- + length: integer + Typed array length. + + Returns + ------- + out: Uint32Array + A typed array. + + Examples + -------- + > var arr = new {{alias}}( 5 ) + [ 0, 0, 0, 0, 0 ] + + +{{alias}}( typedarray ) + Creates a typed array from another typed array. + + Parameters + ---------- + typedarray: TypedArray + Typed array from which to generate another typed array. + + Returns + ------- + out: Uint32Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias:@stdlib/array/int32}}( [ 5, 5, 5 ] ); + > var arr2 = new {{alias}}( arr1 ) + [ 5, 5, 5 ] + + +{{alias}}( obj ) + Creates a typed array from an array-like object or iterable. + + Parameters + ---------- + obj: Object + Array-like object or iterable from which to generate a typed array. + + Returns + ------- + out: Uint32Array + A typed array. + + Examples + -------- + > var arr1 = [ 5.0, 5.0, 5.0 ]; + > var arr2 = new {{alias}}( arr1 ) + [ 5, 5, 5 ] + + +{{alias}}( buffer[, byteOffset[, length]] ) + Returns a typed array view of an ArrayBuffer. + + Parameters + ---------- + buffer: ArrayBuffer + Underlying ArrayBuffer. + + byteOffset: integer (optional) + Integer byte offset specifying the location of the first typed array + element. Default: 0. + + length: integer (optional) + View length. If not provided, the view spans from the byteOffset to + the end of the underlying ArrayBuffer. + + Returns + ------- + out: Uint32Array + A typed array. + + Examples + -------- + > var buf = new {{alias:@stdlib/array/buffer}}( 16 ); + > var arr = new {{alias}}( buf, 0, 4 ) + [ 0, 0, 0, 0 ] + + +{{alias}}.from( src[, map[, thisArg]] ) + Creates a new typed array from an array-like object or an iterable. + + A callback is provided the following arguments: + + - value: source value. + - index: source index. + + Parameters + ---------- + src: ArrayLike|Iterable + Source of array elements. + + map: Function (optional) + Callback to invoke for each source element. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Uint32Array + A typed array. + + Examples + -------- + > function mapFcn( v ) { return v * 2; }; + > var arr = {{alias}}.from( [ 1, 2 ], mapFcn ) + [ 2, 4 ] + + +{{alias}}.of( element0[, element1[, ...elementN]] ) + Creates a new typed array from a variable number of arguments. + + Parameters + ---------- + element0: number + Array element. + + element1: number (optional) + Array element. + + elementN: number (optional) + Array elements. + + Returns + ------- + out: Uint32Array + A typed array. + + Examples + -------- + > var arr = {{alias}}.of( 1, 2 ) + [ 1, 2 ] + + +{{alias}}.BYTES_PER_ELEMENT + Number of bytes per view element. + + Examples + -------- + > {{alias}}.BYTES_PER_ELEMENT + 4 + + +{{alias}}.name + Typed array constructor name. + + Examples + -------- + > {{alias}}.name + 'Uint32Array' + + +{{alias}}.prototype.buffer + Read-only property which returns the ArrayBuffer referenced by the typed + array. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.buffer + + + +{{alias}}.prototype.byteLength + Read-only property which returns the length (in bytes) of the typed array. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.byteLength + 20 + + +{{alias}}.prototype.byteOffset + Read-only property which returns the offset (in bytes) of the typed array + from the start of its ArrayBuffer. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.byteOffset + 0 + + +{{alias}}.prototype.BYTES_PER_ELEMENT + Number of bytes per view element. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.BYTES_PER_ELEMENT + 4 + + +{{alias}}.prototype.length + Read-only property which returns the number of view elements. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.length + 5 + + +{{alias}}.prototype.copyWithin( target, start[, end] ) + Copies a sequence of elements within the array starting at `start` and + ending at `end` (non-inclusive) to the position starting at `target`. + + Parameters + ---------- + target: integer + Target start index position. + + start: integer + Source start index position. + + end: integer (optional) + Source end index position. Default: out.length. + + Returns + ------- + out: Uint32Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3, 4, 5 ] ); + > arr.copyWithin( 3, 0, 2 ); + > arr[ 3 ] + 1 + > arr[ 4 ] + 2 + + +{{alias}}.prototype.entries() + Returns an iterator for iterating over array key-value pairs. + + Returns + ------- + iter: Iterator + Iterator for iterating over array key-value pairs. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.entries(); + > it.next().value + [ 0, 1 ] + > it.next().value + [ 1, 2 ] + > it.next().done + true + + +{{alias}}.prototype.every( predicate[, thisArg] ) + Tests whether all array elements pass a test implemented by a predicate + function. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. If a predicate function + returns a truthy value, an array element passes; otherwise, an array + element fails. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + bool: boolean + Boolean indicating whether all array elements pass. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > function predicate( v ) { return ( v <= 1 ); }; + > arr.every( predicate ) + false + + +{{alias}}.prototype.fill( value[, start[, end]] ) + Fills an array from a start index to an end index (non-inclusive) with a + provided value. + + Parameters + ---------- + value: number + Fill value. + + start: integer (optional) + Start index. If less than zero, the start index is resolved relative to + the last array element. Default: 0. + + end: integer (optional) + End index (non-inclusive). If less than zero, the end index is resolved + relative to the last array element. Default: out.length. + + Returns + ------- + out: Uint32Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > arr.fill( 3 ); + > arr[ 0 ] + 3 + > arr[ 1 ] + 3 + + +{{alias}}.prototype.filter( predicate[, thisArg] ) + Creates a new array which includes those elements for which a predicate + function returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + The returned array has the same data type as the host array. + + If a predicate function does not return a truthy value for any array + element, the method returns `null`. + + Parameters + ---------- + predicate: Function + Predicate function which filters array elements. If a predicate function + returns a truthy value, an array element is included in the output + array; otherwise, an array element is not included in the output array. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Uint32Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 1 ); }; + > var arr2 = arr1.filter( predicate ); + > arr2.length + 2 + + +{{alias}}.prototype.find( predicate[, thisArg] ) + Returns the first array element for which a provided predicate function + returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + If a predicate function never returns a truthy value, the method returns + `undefined`. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + value: number|undefined + Array element. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 2 ); }; + > var v = arr.find( predicate ) + 3 + + +{{alias}}.prototype.findIndex( predicate[, thisArg] ) + Returns the index of the first array element for which a provided predicate + function returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + If a predicate function never returns a truthy value, the method returns + `-1`. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + idx: integer + Array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 2 ); }; + > var idx = arr.findIndex( predicate ) + 2 + + +{{alias}}.prototype.forEach( fcn[, thisArg] ) + Invokes a callback for each array element. + + A provided function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + fcn: Function + Function to invoke for each array element. + + thisArg: Any (optional) + Callback execution context. + + Examples + -------- + > var arr = new {{alias}}( [ 3, 2, 1 ] ); + > var str = ' '; + > function fcn( v, i ) { str += i + ':' + v + ' '; }; + > arr.forEach( fcn ); + > str + ' 0:3 1:2 2:1 ' + + +{{alias}}.prototype.includes( searchElement[, fromIndex] ) + Returns a boolean indicating whether an array includes a search element. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: 0. + + Returns + ------- + bool: boolean + Boolean indicating whether an array includes a search element. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > var bool = arr.includes( 4 ) + false + > bool = arr.includes( 3 ) + true + + +{{alias}}.prototype.indexOf( searchElement[, fromIndex] ) + Returns the index of the first array element strictly equal to a search + element. + + If unable to locate a search element, the method returns `-1`. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: 0. + + Returns + ------- + idx: integer + Array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > var idx = arr.indexOf( 4 ) + -1 + > idx = arr.indexOf( 3 ) + 2 + + +{{alias}}.prototype.join( [separator] ) + Serializes an array by joining all array elements as a string. + + Parameters + ---------- + separator: string (optional) + String delineating array elements. Default: ','. + + Returns + ------- + str: string + Array serialized as a string. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.join( '|' ) + '1|2|3' + + +{{alias}}.prototype.keys() + Returns an iterator for iterating over array keys. + + Returns + ------- + iter: Iterator + Iterator for iterating over array keys. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.keys(); + > it.next().value + 0 + > it.next().value + 1 + > it.next().done + true + + +{{alias}}.prototype.lastIndexOf( searchElement[, fromIndex] ) + Returns the index of the last array element strictly equal to a search + element. + + The method iterates from the last array element to the first array element. + + If unable to locate a search element, the method returns `-1`. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: -1. + + Returns + ------- + idx: integer + array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 0, 2, 0, 1 ] ); + > var idx = arr.lastIndexOf( 3 ) + -1 + > idx = arr.lastIndexOf( 0 ) + 3 + + +{{alias}}.prototype.map( fcn[, thisArg] ) + Maps each array element to an element in a new typed array. + + A provided function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + The returned array has the same data type as the host array. + + Parameters + ---------- + fcn: Function + Function which maps array elements to elements in the new array. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Uint32Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( v ) { return v * 2; }; + > var arr2 = arr1.map( fcn ); + [ 2, 4, 6 ] + + +{{alias}}.prototype.reduce( fcn[, initialValue] ) + Applies a function against an accumulator and each element in an array and + returns the accumulated result. + + The provided function is provided the following arguments: + + - acc: accumulated result. + - value: current array element. + - index: index of the current array element. + - arr: array on which the method is invoked. + + If provided an initial value, the method invokes a provided function with + the initial value as the first argument and the first array element as the + second argument. + + If not provided an initial value, the method invokes a provided function + with the first array element as the first argument and the second array + element as the second argument. + + Parameters + ---------- + fcn: Function + Function to apply. + + initialValue: Any (optional) + Initial accumulation value. + + Returns + ------- + out: Any + Accumulated result. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( acc, v ) { return acc + (v*v); }; + > var v = arr.reduce( fcn, 0 ) + 14 + + +{{alias}}.prototype.reduceRight( fcn[, initialValue] ) + Applies a function against an accumulator and each element in an array and + returns the accumulated result, iterating from right to left. + + The provided function is provided the following arguments: + + - acc: accumulated result. + - value: current array element. + - index: index of the current array element. + - arr: array on which the method is invoked. + + If provided an initial value, the method invokes a provided function with + the initial value as the first argument and the last array element as the + second argument. + + If not provided an initial value, the method invokes a provided function + with the last array element as the first argument and the second-to-last + array element as the second argument. + + Parameters + ---------- + fcn: Function + Function to apply. + + initialValue: Any (optional) + Initial accumulation value. + + Returns + ------- + out: Any + Accumulated result. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( acc, v ) { return acc + (v*v); }; + > var v = arr.reduceRight( fcn, 0 ) + 14 + + +{{alias}}.prototype.reverse() + Reverses an array *in-place*. + + This method mutates the array on which the method is invoked. + + Returns + ------- + out: Uint32Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ) + [ 1, 2, 3 ] + > arr.reverse() + [ 3, 2, 1 ] + + +{{alias}}.prototype.set( arr[, offset] ) + Sets array elements. + + Parameters + ---------- + arr: ArrayLike + Source array containing array values to set. + + offset: integer (optional) + Array index at which to start writing values. Default: 0. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.set( [ 4, 4 ], 1 ); + > arr[ 1 ] + 4 + > arr[ 2 ] + 4 + + +{{alias}}.prototype.slice( [begin[, end]] ) + Copies array elements to a new array with the same underlying data type as + the host array. + + If the method is unable to resolve indices to a non-empty array subsequence, + the method returns `null`. + + Parameters + ---------- + begin: integer (optional) + Start element index (inclusive). If less than zero, the start index is + resolved relative to the last array element. Default: 0. + + end: integer (optional) + End element index (exclusive). If less than zero, the end index is + resolved relative to the last array element. Default: arr.length. + + Returns + ------- + out: Uint32Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > var arr2 = arr1.slice( 1 ); + > arr2.length + 2 + > arr2[ 0 ] + 1 + > arr2[ 1 ] + 2 + + +{{alias}}.prototype.some( predicate[, thisArg] ) + Tests whether at least one array element passes a test implemented by a + predicate function. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. If a predicate function + returns a truthy value, a array element passes; otherwise, an array + element fails. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + bool: boolean + Boolean indicating whether at least one array element passes. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > function predicate( v ) { return ( v > 1 ); }; + > arr.some( predicate ) + true + + +{{alias}}.prototype.sort( [compareFunction] ) + Sorts an array *in-place*. + + The comparison function is provided two array elements per invocation: `a` + and `b`. + + The comparison function return value determines the sort order as follows: + + - If the comparison function returns a value less than zero, then the method + sorts `a` to an index lower than `b` (i.e., `a` should come *before* `b`). + + - If the comparison function returns a value greater than zero, then the + method sorts `a` to an index higher than `b` (i.e., `b` should come *before* + `a`). + + - If the comparison function returns zero, then the relative order of `a` + and `b` should remain unchanged. + + This method mutates the array on which the method is invoked. + + Parameters + ---------- + compareFunction: Function (optional) + Function which specifies the sort order. The default sort order is + ascending order. + + Returns + ------- + out: Uint32Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 0, 2, 1 ] ); + > arr.sort() + [ 0, 1, 1, 2, 2 ] + + +{{alias}}.prototype.subarray( [begin[, end]] ) + Creates a new typed array over the same underlying ArrayBuffer and with the + same underlying data type as the host array. + + If the method is unable to resolve indices to a non-empty array subsequence, + the method returns an empty typed array. + + Parameters + ---------- + begin: integer (optional) + Start element index (inclusive). If less than zero, the start index is + resolved relative to the last array element. Default: 0. + + end: integer (optional) + End element index (exclusive). If less than zero, the end index is + resolved relative to the last array element. Default: arr.length. + + Returns + ------- + out: Uint32Array + A new typed array view. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3, 4, 5 ] ); + > var arr2 = arr1.subarray( 2 ) + [ 3, 4, 5 ] + + +{{alias}}.prototype.toLocaleString( [locales[, options]] ) + Serializes an array as a locale-specific string. + + Parameters + ---------- + locales: string|Array (optional) + A BCP 47 language tag, or an array of such tags. + + options: Object (optional) + Options. + + Returns + ------- + str: string + A typed array string representation. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.toLocaleString() + '1,2,3' + + +{{alias}}.prototype.toString() + Serializes an array as a string. + + Returns + ------- + str: string + A typed array string representation. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.toString() + '1,2,3' + + +{{alias}}.prototype.values() + Returns an iterator for iterating over array elements. + + Returns + ------- + iter: Iterator + Iterator for iterating over array elements. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.values(); + > it.next().value + 1 + > it.next().value + 2 + > it.next().done + true + + + See Also + -------- + diff --git a/uint32/docs/types/index.d.ts b/uint32/docs/types/index.d.ts new file mode 100644 index 00000000..63d82951 --- /dev/null +++ b/uint32/docs/types/index.d.ts @@ -0,0 +1,26 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +// EXPORTS // + +/** +* Typed array constructor which returns a typed array representing an array of 32-bit unsigned integers in the platform byte order. +*/ +export = Uint32Array; diff --git a/uint32/docs/types/test.ts b/uint32/docs/types/test.ts new file mode 100644 index 00000000..7304e8f5 --- /dev/null +++ b/uint32/docs/types/test.ts @@ -0,0 +1,37 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// tslint:disable: no-construct +// tslint:disable: no-unused-expression + +import Uint32Array = require( './index' ); + + +// TESTS // + +// The function returns a typed array instance... +{ + new Uint32Array( 10 ); // $ExpectType Uint32Array + new Uint32Array( [ 2, 5, 5, 7 ] ); // $ExpectType Uint32Array +} + +// The constructor function has to be invoked with `new`... +{ + Uint32Array( 10 ); // $ExpectError + Uint32Array( [ 2, 5, 5, 7 ] ); // $ExpectError +} diff --git a/uint32/examples/index.js b/uint32/examples/index.js new file mode 100644 index 00000000..d0978bec --- /dev/null +++ b/uint32/examples/index.js @@ -0,0 +1,32 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var randu = require( '@stdlib/random/base/randu' ); +var round = require( '@stdlib/math/base/special/round' ); +var ctor = require( './../lib' ); + +var arr; +var i; + +arr = new ctor( 10 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = round( randu()*100.0 ); +} +console.log( arr ); diff --git a/uint32/lib/index.js b/uint32/lib/index.js new file mode 100644 index 00000000..de13a292 --- /dev/null +++ b/uint32/lib/index.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Typed array constructor which returns a typed array representing an array of 32-bit unsigned integers in the platform byte order. +* +* @module @stdlib/array/uint32 +* +* @example +* var ctor = require( '@stdlib/array/uint32' ); +* +* var arr = new ctor( 10 ); +* // returns +*/ + +// MODULES // + +var hasUint32ArraySupport = require( '@stdlib/assert/has-uint32array-support' ); +var builtin = require( './uint32array.js' ); +var polyfill = require( './polyfill.js' ); + + +// MAIN // + +var ctor; +if ( hasUint32ArraySupport() ) { + ctor = builtin; +} else { + ctor = polyfill; +} + + +// EXPORTS // + +module.exports = ctor; diff --git a/uint32/lib/polyfill.js b/uint32/lib/polyfill.js new file mode 100644 index 00000000..c20fe2ed --- /dev/null +++ b/uint32/lib/polyfill.js @@ -0,0 +1,37 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// TODO: write polyfill + +// MAIN // + +/** +* Typed array which represents an array of 32-bit unsigned integers in the platform byte order. +* +* @throws {Error} not implemented +*/ +function polyfill() { + throw new Error( 'not implemented' ); +} + + +// EXPORTS // + +module.exports = polyfill; diff --git a/uint32/lib/uint32array.js b/uint32/lib/uint32array.js new file mode 100644 index 00000000..9ac4e62c --- /dev/null +++ b/uint32/lib/uint32array.js @@ -0,0 +1,28 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MAIN // + +var ctor = ( typeof Uint32Array === 'function' ) ? Uint32Array : void 0; // eslint-disable-line stdlib/require-globals + + +// EXPORTS // + +module.exports = ctor; diff --git a/uint32/package.json b/uint32/package.json new file mode 100644 index 00000000..c306da1d --- /dev/null +++ b/uint32/package.json @@ -0,0 +1,70 @@ +{ + "name": "@stdlib/array/uint32", + "version": "0.0.0", + "description": "Uint32Array.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structure", + "array", + "typed", + "typed array", + "typed-array", + "uint32array", + "uint32", + "uint32_t", + "integer", + "int", + "uint", + "unsigned", + "long" + ] +} diff --git a/uint32/test/test.copy_within.js b/uint32/test/test.copy_within.js new file mode 100644 index 00000000..a02b4a21 --- /dev/null +++ b/uint32/test/test.copy_within.js @@ -0,0 +1,320 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var hasProp = require( '@stdlib/assert/has-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var Uint32Array = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof Uint32Array, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'a typed array instance has a `copyWithin` method for copying a sequence of elements within a typed array', function test( t ) { + var arr = new Uint32Array( 2 ); + t.strictEqual( hasProp( arr, 'copyWithin' ), true, 'has property' ); + t.strictEqual( isFunction( arr.copyWithin ), true, 'has method' ); + t.end(); +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a typed array instance', function test( t ) { + var values; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0 ); + }; + } +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a typed array instance (end)', function test( t ) { + var values; + var arr; + var i; + + arr = new Uint32Array( 2 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0, 5 ); + }; + } +}); + +tape( 'the method copies a sequence of elements within a typed array', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint32Array( arr ); + p.copyWithin( 0, 3 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative target)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint32Array( arr ); + p.copyWithin( -p.length, 3 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative start)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint32Array( arr ); + p.copyWithin( 0, -2 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (end=length)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint32Array( arr ); + p.copyWithin( 0, 3, p.length ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (non-inclusive end)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint32Array( arr ); + p.copyWithin( 2, 0, 2 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative end)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint32Array( arr ); + p.copyWithin( 2, 0, -3 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (target >= length)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint32Array( arr ); + p.copyWithin( p.length, 3 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (target > start)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint32Array( arr ); + p.copyWithin( 2, 0 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + t.strictEqual( p[ 4 ], 2, 'returns expected value' ); + + t.end(); +}); diff --git a/uint32/test/test.js b/uint32/test/test.js new file mode 100644 index 00000000..d21c059b --- /dev/null +++ b/uint32/test/test.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var hasUint32ArraySupport = require( '@stdlib/assert/has-uint32array-support' ); +var polyfill = require( './../lib/polyfill.js' ); +var ctor = require( './../lib' ); + + +// VARIABLES // + +var hasUint32Arrays = hasUint32ArraySupport(); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'if an environment supports `Uint32Array`, the export is an alias for `Uint32Array`', function test( t ) { + var Foo; + + Foo = proxyquire( './../lib', { + '@stdlib/assert/has-uint32array-support': isTrue, + './uint32array.js': Mock + }); + t.strictEqual( Foo, Mock, 'returns builtin' ); + + if ( hasUint32Arrays ) { + t.strictEqual( ctor, Uint32Array, 'is alias' ); // eslint-disable-line stdlib/require-globals + } + + t.end(); + + function Mock() { + return this; + } + + function isTrue() { + return true; + } +}); + +tape( 'if an environment does not support `Uint32Array`, the export is a polyfill', function test( t ) { + var Foo; + + Foo = proxyquire( './../lib', { + '@stdlib/assert/has-uint32array-support': isFalse + }); + + t.strictEqual( Foo, polyfill, 'returns polyfill' ); + t.end(); + + function isFalse() { + return false; + } +}); diff --git a/uint32/test/test.polyfill.js b/uint32/test/test.polyfill.js new file mode 100644 index 00000000..9d6fcb19 --- /dev/null +++ b/uint32/test/test.polyfill.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var ctor = require( './../lib/polyfill.js' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error when invoked', function test( t ) { + t.throws( foo, Error, 'throws an error' ); + t.end(); + + function foo() { + var f = new ctor(); // eslint-disable-line no-unused-vars + } +}); + +// TODO: tests diff --git a/uint8/README.md b/uint8/README.md new file mode 100644 index 00000000..f7c40a9c --- /dev/null +++ b/uint8/README.md @@ -0,0 +1,1431 @@ + + +# Uint8Array + +> [Typed array][mdn-typed-array] constructor which returns a [typed array][mdn-typed-array] representing an array of 8-bit unsigned integers in the platform byte order. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var Uint8Array = require( '@stdlib/array/uint8' ); +``` + +#### Uint8Array() + +A [typed array][mdn-typed-array] constructor which returns a [typed array][mdn-typed-array] representing an array of 8-bit unsigned integers in the platform byte order. + + + +```javascript +var arr = new Uint8Array(); +// returns +``` + +#### Uint8Array( length ) + +Returns a [typed array][mdn-typed-array] having a specified length. + + + +```javascript +var arr = new Uint8Array( 5 ); +// returns [ 0, 0, 0, 0, 0 ] +``` + +#### Uint8Array( typedarray ) + +Creates a [typed array][mdn-typed-array] from another [typed array][mdn-typed-array]. + + + +```javascript +var Float32Array = require( '@stdlib/array/float32' ); + +var arr1 = new Float32Array( [ 5.0, 5.0, 5.0 ] ); +var arr2 = new Uint8Array( arr1 ); +// returns [ 5, 5, 5 ] +``` + +#### Uint8Array( obj ) + +Creates a [typed array][mdn-typed-array] from an array-like `object` or iterable. + + + +```javascript +var arr = new Uint8Array( [ 5.0, 5.0, 5.0 ] ); +// returns [ 5, 5, 5 ] +``` + +#### Uint8Array( buffer\[, byteOffset\[, length]] ) + +Returns a [typed array][mdn-typed-array] view of an [`ArrayBuffer`][@stdlib/array/buffer]. + + + +```javascript +var ArrayBuffer = require( '@stdlib/array/buffer' ); + +var buf = new ArrayBuffer( 4 ); +var arr = new Uint8Array( buf, 0, 4 ); +// returns [ 0, 0, 0, 0 ] +``` + +* * * + +### Properties + + + +#### Uint8Array.BYTES_PER_ELEMENT + +Number of bytes per view element. + + + +```javascript +var nbytes = Uint8Array.BYTES_PER_ELEMENT; +// returns 1 +``` + + + +#### Uint8Array.name + +[Typed array][mdn-typed-array] constructor name. + + + +```javascript +var str = Uint8Array.name; +// returns 'Uint8Array' +``` + + + +#### Uint8Array.prototype.buffer + +**Read-only** property which returns the [`ArrayBuffer`][@stdlib/array/buffer] referenced by the [typed array][mdn-typed-array]. + + + +```javascript +var arr = new Uint8Array( 5 ); +var buf = arr.buffer; +// returns +``` + + + +#### Uint8Array.prototype.byteLength + +**Read-only** property which returns the length (in bytes) of the [typed array][mdn-typed-array]. + + + +```javascript +var arr = new Uint8Array( 5 ); +var byteLength = arr.byteLength; +// returns 5 +``` + + + +#### Uint8Array.prototype.byteOffset + +**Read-only** property which returns the offset (in bytes) of the [typed array][mdn-typed-array] from the start of its [`ArrayBuffer`][@stdlib/array/buffer]. + + + +```javascript +var arr = new Uint8Array( 5 ); +var byteOffset = arr.byteOffset; +// returns 0 +``` + + + +#### Uint8Array.prototype.BYTES_PER_ELEMENT + +Number of bytes per view element. + + + +```javascript +var arr = new Uint8Array( 5 ); +var nbytes = arr.BYTES_PER_ELEMENT; +// returns 1 +``` + + + +#### Uint8Array.prototype.length + +**Read-only** property which returns the number of view elements. + + + +```javascript +var arr = new Uint8Array( 5 ); +var len = arr.length; +// returns 5 +``` + +* * * + +### Methods + + + +#### Uint8Array.from( src\[, map\[, thisArg]] ) + +Creates a new typed array from an array-like `object` or an iterable. + +```javascript +var arr = Uint8Array.from( [ 1, 2 ] ); +// returns [ 1, 2 ] +``` + +To invoke a function for each `src` value, provide a callback function. + +```javascript +function mapFcn( v ) { + return v * 2; +} + +var arr = Uint8Array.from( [ 1, 2 ], mapFcn ); +// returns [ 2, 4 ] +``` + +A callback function is provided two arguments: + +- `value`: source value +- `index`: source index + +To set the callback execution context, provide a `thisArg`. + +```javascript +function mapFcn( v ) { + this.count += 1; + return v * 2; +} + +var ctx = { + 'count': 0 +}; + +var arr = Uint8Array.from( [ 1, 2 ], mapFcn, ctx ); +// returns [ 2, 4 ] + +var n = ctx.count; +// returns 2 +``` + + + +#### Uint8Array.of( element0\[, element1\[, ...elementN]] ) + +Creates a new typed array from a variable number of arguments. + +```javascript +var arr = Uint8Array.of( 1, 2 ); +// returns [ 1, 2 ] +``` + + + +#### Uint8Array.prototype.copyWithin( target, start\[, end] ) + +Copies a sequence of elements within an array starting at `start` and ending at `end` (non-inclusive) to the position starting at `target`. + + + +```javascript +var arr = new Uint8Array( [ 1, 2, 3, 4, 5 ] ); + +// Copy the last two elements to the first two elements: +arr.copyWithin( 0, 3 ); + +var v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 5 +``` + +By default, `end` equals the number of array elements (i.e., one more than the last array index). To limit the sequence length, provide an `end` argument. + + + +```javascript +var arr = new Uint8Array( [ 1, 2, 3, 4, 5 ] ); + +// Copy the first two elements to the last two elements: +arr.copyWithin( 3, 0, 2 ); + +var v = arr[ 3 ]; +// returns 1 + +v = arr[ 4 ]; +// returns 2 +``` + +When a `target`, `start`, and/or `end` index is negative, the respective index is determined relative to the last array element. The following example achieves the same behavior as the previous example: + + + +```javascript +var arr = new Uint8Array( [ 1, 2, 3, 4, 5 ] ); + +// Copy the first two elements to the last two elements: +arr.copyWithin( -2, -5, -3 ); + +var v = arr[ 3 ]; +// returns 1 + +v = arr[ 4 ]; +// returns 2 +``` + + + +#### Uint8Array.prototype.entries() + +Returns an iterator for iterating over array key-value pairs. + + + +```javascript +var arr = new Uint8Array( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.entries(); + +// Iterate over key-value pairs... +var v = it.next().value; +// returns [ 0, 1 ] + +v = it.next().value; +// returns [ 1, 2 ] + +var bool = it.next().done; +// returns true +``` + + + +#### Uint8Array.prototype.every( predicate\[, thisArg] ) + +Tests whether all array elements pass a test implemented by a `predicate` function. + + + +```javascript +function predicate( v ) { + return ( v <= 1 ); +} + +var arr = new Uint8Array( [ 1, 2 ] ); + +var bool = arr.every( predicate ); +// returns false +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 1 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint8Array( [ 1, 2 ] ); + +var bool = arr.every( predicate, ctx ); +// returns true + +var n = ctx.count; +// returns 2 +``` + + + +#### Uint8Array.prototype.fill( value\[, start\[, end]] ) + +Fills an array from a `start` index to an `end` index (non-inclusive) with a provided `value`. + + + +```javascript +var arr = new Uint8Array( 2 ); + +// Set all array elements to the same value: +arr.fill( 2 ); + +var v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 2 + +// Set all array elements starting from the first index to the same value: +arr.fill( 3, 1 ); + +v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 3 + +// Set all array elements, except the last element, to the same value: +arr.fill( 4, 0, arr.length-1 ); + +v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 3 +``` + +When a `start` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr = new Uint8Array( 2 ); + +// Set all array elements, except the last element, to the same value: +arr.fill( 2, -arr.length, -1 ); + +var v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 0 +``` + + + +#### Uint8Array.prototype.filter( predicate\[, thisArg] ) + +Creates a new array (of the same data type as the host array) which includes those elements for which a `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v >= 2 ); +} + +var arr1 = new Uint8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate ); +// returns [ 2, 3 ] +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns an empty array. + + + +```javascript +function predicate( v ) { + return ( v >= 10 ); +} + +var arr1 = new Uint8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate ); +// returns [] +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr1 = new Uint8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint8Array.prototype.find( predicate\[, thisArg] ) + +Returns the first array element for which a provided `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v > 2 ); +} + +var arr = new Uint8Array( [ 1, 2, 3 ] ); + +var v = arr.find( predicate ); +// returns 3 +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns `undefined`. + + + +```javascript +function predicate( v ) { + return ( v < 1 ); +} + +var arr = new Uint8Array( [ 1, 2, 3 ] ); + +var v = arr.find( predicate ); +// returns undefined +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v > 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint8Array( [ 1, 2, 3 ] ); + +var v = arr.find( predicate, ctx ); +// returns 3 + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint8Array.prototype.findIndex( predicate\[, thisArg] ) + +Returns the index of the first array element for which a provided `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v >= 3 ); +} + +var arr = new Uint8Array( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate ); +// returns 2 +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns `-1`. + + + +```javascript +function predicate( v ) { + return ( v < 1 ); +} + +var arr = new Uint8Array( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate ); +// returns -1 +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 3 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint8Array( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate, ctx ); +// returns 2 + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint8Array.prototype.forEach( fcn\[, thisArg] ) + +Invokes a callback for each array element. + + + +```javascript +var arr = new Uint8Array( [ 1, 2, 3 ] ); + +var str = ''; + +function fcn( v, i ) { + str += i + ':' + v; + if ( i < arr.length-1 ) { + str += ' '; + } +} + +arr.forEach( fcn ); + +console.log( str ); +// => '0:1 1:2 2:3' +``` + +The callback is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function fcn() { + this.count += 1; +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint8Array( [ 1, 2, 3 ] ); + +arr.forEach( fcn, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint8Array.prototype.includes( searchElement\[, fromIndex] ) + +Returns a `boolean` indicating whether an array includes a search element. + + + +```javascript +var arr = new Uint8Array( [ 1, 2, 3 ] ); + +var bool = arr.includes( 3 ); +// returns true + +bool = arr.includes( 0 ); +// returns false +``` + +By default, the method searches the entire array (`fromIndex = 0`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Uint8Array( [ 1, 2, 3 ] ); + +var bool = arr.includes( 1, 1 ); +// returns false +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Uint8Array( [ 1, 2, 3 ] ); + +bool = arr.includes( 1, -2 ); +// returns false +``` + + + +#### Uint8Array.prototype.indexOf( searchElement\[, fromIndex] ) + +Returns the index of the first array element strictly equal to a search element. + + + +```javascript +var arr = new Uint8Array( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 3 ); +// returns 2 + +idx = arr.indexOf( 0 ); +// returns -1 +``` + +By default, the method searches the entire array (`fromIndex = 0`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Uint8Array( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 1, 1 ); +// returns -1 +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Uint8Array( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 1, -2 ); +// returns -1 +``` + + + +#### Uint8Array.prototype.join( \[separator] ) + +Serializes an array by joining all array elements as a string. + + + +```javascript +var arr = new Uint8Array( [ 1, 2, 3 ] ); + +var str = arr.join(); +// returns '1,2,3' +``` + +By default, the method delineates array elements using a comma `,`. To specify a custom separator, provide a `separator` string. + + + +```javascript +var arr = new Uint8Array( [ 1, 2, 3 ] ); + +var str = arr.join( '|' ); +// returns '1|2|3' +``` + + + +#### Uint8Array.prototype.keys() + +Returns an iterator for iterating over array keys. + + + +```javascript +var arr = new Uint8Array( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.keys(); + +// Iterate over keys... +var v = it.next().value; +// returns 0 + +v = it.next().value; +// returns 1 + +var bool = it.next().done; +// returns true +``` + + + +#### Uint8Array.prototype.lastIndexOf( searchElement\[, fromIndex] ) + +Returns the index of the last array element strictly equal to a search element, iterating from right to left. + + + +```javascript +var arr = new Uint8Array( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0 ); +// returns 3 + +idx = arr.lastIndexOf( 3 ); +// returns -1 +``` + +By default, the method searches the entire array (`fromIndex = -1`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Uint8Array( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0, 2 ); +// returns 1 +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Uint8Array( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0, -3 ); +// returns 1 +``` + + + +#### Uint8Array.prototype.map( fcn\[, thisArg] ) + +Maps each array element to an element in a new array having the same data type as the host array. + + + +```javascript +function fcn( v ) { + return v * 2; +} + +var arr1 = new Uint8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.map( fcn ); +// returns [ 2, 4, 6 ] +``` + +A callback is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function fcn( v ) { + this.count += 1; + return v * 2; +} + +var ctx = { + 'count': 0 +}; + +var arr1 = new Uint8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.map( fcn, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint8Array.prototype.reduce( fcn\[, initialValue] ) + +Applies a function against an accumulator and each element in an array and returns the accumulated result. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Uint8Array( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn ); +// returns 12 +``` + +If not provided an initial value, the method invokes a provided function with the first array element as the first argument and the second array element as the second argument. + +If provided an initial value, the method invokes a provided function with the initial value as the first argument and the first array element as the second argument. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Uint8Array( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn, 0 ); +// returns 14 +``` + +A callback is provided four arguments: + +- `acc`: accumulated result +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + + + +#### Uint8Array.prototype.reduceRight( fcn\[, initialValue] ) + +Applies a function against an accumulator and each element in an array and returns the accumulated result, iterating from right to left. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Uint8Array( [ 2, 1, 3 ] ); + +var v = arr.reduceRight( fcn ); +// returns 8 +``` + +If not provided an initial value, the method invokes a provided function with the last array element as the first argument and the second-to-last array element as the second argument. + +If provided an initial value, the method invokes a provided function with the initial value as the first argument and the last array element as the second argument. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Uint8Array( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn, 0 ); +// returns 14 +``` + +A callback is provided four arguments: + +- `acc`: accumulated result +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + + + +#### Uint8Array.prototype.reverse() + +Reverses an array **in-place** (thus mutating the array on which the method is invoked). + + + +```javascript +var arr = new Uint8Array( [ 2, 0, 3 ] ); + +// Reverse the array: +arr.reverse(); + +var v = arr[ 0 ]; +// returns 3 + +v = arr[ 1 ]; +// returns 0 + +v = arr[ 2 ]; +// returns 2 +``` + + + +#### Uint8Array.prototype.set( arr\[, offset] ) + +Sets array elements. + + + +```javascript +var arr = new Uint8Array( [ 1, 2, 3 ] ); +// returns [ 1, 2, 3 ] + +// Set the first two array elements: +arr.set( [ 4, 5 ] ); + +var v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 5 +``` + +By default, the method starts writing values at the first array index. To specify an alternative index, provide an index `offset`. + + + +```javascript +var arr = new Uint8Array( [ 1, 2, 3 ] ); +// returns [ 1, 2, 3 ] + +// Set the last two array elements: +arr.set( [ 4, 5 ], 1 ); + +var v = arr[ 1 ]; +// returns 4 + +v = arr[ 2 ]; +// returns 5 +``` + + + +#### Uint8Array.prototype.slice( \[begin\[, end]] ) + +Copies array elements to a new array with the same underlying data type as the host array. + + + +```javascript +var arr1 = new Uint8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice(); + +var bool = ( arr1 === arr2 ); +// returns false + +bool = ( arr1.buffer === arr2.buffer ); +// returns false + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 + +v = arr2[ 2 ]; +// returns 3 +``` + +By default, the method copies elements beginning with the first array element. To specify an alternative array index at which to begin copying, provide a `begin` index (inclusive). + + + +```javascript +var arr1 = new Uint8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( 1 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 2 + +v = arr2[ 1 ]; +// returns 3 +``` + +By default, the method copies all array elements after `begin`. To specify an alternative array index at which to end copying, provide an `end` index (exclusive). + + + +```javascript +var arr1 = new Uint8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( 0, 2 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 +``` + +When a `begin` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr1 = new Uint8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( -arr1.length, -1 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 +``` + + + +#### Uint8Array.prototype.some( predicate\[, thisArg] ) + +Tests whether at least one array element passes a test implemented by a `predicate` function. + + + +```javascript +function predicate( v ) { + return ( v >= 2 ); +} + +var arr = new Uint8Array( [ 1, 2 ] ); + +var bool = arr.some( predicate ); +// returns true +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint8Array( [ 1, 1 ] ); + +var bool = arr.some( predicate, ctx ); +// returns false + +var n = ctx.count; +// returns 2 +``` + + + +#### Uint8Array.prototype.sort( \[compareFunction] ) + +Sorts an array **in-place** (thus mutating the array on which the method is invoked). + + + +```javascript +var arr = new Uint8Array( [ 2, 3, 0 ] ); + +// Sort the array (in ascending order): +arr.sort(); + +var v = arr[ 0 ]; +// returns 0 + +v = arr[ 1 ]; +// returns 2 + +v = arr[ 2 ]; +// returns 3 +``` + +By default, the method sorts array elements in ascending order. To impose a custom order, provide a `compareFunction`. + + + +```javascript +function descending( a, b ) { + return b - a; +} + +var arr = new Uint8Array( [ 2, 3, 0 ] ); + +// Sort the array (in descending order): +arr.sort( descending ); + +var v = arr[ 0 ]; +// returns 3 + +v = arr[ 1 ]; +// returns 2 + +v = arr[ 2 ]; +// returns 0 +``` + +The comparison function is provided two array elements, `a` and `b`, per invocation, and its return value determines the sort order as follows: + +- If the comparison function returns a value **less** than zero, then the method sorts `a` to an index lower than `b` (i.e., `a` should come **before** `b`). +- If the comparison function returns a value **greater** than zero, then the method sorts `a` to an index higher than `b` (i.e., `b` should come **before** `a`). +- If the comparison function returns **zero**, then the relative order of `a` and `b` _should_ remain unchanged. + + + +#### Uint8Array.prototype.subarray( \[begin\[, end]] ) + +Creates a new typed array view over the same underlying [`ArrayBuffer`][@stdlib/array/buffer] and with the same underlying data type as the host array. + + + +```javascript +var arr1 = new Uint8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray(); +// returns [ 1, 2, 3 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +By default, the method creates a typed array view beginning with the first array element. To specify an alternative array index at which to begin, provide a `begin` index (inclusive). + + + +```javascript +var arr1 = new Uint8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 1 ); +// returns [ 2, 3 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +By default, the method creates a typed array view which includes all array elements after `begin`. To limit the number of array elements after `begin`, provide an `end` index (exclusive). + + + +```javascript +var arr1 = new Uint8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 0, 2 ); +// returns [ 1, 2 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +When a `begin` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr1 = new Uint8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( -arr1.length, -1 ); +// returns [ 1, 2 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +If the method is unable to resolve indices to a non-empty array subsequence, the method returns an empty typed array. + + + +```javascript +var arr1 = new Uint8Array( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 10, -1 ); +// returns [] +``` + + + +#### Uint8Array.prototype.toLocaleString( \[locales\[, options]] ) + +Serializes an array as a locale-specific `string`. + + + +```javascript +var arr = new Uint8Array( [ 1, 2, 3 ] ); + +var str = arr.toLocaleString(); +// returns '1,2,3' +``` + + + +#### Uint8Array.prototype.toString() + +Serializes an array as a `string`. + + + +```javascript +var arr = new Uint8Array( [ 1, 2, 3 ] ); + +var str = arr.toString(); +// returns '1,2,3' +``` + + + +#### Uint8Array.prototype.values() + +Returns an iterator for iterating over array elements. + + + +```javascript +var arr = new Uint8Array( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.values(); + +// Iterate over array elements... +var v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 2 + +var bool = it.next().done; +// returns true +``` + +
+ + + +* * * + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var randu = require( '@stdlib/random/base/randu' ); +var round = require( '@stdlib/math/base/special/round' ); +var ctor = require( '@stdlib/array/uint8' ); + +var arr; +var i; + +arr = new ctor( 10 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = round( randu()*100.0 ); +} +console.log( arr ); +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/uint8/benchmark/benchmark.copy_within.js b/uint8/benchmark/benchmark.copy_within.js new file mode 100644 index 00000000..fd94b254 --- /dev/null +++ b/uint8/benchmark/benchmark.copy_within.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':copyWithin', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr[ 0 ] = v; + arr = arr.copyWithin( 1, 0 ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/benchmark/benchmark.copy_within.length.js b/uint8/benchmark/benchmark.copy_within.length.js new file mode 100644 index 00000000..7dd8aae0 --- /dev/null +++ b/uint8/benchmark/benchmark.copy_within.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr[ 0 ] = v; + arr = arr.copyWithin( 1, 0 ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':copyWithin:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.data.js b/uint8/benchmark/benchmark.data.js new file mode 100644 index 00000000..c494b681 --- /dev/null +++ b/uint8/benchmark/benchmark.data.js @@ -0,0 +1,75 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::get,index', function benchmark( b ) { + var arr; + var N; + var v; + var i; + + arr = new Uint8Array( 2 ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr[ i%N ]; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::set,index', function benchmark( b ) { + var arr; + var N; + var i; + + arr = new Uint8Array( 2 ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ i%N ] = i; + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] || arr[ 1 ] !== arr[ 1 ] ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/benchmark/benchmark.entries.js b/uint8/benchmark/benchmark.entries.js new file mode 100644 index 00000000..fefbd578 --- /dev/null +++ b/uint8/benchmark/benchmark.entries.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':entries', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Uint8Array( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.entries(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/benchmark/benchmark.every.js b/uint8/benchmark/benchmark.every.js new file mode 100644 index 00000000..d22cc45d --- /dev/null +++ b/uint8/benchmark/benchmark.every.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':every', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); + +bench( pkg+'::this_context:every', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate, {} ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); diff --git a/uint8/benchmark/benchmark.every.length.js b/uint8/benchmark/benchmark.every.length.js new file mode 100644 index 00000000..f89c9abb --- /dev/null +++ b/uint8/benchmark/benchmark.every.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value >= 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':every:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.fill.js b/uint8/benchmark/benchmark.fill.js new file mode 100644 index 00000000..ba36b131 --- /dev/null +++ b/uint8/benchmark/benchmark.fill.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':fill', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr = arr.fill( v ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/benchmark/benchmark.fill.length.js b/uint8/benchmark/benchmark.fill.length.js new file mode 100644 index 00000000..010fbc57 --- /dev/null +++ b/uint8/benchmark/benchmark.fill.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr = arr.fill( v ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':fill:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.filter.js b/uint8/benchmark/benchmark.filter.js new file mode 100644 index 00000000..1dae0041 --- /dev/null +++ b/uint8/benchmark/benchmark.filter.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint8Array = require( '@stdlib/assert/is-uint8array' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':filter', function benchmark( b ) { + var arr; + var out; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8Array( out ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); + +bench( pkg+'::this_context:filter', function benchmark( b ) { + var arr; + var out; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate, {} ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8Array( out ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); diff --git a/uint8/benchmark/benchmark.filter.length.js b/uint8/benchmark/benchmark.filter.length.js new file mode 100644 index 00000000..37014c67 --- /dev/null +++ b/uint8/benchmark/benchmark.filter.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint8Array = require( '@stdlib/assert/is-uint8array' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value >= 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8Array( out ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':filter:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.find.js b/uint8/benchmark/benchmark.find.js new file mode 100644 index 00000000..5327e0eb --- /dev/null +++ b/uint8/benchmark/benchmark.find.js @@ -0,0 +1,82 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':find', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:find', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate, {} ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/uint8/benchmark/benchmark.find.length.js b/uint8/benchmark/benchmark.find.length.js new file mode 100644 index 00000000..c3628e40 --- /dev/null +++ b/uint8/benchmark/benchmark.find.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - tuple length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8Array( len ); + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':find:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.find_index.js b/uint8/benchmark/benchmark.find_index.js new file mode 100644 index 00000000..b4d8cd42 --- /dev/null +++ b/uint8/benchmark/benchmark.find_index.js @@ -0,0 +1,82 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':findIndex', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:findIndex', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate, {} ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/uint8/benchmark/benchmark.find_index.length.js b/uint8/benchmark/benchmark.find_index.length.js new file mode 100644 index 00000000..bf124a99 --- /dev/null +++ b/uint8/benchmark/benchmark.find_index.length.js @@ -0,0 +1,104 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':findIndex:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.for_each.js b/uint8/benchmark/benchmark.for_each.js new file mode 100644 index 00000000..404a9c9d --- /dev/null +++ b/uint8/benchmark/benchmark.for_each.js @@ -0,0 +1,88 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':forEach', function benchmark( b ) { + var count; + var arr; + var N; + var i; + + arr = new Uint8Array( 2 ); + N = arr.length; + + count = 0; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn ); + if ( count !== N*(i+1) ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( count !== N*i ) { + b.fail( 'unexpected result' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn() { + count += 1; + } +}); + +bench( pkg+'::this_context:forEach', function benchmark( b ) { + var count; + var arr; + var N; + var i; + + arr = new Uint8Array( 2 ); + N = arr.length; + + count = 0; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn, {} ); + if ( count !== N*(i+1) ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( count !== N*i ) { + b.fail( 'unexpected result' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn() { + count += 1; + } +}); diff --git a/uint8/benchmark/benchmark.for_each.length.js b/uint8/benchmark/benchmark.for_each.length.js new file mode 100644 index 00000000..a7ef3a42 --- /dev/null +++ b/uint8/benchmark/benchmark.for_each.length.js @@ -0,0 +1,106 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var count; + var arr; + + arr = new Uint8Array( len ); + count = 0; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn ); + if ( count !== count ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( count !== count ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } + + /** + * Callback invoked for each tuple element. + * + * @private + */ + function fcn() { + count += 1; + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':forEach:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.from.js b/uint8/benchmark/benchmark.from.js new file mode 100644 index 00000000..abe60a05 --- /dev/null +++ b/uint8/benchmark/benchmark.from.js @@ -0,0 +1,237 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var ITERATOR_SYMBOL = require( '@stdlib/symbol/iterator' ); +var isUint8Array = require( '@stdlib/assert/is-uint8array' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// VARIABLES // + +var opts = { + 'skip': ( ITERATOR_SYMBOL === null ) +}; + + +// MAIN // + +bench( pkg+'::typed_array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Uint8Array( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint8Array.from( buf ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint8Array( arr ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array,clbk:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Uint8Array( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint8Array.from( buf, clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint8Array( arr ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1; + } +}); + +bench( pkg+'::array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1, 2 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint8Array.from( buf ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint8Array( arr ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::array,clbk:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1, 2 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint8Array.from( buf, clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint8Array( arr ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1; + } +}); + +bench( pkg+'::iterable:from', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint8Array.from( createIterable() ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint8Array( arr ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out; + var i; + + out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + + i = 0; + + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + i += 1; + if ( i <= 2 ) { + return { + 'value': 0, + 'done': false + }; + } + return { + 'done': true + }; + } + } +}); + +bench( pkg+'::iterable,clbk:from:', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint8Array.from( createIterable(), clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint8Array( arr ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out; + var i; + + out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + + i = 0; + + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + i += 1; + if ( i <= 2 ) { + return { + 'value': 1, + 'done': false + }; + } + return { + 'done': true + }; + } + } + + function clbk( v ) { + return v + 1; + } +}); diff --git a/uint8/benchmark/benchmark.includes.js b/uint8/benchmark/benchmark.includes.js new file mode 100644 index 00000000..12a1656c --- /dev/null +++ b/uint8/benchmark/benchmark.includes.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':includes', function benchmark( b ) { + var bool; + var arr; + var v; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + bool = arr.includes( v ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/benchmark/benchmark.includes.length.js b/uint8/benchmark/benchmark.includes.length.js new file mode 100644 index 00000000..fdb98c85 --- /dev/null +++ b/uint8/benchmark/benchmark.includes.length.js @@ -0,0 +1,96 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + bool = arr.includes( v ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':includes:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.index_of.js b/uint8/benchmark/benchmark.index_of.js new file mode 100644 index 00000000..8fa6d85b --- /dev/null +++ b/uint8/benchmark/benchmark.index_of.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':indexOf', function benchmark( b ) { + var out; + var arr; + var v; + var i; + + arr = new Uint8Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.indexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/benchmark/benchmark.index_of.length.js b/uint8/benchmark/benchmark.index_of.length.js new file mode 100644 index 00000000..dd76a68a --- /dev/null +++ b/uint8/benchmark/benchmark.index_of.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.indexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':indexOf:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.join.js b/uint8/benchmark/benchmark.join.js new file mode 100644 index 00000000..958aa548 --- /dev/null +++ b/uint8/benchmark/benchmark.join.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':join', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i % 127; + out = arr.join(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/benchmark/benchmark.join.length.js b/uint8/benchmark/benchmark.join.length.js new file mode 100644 index 00000000..c25d2121 --- /dev/null +++ b/uint8/benchmark/benchmark.join.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i % 127; + out = arr.join(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':join:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.js b/uint8/benchmark/benchmark.js new file mode 100644 index 00000000..f2514f53 --- /dev/null +++ b/uint8/benchmark/benchmark.js @@ -0,0 +1,47 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint8Array = require( '@stdlib/assert/is-uint8array' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new ctor( 0 ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isUint8Array( arr ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/benchmark/benchmark.keys.js b/uint8/benchmark/benchmark.keys.js new file mode 100644 index 00000000..2c70df05 --- /dev/null +++ b/uint8/benchmark/benchmark.keys.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':keys', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.keys(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/benchmark/benchmark.last_index_of.js b/uint8/benchmark/benchmark.last_index_of.js new file mode 100644 index 00000000..0e80fc65 --- /dev/null +++ b/uint8/benchmark/benchmark.last_index_of.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':lastIndexOf', function benchmark( b ) { + var out; + var arr; + var v; + var i; + + arr = new Uint8Array( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.lastIndexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/benchmark/benchmark.last_index_of.length.js b/uint8/benchmark/benchmark.last_index_of.length.js new file mode 100644 index 00000000..b36aa4c7 --- /dev/null +++ b/uint8/benchmark/benchmark.last_index_of.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.lastIndexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':lastIndexOf:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.length.js b/uint8/benchmark/benchmark.length.js new file mode 100644 index 00000000..e40be57e --- /dev/null +++ b/uint8/benchmark/benchmark.length.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint8Array = require( '@stdlib/assert/is-uint8array' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new ctor( len ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isUint8Array( arr ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.map.js b/uint8/benchmark/benchmark.map.js new file mode 100644 index 00000000..106bc120 --- /dev/null +++ b/uint8/benchmark/benchmark.map.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint8Array = require( '@stdlib/assert/is-uint8array' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':map', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8Array( out ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); + +bench( pkg+'::this_context:map', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn, {} ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8Array( out ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/uint8/benchmark/benchmark.map.length.js b/uint8/benchmark/benchmark.map.length.js new file mode 100644 index 00000000..f0200bd5 --- /dev/null +++ b/uint8/benchmark/benchmark.map.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint8Array = require( '@stdlib/assert/is-uint8array' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Maps an array element to a new value. +* +* @private +* @param {*} value - array element +* @returns {*} new value +*/ +function fcn( value ) { + return value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8Array( out ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':map:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.of.js b/uint8/benchmark/benchmark.of.js new file mode 100644 index 00000000..6aaa2bf4 --- /dev/null +++ b/uint8/benchmark/benchmark.of.js @@ -0,0 +1,48 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint8Array = require( '@stdlib/assert/is-uint8array' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':of', function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint8Array.of( i, 2 ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint8Array( arr ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/benchmark/benchmark.properties.js b/uint8/benchmark/benchmark.properties.js new file mode 100644 index 00000000..891b634f --- /dev/null +++ b/uint8/benchmark/benchmark.properties.js @@ -0,0 +1,145 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isArrayBuffer = require( '@stdlib/assert/is-arraybuffer' ); +var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::get:buffer', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.buffer; + if ( typeof v !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isArrayBuffer( v ) ) { + b.fail( 'should return an ArrayBuffer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteLength', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteLength; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteOffset', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteOffset; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:BYTES_PER_ELEMENT', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.BYTES_PER_ELEMENT; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:length', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.length; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/benchmark/benchmark.reduce.js b/uint8/benchmark/benchmark.reduce.js new file mode 100644 index 00000000..21498da8 --- /dev/null +++ b/uint8/benchmark/benchmark.reduce.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reduce', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( acc, v ) { + return acc + v + 1; + } +}); + +bench( pkg+'::initial_value:reduce', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn, 3 ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/uint8/benchmark/benchmark.reduce.length.js b/uint8/benchmark/benchmark.reduce.length.js new file mode 100644 index 00000000..82c3ceb4 --- /dev/null +++ b/uint8/benchmark/benchmark.reduce.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Updates an accumulated value. +* +* @private +* @param {*} acc - accumulated value +* @param {*} value - array element +* @returns {*} accumulated value +*/ +function fcn( acc, value ) { + return acc + value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reduce:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.reduce_right.js b/uint8/benchmark/benchmark.reduce_right.js new file mode 100644 index 00000000..e452af1d --- /dev/null +++ b/uint8/benchmark/benchmark.reduce_right.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reduceRight', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( acc, v ) { + return acc + v + 1; + } +}); + +bench( pkg+'::initial_value:reduceRight', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn, 3 ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/uint8/benchmark/benchmark.reduce_right.length.js b/uint8/benchmark/benchmark.reduce_right.length.js new file mode 100644 index 00000000..6e1b422e --- /dev/null +++ b/uint8/benchmark/benchmark.reduce_right.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Updates an accumulated value. +* +* @private +* @param {*} acc - accumulated value +* @param {*} value - array element +* @returns {*} accumulated value +*/ +function fcn( acc, value ) { + return acc + value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reduceRight:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.reverse.js b/uint8/benchmark/benchmark.reverse.js new file mode 100644 index 00000000..84bcc28b --- /dev/null +++ b/uint8/benchmark/benchmark.reverse.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint8Array = require( '@stdlib/assert/is-uint8array' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reverse', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.reverse(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8Array( out ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/benchmark/benchmark.reverse.length.js b/uint8/benchmark/benchmark.reverse.length.js new file mode 100644 index 00000000..e5e360ee --- /dev/null +++ b/uint8/benchmark/benchmark.reverse.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint8Array = require( '@stdlib/assert/is-uint8array' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.reverse(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8Array( out ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reverse:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.set.js b/uint8/benchmark/benchmark.set.js new file mode 100644 index 00000000..59827e1e --- /dev/null +++ b/uint8/benchmark/benchmark.set.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::array:set', function benchmark( b ) { + var values; + var buf; + var arr; + var N; + var v; + var i; + + values = []; + for ( i = 0; i < 10; i++ ) { + values.push( i ); + } + N = values.length; + + arr = new Uint8Array( 2 ); + buf = [ 0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = values[ i%N ]; + v = arr.set( buf ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array:set', function benchmark( b ) { + var values; + var buf; + var arr; + var N; + var v; + var i; + + values = new Uint8Array( 20 ); + N = values.length; + for ( i = 0; i < N; i++ ) { + values[ i ] = i; + } + + arr = new Uint8Array( 2 ); + buf = new Uint8Array( 1 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = values[ i%N ]; + v = arr.set( buf ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/benchmark/benchmark.set.length.js b/uint8/benchmark/benchmark.set.length.js new file mode 100644 index 00000000..052293f4 --- /dev/null +++ b/uint8/benchmark/benchmark.set.length.js @@ -0,0 +1,114 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randi = require( '@stdlib/random/base/randi' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var values; + var arr1; + var arr2; + var arr; + var N; + var i; + + arr1 = []; + arr2 = []; + for ( i = 0; i < len; i++ ) { + arr1.push( randi() ); + arr2.push( randi() ); + } + arr = new Uint8Array( len ); + + values = [ + arr1, + arr2 + ]; + N = values.length; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr.set( values[ i%N ] ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':set:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.slice.js b/uint8/benchmark/benchmark.slice.js new file mode 100644 index 00000000..874b535e --- /dev/null +++ b/uint8/benchmark/benchmark.slice.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint8Array = require( '@stdlib/assert/is-uint8array' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':slice', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.slice(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8Array( out ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/benchmark/benchmark.slice.length.js b/uint8/benchmark/benchmark.slice.length.js new file mode 100644 index 00000000..78e2b7e1 --- /dev/null +++ b/uint8/benchmark/benchmark.slice.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint8Array = require( '@stdlib/assert/is-uint8array' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.slice(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8Array( out ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':slice:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.some.js b/uint8/benchmark/benchmark.some.js new file mode 100644 index 00000000..f20c59ca --- /dev/null +++ b/uint8/benchmark/benchmark.some.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':some', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:some', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate, {} ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/uint8/benchmark/benchmark.some.length.js b/uint8/benchmark/benchmark.some.length.js new file mode 100644 index 00000000..647c0768 --- /dev/null +++ b/uint8/benchmark/benchmark.some.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':some:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.sort.js b/uint8/benchmark/benchmark.sort.js new file mode 100644 index 00000000..4d36b9d6 --- /dev/null +++ b/uint8/benchmark/benchmark.sort.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var randi = require( '@stdlib/random/base/randi' ); +var isUint8Array = require( '@stdlib/assert/is-uint8array' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':sort', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8Array( [ randi(), randi() ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = randi(); + out = arr.sort(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8Array( out ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/benchmark/benchmark.sort.length.js b/uint8/benchmark/benchmark.sort.length.js new file mode 100644 index 00000000..ca66eda0 --- /dev/null +++ b/uint8/benchmark/benchmark.sort.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randi = require( '@stdlib/random/base/randi' ); +var isUint8Array = require( '@stdlib/assert/is-uint8array' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var data; + var arr; + var i; + + data = []; + for ( i = 0; i < len; i++ ) { + data.push( randi() ); + } + arr = new Uint8Array( data ); + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ i%len ] = randi(); + out = arr.sort(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8Array( out ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':sort:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.subarray.js b/uint8/benchmark/benchmark.subarray.js new file mode 100644 index 00000000..2c91017e --- /dev/null +++ b/uint8/benchmark/benchmark.subarray.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint8Array = require( '@stdlib/assert/is-uint8array' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':subarray', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.subarray(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8Array( out ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/benchmark/benchmark.subarray.length.js b/uint8/benchmark/benchmark.subarray.length.js new file mode 100644 index 00000000..e353f017 --- /dev/null +++ b/uint8/benchmark/benchmark.subarray.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint8Array = require( '@stdlib/assert/is-uint8array' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.subarray(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8Array( out ) ) { + b.fail( 'should return a Uint8Array' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':subarray:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.to_locale_string.js b/uint8/benchmark/benchmark.to_locale_string.js new file mode 100644 index 00000000..7631518a --- /dev/null +++ b/uint8/benchmark/benchmark.to_locale_string.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':toLocaleString', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toLocaleString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/benchmark/benchmark.to_locale_string.length.js b/uint8/benchmark/benchmark.to_locale_string.length.js new file mode 100644 index 00000000..824ebc29 --- /dev/null +++ b/uint8/benchmark/benchmark.to_locale_string.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toLocaleString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':toLocaleString:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.to_string.js b/uint8/benchmark/benchmark.to_string.js new file mode 100644 index 00000000..75f8bcb2 --- /dev/null +++ b/uint8/benchmark/benchmark.to_string.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':toString', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/benchmark/benchmark.to_string.length.js b/uint8/benchmark/benchmark.to_string.length.js new file mode 100644 index 00000000..de8020da --- /dev/null +++ b/uint8/benchmark/benchmark.to_string.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8Array( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':toString:len='+len, f ); + } +} + +main(); diff --git a/uint8/benchmark/benchmark.values.js b/uint8/benchmark/benchmark.values.js new file mode 100644 index 00000000..f5932384 --- /dev/null +++ b/uint8/benchmark/benchmark.values.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8Array = require( './../lib' ); + + +// MAIN // + +bench( pkg+':values', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.values(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8/docs/repl.txt b/uint8/docs/repl.txt new file mode 100644 index 00000000..e4c3209b --- /dev/null +++ b/uint8/docs/repl.txt @@ -0,0 +1,953 @@ + +{{alias}}() + A typed array constructor which returns a typed array representing an array + of 8-bit unsigned integers in the platform byte order. + + Returns + ------- + out: Uint8Array + A typed array. + + Examples + -------- + > var arr = new {{alias}}() + + + +{{alias}}( length ) + Returns a typed array having a specified length. + + Parameters + ---------- + length: integer + Typed array length. + + Returns + ------- + out: Uint8Array + A typed array. + + Examples + -------- + > var arr = new {{alias}}( 5 ) + [ 0, 0, 0, 0, 0 ] + + +{{alias}}( typedarray ) + Creates a typed array from another typed array. + + Parameters + ---------- + typedarray: TypedArray + Typed array from which to generate another typed array. + + Returns + ------- + out: Uint8Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias:@stdlib/array/int32}}( [ 5, 5, 5 ] ); + > var arr2 = new {{alias}}( arr1 ) + [ 5, 5, 5 ] + + +{{alias}}( obj ) + Creates a typed array from an array-like object or iterable. + + Parameters + ---------- + obj: Object + Array-like object or iterable from which to generate a typed array. + + Returns + ------- + out: Uint8Array + A typed array. + + Examples + -------- + > var arr1 = [ 5.0, 5.0, 5.0 ]; + > var arr2 = new {{alias}}( arr1 ) + [ 5, 5, 5 ] + + +{{alias}}( buffer[, byteOffset[, length]] ) + Returns a typed array view of an ArrayBuffer. + + Parameters + ---------- + buffer: ArrayBuffer + Underlying ArrayBuffer. + + byteOffset: integer (optional) + Integer byte offset specifying the location of the first typed array + element. Default: 0. + + length: integer (optional) + View length. If not provided, the view spans from the byteOffset to + the end of the underlying ArrayBuffer. + + Returns + ------- + out: Uint8Array + A typed array. + + Examples + -------- + > var buf = new {{alias:@stdlib/array/buffer}}( 4 ); + > var arr = new {{alias}}( buf, 0, 4 ) + [ 0, 0, 0, 0 ] + + +{{alias}}.from( src[, map[, thisArg]] ) + Creates a new typed array from an array-like object or an iterable. + + A callback is provided the following arguments: + + - value: source value. + - index: source index. + + Parameters + ---------- + src: ArrayLike|Iterable + Source of array elements. + + map: Function (optional) + Callback to invoke for each source element. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Uint8Array + A typed array. + + Examples + -------- + > function mapFcn( v ) { return v * 2; }; + > var arr = {{alias}}.from( [ 1, 2 ], mapFcn ) + [ 2, 4 ] + + +{{alias}}.of( element0[, element1[, ...elementN]] ) + Creates a new typed array from a variable number of arguments. + + Parameters + ---------- + element0: number + Array element. + + element1: number (optional) + Array element. + + elementN: number (optional) + Array elements. + + Returns + ------- + out: Uint8Array + A typed array. + + Examples + -------- + > var arr = {{alias}}.of( 1, 2 ) + [ 1, 2 ] + + +{{alias}}.BYTES_PER_ELEMENT + Number of bytes per view element. + + Examples + -------- + > {{alias}}.BYTES_PER_ELEMENT + 1 + + +{{alias}}.name + Typed array constructor name. + + Examples + -------- + > {{alias}}.name + 'Uint8Array' + + +{{alias}}.prototype.buffer + Read-only property which returns the ArrayBuffer referenced by the typed + array. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.buffer + + + +{{alias}}.prototype.byteLength + Read-only property which returns the length (in bytes) of the typed array. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.byteLength + 5 + + +{{alias}}.prototype.byteOffset + Read-only property which returns the offset (in bytes) of the typed array + from the start of its ArrayBuffer. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.byteOffset + 0 + + +{{alias}}.prototype.BYTES_PER_ELEMENT + Number of bytes per view element. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.BYTES_PER_ELEMENT + 1 + + +{{alias}}.prototype.length + Read-only property which returns the number of view elements. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.length + 5 + + +{{alias}}.prototype.copyWithin( target, start[, end] ) + Copies a sequence of elements within the array starting at `start` and + ending at `end` (non-inclusive) to the position starting at `target`. + + Parameters + ---------- + target: integer + Target start index position. + + start: integer + Source start index position. + + end: integer (optional) + Source end index position. Default: out.length. + + Returns + ------- + out: Uint8Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3, 4, 5 ] ); + > arr.copyWithin( 3, 0, 2 ); + > arr[ 3 ] + 1 + > arr[ 4 ] + 2 + + +{{alias}}.prototype.entries() + Returns an iterator for iterating over array key-value pairs. + + Returns + ------- + iter: Iterator + Iterator for iterating over array key-value pairs. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.entries(); + > it.next().value + [ 0, 1 ] + > it.next().value + [ 1, 2 ] + > it.next().done + true + + +{{alias}}.prototype.every( predicate[, thisArg] ) + Tests whether all array elements pass a test implemented by a predicate + function. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. If a predicate function + returns a truthy value, an array element passes; otherwise, an array + element fails. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + bool: boolean + Boolean indicating whether all array elements pass. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > function predicate( v ) { return ( v <= 1 ); }; + > arr.every( predicate ) + false + + +{{alias}}.prototype.fill( value[, start[, end]] ) + Fills an array from a start index to an end index (non-inclusive) with a + provided value. + + Parameters + ---------- + value: number + Fill value. + + start: integer (optional) + Start index. If less than zero, the start index is resolved relative to + the last array element. Default: 0. + + end: integer (optional) + End index (non-inclusive). If less than zero, the end index is resolved + relative to the last array element. Default: out.length. + + Returns + ------- + out: Uint8Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > arr.fill( 3 ); + > arr[ 0 ] + 3 + > arr[ 1 ] + 3 + + +{{alias}}.prototype.filter( predicate[, thisArg] ) + Creates a new array which includes those elements for which a predicate + function returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + The returned array has the same data type as the host array. + + If a predicate function does not return a truthy value for any array + element, the method returns `null`. + + Parameters + ---------- + predicate: Function + Predicate function which filters array elements. If a predicate function + returns a truthy value, an array element is included in the output + array; otherwise, an array element is not included in the output array. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Uint8Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 1 ); }; + > var arr2 = arr1.filter( predicate ); + > arr2.length + 2 + + +{{alias}}.prototype.find( predicate[, thisArg] ) + Returns the first array element for which a provided predicate function + returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + If a predicate function never returns a truthy value, the method returns + `undefined`. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + value: number|undefined + Array element. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 2 ); }; + > var v = arr.find( predicate ) + 3 + + +{{alias}}.prototype.findIndex( predicate[, thisArg] ) + Returns the index of the first array element for which a provided predicate + function returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + If a predicate function never returns a truthy value, the method returns + `-1`. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + idx: integer + Array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 2 ); }; + > var idx = arr.findIndex( predicate ) + 2 + + +{{alias}}.prototype.forEach( fcn[, thisArg] ) + Invokes a callback for each array element. + + A provided function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + fcn: Function + Function to invoke for each array element. + + thisArg: Any (optional) + Callback execution context. + + Examples + -------- + > var arr = new {{alias}}( [ 3, 2, 1 ] ); + > var str = ' '; + > function fcn( v, i ) { str += i + ':' + v + ' '; }; + > arr.forEach( fcn ); + > str + ' 0:3 1:2 2:1 ' + + +{{alias}}.prototype.includes( searchElement[, fromIndex] ) + Returns a boolean indicating whether an array includes a search element. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: 0. + + Returns + ------- + bool: boolean + Boolean indicating whether an array includes a search element. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > var bool = arr.includes( 4 ) + false + > bool = arr.includes( 3 ) + true + + +{{alias}}.prototype.indexOf( searchElement[, fromIndex] ) + Returns the index of the first array element strictly equal to a search + element. + + If unable to locate a search element, the method returns `-1`. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: 0. + + Returns + ------- + idx: integer + Array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > var idx = arr.indexOf( 4 ) + -1 + > idx = arr.indexOf( 3 ) + 2 + + +{{alias}}.prototype.join( [separator] ) + Serializes an array by joining all array elements as a string. + + Parameters + ---------- + separator: string (optional) + String delineating array elements. Default: ','. + + Returns + ------- + str: string + Array serialized as a string. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.join( '|' ) + '1|2|3' + + +{{alias}}.prototype.keys() + Returns an iterator for iterating over array keys. + + Returns + ------- + iter: Iterator + Iterator for iterating over array keys. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.keys(); + > it.next().value + 0 + > it.next().value + 1 + > it.next().done + true + + +{{alias}}.prototype.lastIndexOf( searchElement[, fromIndex] ) + Returns the index of the last array element strictly equal to a search + element. + + The method iterates from the last array element to the first array element. + + If unable to locate a search element, the method returns `-1`. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: -1. + + Returns + ------- + idx: integer + array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 0, 2, 0, 1 ] ); + > var idx = arr.lastIndexOf( 3 ) + -1 + > idx = arr.lastIndexOf( 0 ) + 3 + + +{{alias}}.prototype.map( fcn[, thisArg] ) + Maps each array element to an element in a new typed array. + + A provided function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + The returned array has the same data type as the host array. + + Parameters + ---------- + fcn: Function + Function which maps array elements to elements in the new array. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Uint8Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( v ) { return v * 2; }; + > var arr2 = arr1.map( fcn ); + [ 2, 4, 6 ] + + +{{alias}}.prototype.reduce( fcn[, initialValue] ) + Applies a function against an accumulator and each element in an array and + returns the accumulated result. + + The provided function is provided the following arguments: + + - acc: accumulated result. + - value: current array element. + - index: index of the current array element. + - arr: array on which the method is invoked. + + If provided an initial value, the method invokes a provided function with + the initial value as the first argument and the first array element as the + second argument. + + If not provided an initial value, the method invokes a provided function + with the first array element as the first argument and the second array + element as the second argument. + + Parameters + ---------- + fcn: Function + Function to apply. + + initialValue: Any (optional) + Initial accumulation value. + + Returns + ------- + out: Any + Accumulated result. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( acc, v ) { return acc + (v*v); }; + > var v = arr.reduce( fcn, 0 ) + 14 + + +{{alias}}.prototype.reduceRight( fcn[, initialValue] ) + Applies a function against an accumulator and each element in an array and + returns the accumulated result, iterating from right to left. + + The provided function is provided the following arguments: + + - acc: accumulated result. + - value: current array element. + - index: index of the current array element. + - arr: array on which the method is invoked. + + If provided an initial value, the method invokes a provided function with + the initial value as the first argument and the last array element as the + second argument. + + If not provided an initial value, the method invokes a provided function + with the last array element as the first argument and the second-to-last + array element as the second argument. + + Parameters + ---------- + fcn: Function + Function to apply. + + initialValue: Any (optional) + Initial accumulation value. + + Returns + ------- + out: Any + Accumulated result. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( acc, v ) { return acc + (v*v); }; + > var v = arr.reduceRight( fcn, 0 ) + 14 + + +{{alias}}.prototype.reverse() + Reverses an array *in-place*. + + This method mutates the array on which the method is invoked. + + Returns + ------- + out: Uint8Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ) + [ 1, 2, 3 ] + > arr.reverse() + [ 3, 2, 1 ] + + +{{alias}}.prototype.set( arr[, offset] ) + Sets array elements. + + Parameters + ---------- + arr: ArrayLike + Source array containing array values to set. + + offset: integer (optional) + Array index at which to start writing values. Default: 0. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.set( [ 4, 4 ], 1 ); + > arr[ 1 ] + 4 + > arr[ 2 ] + 4 + + +{{alias}}.prototype.slice( [begin[, end]] ) + Copies array elements to a new array with the same underlying data type as + the host array. + + If the method is unable to resolve indices to a non-empty array subsequence, + the method returns `null`. + + Parameters + ---------- + begin: integer (optional) + Start element index (inclusive). If less than zero, the start index is + resolved relative to the last array element. Default: 0. + + end: integer (optional) + End element index (exclusive). If less than zero, the end index is + resolved relative to the last array element. Default: arr.length. + + Returns + ------- + out: Uint8Array + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > var arr2 = arr1.slice( 1 ); + > arr2.length + 2 + > arr2[ 0 ] + 1 + > arr2[ 1 ] + 2 + + +{{alias}}.prototype.some( predicate[, thisArg] ) + Tests whether at least one array element passes a test implemented by a + predicate function. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. If a predicate function + returns a truthy value, a array element passes; otherwise, an array + element fails. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + bool: boolean + Boolean indicating whether at least one array element passes. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > function predicate( v ) { return ( v > 1 ); }; + > arr.some( predicate ) + true + + +{{alias}}.prototype.sort( [compareFunction] ) + Sorts an array *in-place*. + + The comparison function is provided two array elements per invocation: `a` + and `b`. + + The comparison function return value determines the sort order as follows: + + - If the comparison function returns a value less than zero, then the method + sorts `a` to an index lower than `b` (i.e., `a` should come *before* `b`). + + - If the comparison function returns a value greater than zero, then the + method sorts `a` to an index higher than `b` (i.e., `b` should come *before* + `a`). + + - If the comparison function returns zero, then the relative order of `a` + and `b` should remain unchanged. + + This method mutates the array on which the method is invoked. + + Parameters + ---------- + compareFunction: Function (optional) + Function which specifies the sort order. The default sort order is + ascending order. + + Returns + ------- + out: Uint8Array + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 0, 2, 1 ] ); + > arr.sort() + [ 0, 1, 1, 2, 2 ] + + +{{alias}}.prototype.subarray( [begin[, end]] ) + Creates a new typed array over the same underlying ArrayBuffer and with the + same underlying data type as the host array. + + If the method is unable to resolve indices to a non-empty array subsequence, + the method returns an empty typed array. + + Parameters + ---------- + begin: integer (optional) + Start element index (inclusive). If less than zero, the start index is + resolved relative to the last array element. Default: 0. + + end: integer (optional) + End element index (exclusive). If less than zero, the end index is + resolved relative to the last array element. Default: arr.length. + + Returns + ------- + out: Uint8Array + A new typed array view. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3, 4, 5 ] ); + > var arr2 = arr1.subarray( 2 ) + [ 3, 4, 5 ] + + +{{alias}}.prototype.toLocaleString( [locales[, options]] ) + Serializes an array as a locale-specific string. + + Parameters + ---------- + locales: string|Array (optional) + A BCP 47 language tag, or an array of such tags. + + options: Object (optional) + Options. + + Returns + ------- + str: string + A typed array string representation. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.toLocaleString() + '1,2,3' + + +{{alias}}.prototype.toString() + Serializes an array as a string. + + Returns + ------- + str: string + A typed array string representation. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.toString() + '1,2,3' + + +{{alias}}.prototype.values() + Returns an iterator for iterating over array elements. + + Returns + ------- + iter: Iterator + Iterator for iterating over array elements. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.values(); + > it.next().value + 1 + > it.next().value + 2 + > it.next().done + true + + + See Also + -------- + diff --git a/uint8/docs/types/index.d.ts b/uint8/docs/types/index.d.ts new file mode 100644 index 00000000..7803cfcb --- /dev/null +++ b/uint8/docs/types/index.d.ts @@ -0,0 +1,26 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +// EXPORTS // + +/** +* Typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order. +*/ +export = Uint8Array; diff --git a/uint8/docs/types/test.ts b/uint8/docs/types/test.ts new file mode 100644 index 00000000..3db20813 --- /dev/null +++ b/uint8/docs/types/test.ts @@ -0,0 +1,37 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// tslint:disable: no-construct +// tslint:disable: no-unused-expression + +import Uint8Array = require( './index' ); + + +// TESTS // + +// The function returns a typed array instance... +{ + new Uint8Array( 10 ); // $ExpectType Uint8Array + new Uint8Array( [ 2, 5, 5, 7 ] ); // $ExpectType Uint8Array +} + +// The constructor function has to be invoked with `new`... +{ + Uint8Array( 10 ); // $ExpectError + Uint8Array( [ 2, 5, 5, 7 ] ); // $ExpectError +} diff --git a/uint8/examples/index.js b/uint8/examples/index.js new file mode 100644 index 00000000..d0978bec --- /dev/null +++ b/uint8/examples/index.js @@ -0,0 +1,32 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var randu = require( '@stdlib/random/base/randu' ); +var round = require( '@stdlib/math/base/special/round' ); +var ctor = require( './../lib' ); + +var arr; +var i; + +arr = new ctor( 10 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = round( randu()*100.0 ); +} +console.log( arr ); diff --git a/uint8/lib/index.js b/uint8/lib/index.js new file mode 100644 index 00000000..0fe6fc91 --- /dev/null +++ b/uint8/lib/index.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order. +* +* @module @stdlib/array/uint8 +* +* @example +* var ctor = require( '@stdlib/array/uint8' ); +* +* var arr = new ctor( 10 ); +* // returns +*/ + +// MODULES // + +var hasUint8ArraySupport = require( '@stdlib/assert/has-uint8array-support' ); +var builtin = require( './uint8array.js' ); +var polyfill = require( './polyfill.js' ); + + +// MAIN // + +var ctor; +if ( hasUint8ArraySupport() ) { + ctor = builtin; +} else { + ctor = polyfill; +} + + +// EXPORTS // + +module.exports = ctor; diff --git a/uint8/lib/polyfill.js b/uint8/lib/polyfill.js new file mode 100644 index 00000000..6b806341 --- /dev/null +++ b/uint8/lib/polyfill.js @@ -0,0 +1,37 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// TODO: write polyfill + +// MAIN // + +/** +* Typed array which represents an array of 8-bit unsigned integers in the platform byte order. +* +* @throws {Error} not implemented +*/ +function polyfill() { + throw new Error( 'not implemented' ); +} + + +// EXPORTS // + +module.exports = polyfill; diff --git a/uint8/lib/uint8array.js b/uint8/lib/uint8array.js new file mode 100644 index 00000000..c19ff14e --- /dev/null +++ b/uint8/lib/uint8array.js @@ -0,0 +1,28 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MAIN // + +var ctor = ( typeof Uint8Array === 'function' ) ? Uint8Array : void 0; // eslint-disable-line stdlib/require-globals + + +// EXPORTS // + +module.exports = ctor; diff --git a/uint8/package.json b/uint8/package.json new file mode 100644 index 00000000..49ec4b62 --- /dev/null +++ b/uint8/package.json @@ -0,0 +1,71 @@ +{ + "name": "@stdlib/array/uint8", + "version": "0.0.0", + "description": "Uint8Array.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structure", + "array", + "typed", + "typed array", + "typed-array", + "uint8array", + "uint8", + "uint8_t", + "integer", + "int", + "uint", + "unsigned", + "byte", + "octet" + ] +} diff --git a/uint8/test/test.copy_within.js b/uint8/test/test.copy_within.js new file mode 100644 index 00000000..56d67eea --- /dev/null +++ b/uint8/test/test.copy_within.js @@ -0,0 +1,320 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var hasProp = require( '@stdlib/assert/has-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var Uint8Array = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof Uint8Array, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'a typed array instance has a `copyWithin` method for copying a sequence of elements within a typed array', function test( t ) { + var arr = new Uint8Array( 2 ); + t.strictEqual( hasProp( arr, 'copyWithin' ), true, 'has property' ); + t.strictEqual( isFunction( arr.copyWithin ), true, 'has method' ); + t.end(); +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a typed array instance', function test( t ) { + var values; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0 ); + }; + } +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a typed array instance (end)', function test( t ) { + var values; + var arr; + var i; + + arr = new Uint8Array( 2 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0, 5 ); + }; + } +}); + +tape( 'the method copies a sequence of elements within a typed array', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint8Array( arr ); + p.copyWithin( 0, 3 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative target)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint8Array( arr ); + p.copyWithin( -p.length, 3 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative start)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint8Array( arr ); + p.copyWithin( 0, -2 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (end=length)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint8Array( arr ); + p.copyWithin( 0, 3, p.length ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (non-inclusive end)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint8Array( arr ); + p.copyWithin( 2, 0, 2 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative end)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint8Array( arr ); + p.copyWithin( 2, 0, -3 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (target >= length)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint8Array( arr ); + p.copyWithin( p.length, 3 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (target > start)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint8Array( arr ); + p.copyWithin( 2, 0 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + t.strictEqual( p[ 4 ], 2, 'returns expected value' ); + + t.end(); +}); diff --git a/uint8/test/test.js b/uint8/test/test.js new file mode 100644 index 00000000..4c6046f7 --- /dev/null +++ b/uint8/test/test.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var hasUint8ArraySupport = require( '@stdlib/assert/has-uint8array-support' ); +var polyfill = require( './../lib/polyfill.js' ); +var ctor = require( './../lib' ); + + +// VARIABLES // + +var hasUint8Arrays = hasUint8ArraySupport(); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'if an environment supports `Uint8Array`, the export is an alias for `Uint8Array`', function test( t ) { + var Foo; + + Foo = proxyquire( './../lib', { + '@stdlib/assert/has-uint8array-support': isTrue, + './uint8array.js': Mock + }); + t.strictEqual( Foo, Mock, 'returns builtin' ); + + if ( hasUint8Arrays ) { + t.strictEqual( ctor, Uint8Array, 'is alias' ); // eslint-disable-line stdlib/require-globals + } + + t.end(); + + function Mock() { + return this; + } + + function isTrue() { + return true; + } +}); + +tape( 'if an environment does not support `Uint8Array`, the export is a polyfill', function test( t ) { + var Foo; + + Foo = proxyquire( './../lib', { + '@stdlib/assert/has-uint8array-support': isFalse + }); + + t.strictEqual( Foo, polyfill, 'returns polyfill' ); + t.end(); + + function isFalse() { + return false; + } +}); diff --git a/uint8/test/test.polyfill.js b/uint8/test/test.polyfill.js new file mode 100644 index 00000000..9d6fcb19 --- /dev/null +++ b/uint8/test/test.polyfill.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var ctor = require( './../lib/polyfill.js' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error when invoked', function test( t ) { + t.throws( foo, Error, 'throws an error' ); + t.end(); + + function foo() { + var f = new ctor(); // eslint-disable-line no-unused-vars + } +}); + +// TODO: tests diff --git a/uint8c/README.md b/uint8c/README.md new file mode 100644 index 00000000..2b5172c6 --- /dev/null +++ b/uint8c/README.md @@ -0,0 +1,1431 @@ + + +# Uint8ClampedArray + +> [Typed array][mdn-typed-array] constructor which returns a [typed array][mdn-typed-array] representing an array of 8-bit unsigned integers in the platform byte order clamped to 0-255. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); +``` + +#### Uint8ClampedArray() + +A [typed array][mdn-typed-array] constructor which returns a [typed array][mdn-typed-array] representing an array of 8-bit unsigned integers in the platform byte order clamped to `0-255`. + + + +```javascript +var arr = new Uint8ClampedArray(); +// returns +``` + +#### Uint8ClampedArray( length ) + +Returns a [typed array][mdn-typed-array] having a specified length. + + + +```javascript +var arr = new Uint8ClampedArray( 5 ); +// returns [ 0, 0, 0, 0, 0 ] +``` + +#### Uint8ClampedArray( typedarray ) + +Creates a [typed array][mdn-typed-array] from another [typed array][mdn-typed-array]. + + + +```javascript +var Float32Array = require( '@stdlib/array/float32' ); + +var arr1 = new Float32Array( [ 5.0, 5.0, 5.0 ] ); +var arr2 = new Uint8ClampedArray( arr1 ); +// returns [ 5, 5, 5 ] +``` + +#### Uint8ClampedArray( obj ) + +Creates a [typed array][mdn-typed-array] from an array-like `object` or iterable. + + + +```javascript +var arr = new Uint8ClampedArray( [ 5.0, 5.0, 5.0 ] ); +// returns [ 5, 5, 5 ] +``` + +#### Uint8ClampedArray( buffer\[, byteOffset\[, length]] ) + +Returns a [typed array][mdn-typed-array] view of an [`ArrayBuffer`][@stdlib/array/buffer]. + + + +```javascript +var ArrayBuffer = require( '@stdlib/array/buffer' ); + +var buf = new ArrayBuffer( 4 ); +var arr = new Uint8ClampedArray( buf, 0, 4 ); +// returns [ 0, 0, 0, 0 ] +``` + +* * * + +### Properties + + + +#### Uint8ClampedArray.BYTES_PER_ELEMENT + +Number of bytes per view element. + + + +```javascript +var nbytes = Uint8ClampedArray.BYTES_PER_ELEMENT; +// returns 1 +``` + + + +#### Uint8ClampedArray.name + +[Typed array][mdn-typed-array] constructor name. + + + +```javascript +var str = Uint8ClampedArray.name; +// returns 'Uint8ClampedArray' +``` + + + +#### Uint8ClampedArray.prototype.buffer + +**Read-only** property which returns the [`ArrayBuffer`][@stdlib/array/buffer] referenced by the [typed array][mdn-typed-array]. + + + +```javascript +var arr = new Uint8ClampedArray( 5 ); +var buf = arr.buffer; +// returns +``` + + + +#### Uint8ClampedArray.prototype.byteLength + +**Read-only** property which returns the length (in bytes) of the [typed array][mdn-typed-array]. + + + +```javascript +var arr = new Uint8ClampedArray( 5 ); +var byteLength = arr.byteLength; +// returns 5 +``` + + + +#### Uint8ClampedArray.prototype.byteOffset + +**Read-only** property which returns the offset (in bytes) of the [typed array][mdn-typed-array] from the start of its [`ArrayBuffer`][@stdlib/array/buffer]. + + + +```javascript +var arr = new Uint8ClampedArray( 5 ); +var byteOffset = arr.byteOffset; +// returns 0 +``` + + + +#### Uint8ClampedArray.prototype.BYTES_PER_ELEMENT + +Number of bytes per view element. + + + +```javascript +var arr = new Uint8ClampedArray( 5 ); +var nbytes = arr.BYTES_PER_ELEMENT; +// returns 1 +``` + + + +#### Uint8ClampedArray.prototype.length + +**Read-only** property which returns the number of view elements. + + + +```javascript +var arr = new Uint8ClampedArray( 5 ); +var len = arr.length; +// returns 5 +``` + +* * * + +### Methods + + + +#### Uint8ClampedArray.from( src\[, map\[, thisArg]] ) + +Creates a new typed array from an array-like `object` or an iterable. + +```javascript +var arr = Uint8ClampedArray.from( [ 1, 2 ] ); +// returns [ 1, 2 ] +``` + +To invoke a function for each `src` value, provide a callback function. + +```javascript +function mapFcn( v ) { + return v * 2; +} + +var arr = Uint8ClampedArray.from( [ 1, 2 ], mapFcn ); +// returns [ 2, 4 ] +``` + +A callback function is provided two arguments: + +- `value`: source value +- `index`: source index + +To set the callback execution context, provide a `thisArg`. + +```javascript +function mapFcn( v ) { + this.count += 1; + return v * 2; +} + +var ctx = { + 'count': 0 +}; + +var arr = Uint8ClampedArray.from( [ 1, 2 ], mapFcn, ctx ); +// returns [ 2, 4 ] + +var n = ctx.count; +// returns 2 +``` + + + +#### Uint8ClampedArray.of( element0\[, element1\[, ...elementN]] ) + +Creates a new typed array from a variable number of arguments. + +```javascript +var arr = Uint8ClampedArray.of( 1, 2 ); +// returns [ 1, 2 ] +``` + + + +#### Uint8ClampedArray.prototype.copyWithin( target, start\[, end] ) + +Copies a sequence of elements within an array starting at `start` and ending at `end` (non-inclusive) to the position starting at `target`. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 2, 3, 4, 5 ] ); + +// Copy the last two elements to the first two elements: +arr.copyWithin( 0, 3 ); + +var v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 5 +``` + +By default, `end` equals the number of array elements (i.e., one more than the last array index). To limit the sequence length, provide an `end` argument. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 2, 3, 4, 5 ] ); + +// Copy the first two elements to the last two elements: +arr.copyWithin( 3, 0, 2 ); + +var v = arr[ 3 ]; +// returns 1 + +v = arr[ 4 ]; +// returns 2 +``` + +When a `target`, `start`, and/or `end` index is negative, the respective index is determined relative to the last array element. The following example achieves the same behavior as the previous example: + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 2, 3, 4, 5 ] ); + +// Copy the first two elements to the last two elements: +arr.copyWithin( -2, -5, -3 ); + +var v = arr[ 3 ]; +// returns 1 + +v = arr[ 4 ]; +// returns 2 +``` + + + +#### Uint8ClampedArray.prototype.entries() + +Returns an iterator for iterating over array key-value pairs. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.entries(); + +// Iterate over key-value pairs... +var v = it.next().value; +// returns [ 0, 1 ] + +v = it.next().value; +// returns [ 1, 2 ] + +var bool = it.next().done; +// returns true +``` + + + +#### Uint8ClampedArray.prototype.every( predicate\[, thisArg] ) + +Tests whether all array elements pass a test implemented by a `predicate` function. + + + +```javascript +function predicate( v ) { + return ( v <= 1 ); +} + +var arr = new Uint8ClampedArray( [ 1, 2 ] ); + +var bool = arr.every( predicate ); +// returns false +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 1 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint8ClampedArray( [ 1, 2 ] ); + +var bool = arr.every( predicate, ctx ); +// returns true + +var n = ctx.count; +// returns 2 +``` + + + +#### Uint8ClampedArray.prototype.fill( value\[, start\[, end]] ) + +Fills an array from a `start` index to an `end` index (non-inclusive) with a provided `value`. + + + +```javascript +var arr = new Uint8ClampedArray( 2 ); + +// Set all array elements to the same value: +arr.fill( 2 ); + +var v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 2 + +// Set all array elements starting from the first index to the same value: +arr.fill( 3, 1 ); + +v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 3 + +// Set all array elements, except the last element, to the same value: +arr.fill( 4, 0, arr.length-1 ); + +v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 3 +``` + +When a `start` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr = new Uint8ClampedArray( 2 ); + +// Set all array elements, except the last element, to the same value: +arr.fill( 2, -arr.length, -1 ); + +var v = arr[ 0 ]; +// returns 2 + +v = arr[ 1 ]; +// returns 0 +``` + + + +#### Uint8ClampedArray.prototype.filter( predicate\[, thisArg] ) + +Creates a new array (of the same data type as the host array) which includes those elements for which a `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v >= 2 ); +} + +var arr1 = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate ); +// returns [ 2, 3 ] +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns an empty array. + + + +```javascript +function predicate( v ) { + return ( v >= 10 ); +} + +var arr1 = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate ); +// returns [] +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr1 = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var arr2 = arr1.filter( predicate, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint8ClampedArray.prototype.find( predicate\[, thisArg] ) + +Returns the first array element for which a provided `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v > 2 ); +} + +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var v = arr.find( predicate ); +// returns 3 +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns `undefined`. + + + +```javascript +function predicate( v ) { + return ( v < 1 ); +} + +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var v = arr.find( predicate ); +// returns undefined +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v > 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var v = arr.find( predicate, ctx ); +// returns 3 + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint8ClampedArray.prototype.findIndex( predicate\[, thisArg] ) + +Returns the index of the first array element for which a provided `predicate` function returns a truthy value. + + + +```javascript +function predicate( v ) { + return ( v >= 3 ); +} + +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate ); +// returns 2 +``` + +If a `predicate` function does not return a truthy value for any array element, the method returns `-1`. + + + +```javascript +function predicate( v ) { + return ( v < 1 ); +} + +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate ); +// returns -1 +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 3 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var idx = arr.findIndex( predicate, ctx ); +// returns 2 + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint8ClampedArray.prototype.forEach( fcn\[, thisArg] ) + +Invokes a callback for each array element. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var str = ''; + +function fcn( v, i ) { + str += i + ':' + v; + if ( i < arr.length-1 ) { + str += ' '; + } +} + +arr.forEach( fcn ); + +console.log( str ); +// => '0:1 1:2 2:3' +``` + +The callback is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function fcn() { + this.count += 1; +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +arr.forEach( fcn, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint8ClampedArray.prototype.includes( searchElement\[, fromIndex] ) + +Returns a `boolean` indicating whether an array includes a search element. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var bool = arr.includes( 3 ); +// returns true + +bool = arr.includes( 0 ); +// returns false +``` + +By default, the method searches the entire array (`fromIndex = 0`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var bool = arr.includes( 1, 1 ); +// returns false +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +bool = arr.includes( 1, -2 ); +// returns false +``` + + + +#### Uint8ClampedArray.prototype.indexOf( searchElement\[, fromIndex] ) + +Returns the index of the first array element strictly equal to a search element. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 3 ); +// returns 2 + +idx = arr.indexOf( 0 ); +// returns -1 +``` + +By default, the method searches the entire array (`fromIndex = 0`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 1, 1 ); +// returns -1 +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var idx = arr.indexOf( 1, -2 ); +// returns -1 +``` + + + +#### Uint8ClampedArray.prototype.join( \[separator] ) + +Serializes an array by joining all array elements as a string. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var str = arr.join(); +// returns '1,2,3' +``` + +By default, the method delineates array elements using a comma `,`. To specify a custom separator, provide a `separator` string. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var str = arr.join( '|' ); +// returns '1|2|3' +``` + + + +#### Uint8ClampedArray.prototype.keys() + +Returns an iterator for iterating over array keys. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.keys(); + +// Iterate over keys... +var v = it.next().value; +// returns 0 + +v = it.next().value; +// returns 1 + +var bool = it.next().done; +// returns true +``` + + + +#### Uint8ClampedArray.prototype.lastIndexOf( searchElement\[, fromIndex] ) + +Returns the index of the last array element strictly equal to a search element, iterating from right to left. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0 ); +// returns 3 + +idx = arr.lastIndexOf( 3 ); +// returns -1 +``` + +By default, the method searches the entire array (`fromIndex = -1`). To begin searching from a specific array index, provide a `fromIndex`. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0, 2 ); +// returns 1 +``` + +When a `fromIndex` is negative, the starting index is resolved relative to the last array element. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 0, 2, 0, 1 ] ); + +var idx = arr.lastIndexOf( 0, -3 ); +// returns 1 +``` + + + +#### Uint8ClampedArray.prototype.map( fcn\[, thisArg] ) + +Maps each array element to an element in a new array having the same data type as the host array. + + + +```javascript +function fcn( v ) { + return v * 2; +} + +var arr1 = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var arr2 = arr1.map( fcn ); +// returns [ 2, 4, 6 ] +``` + +A callback is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function fcn( v ) { + this.count += 1; + return v * 2; +} + +var ctx = { + 'count': 0 +}; + +var arr1 = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var arr2 = arr1.map( fcn, ctx ); + +var n = ctx.count; +// returns 3 +``` + + + +#### Uint8ClampedArray.prototype.reduce( fcn\[, initialValue] ) + +Applies a function against an accumulator and each element in an array and returns the accumulated result. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Uint8ClampedArray( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn ); +// returns 12 +``` + +If not provided an initial value, the method invokes a provided function with the first array element as the first argument and the second array element as the second argument. + +If provided an initial value, the method invokes a provided function with the initial value as the first argument and the first array element as the second argument. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Uint8ClampedArray( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn, 0 ); +// returns 14 +``` + +A callback is provided four arguments: + +- `acc`: accumulated result +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + + + +#### Uint8ClampedArray.prototype.reduceRight( fcn\[, initialValue] ) + +Applies a function against an accumulator and each element in an array and returns the accumulated result, iterating from right to left. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Uint8ClampedArray( [ 2, 1, 3 ] ); + +var v = arr.reduceRight( fcn ); +// returns 8 +``` + +If not provided an initial value, the method invokes a provided function with the last array element as the first argument and the second-to-last array element as the second argument. + +If provided an initial value, the method invokes a provided function with the initial value as the first argument and the last array element as the second argument. + + + +```javascript +function fcn( acc, v ) { + return acc + ( v*v ); +} + +var arr = new Uint8ClampedArray( [ 2, 1, 3 ] ); + +var v = arr.reduce( fcn, 0 ); +// returns 14 +``` + +A callback is provided four arguments: + +- `acc`: accumulated result +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + + + +#### Uint8ClampedArray.prototype.reverse() + +Reverses an array **in-place** (thus mutating the array on which the method is invoked). + + + +```javascript +var arr = new Uint8ClampedArray( [ 2, 0, 3 ] ); + +// Reverse the array: +arr.reverse(); + +var v = arr[ 0 ]; +// returns 3 + +v = arr[ 1 ]; +// returns 0 + +v = arr[ 2 ]; +// returns 2 +``` + + + +#### Uint8ClampedArray.prototype.set( arr\[, offset] ) + +Sets array elements. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); +// returns [ 1, 2, 3 ] + +// Set the first two array elements: +arr.set( [ 4, 5 ] ); + +var v = arr[ 0 ]; +// returns 4 + +v = arr[ 1 ]; +// returns 5 +``` + +By default, the method starts writing values at the first array index. To specify an alternative index, provide an index `offset`. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); +// returns [ 1, 2, 3 ] + +// Set the last two array elements: +arr.set( [ 4, 5 ], 1 ); + +var v = arr[ 1 ]; +// returns 4 + +v = arr[ 2 ]; +// returns 5 +``` + + + +#### Uint8ClampedArray.prototype.slice( \[begin\[, end]] ) + +Copies array elements to a new array with the same underlying data type as the host array. + + + +```javascript +var arr1 = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice(); + +var bool = ( arr1 === arr2 ); +// returns false + +bool = ( arr1.buffer === arr2.buffer ); +// returns false + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 + +v = arr2[ 2 ]; +// returns 3 +``` + +By default, the method copies elements beginning with the first array element. To specify an alternative array index at which to begin copying, provide a `begin` index (inclusive). + + + +```javascript +var arr1 = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( 1 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 2 + +v = arr2[ 1 ]; +// returns 3 +``` + +By default, the method copies all array elements after `begin`. To specify an alternative array index at which to end copying, provide an `end` index (exclusive). + + + +```javascript +var arr1 = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( 0, 2 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 +``` + +When a `begin` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr1 = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var arr2 = arr1.slice( -arr1.length, -1 ); + +var len = arr2.length; +// returns 2 + +var v = arr2[ 0 ]; +// returns 1 + +v = arr2[ 1 ]; +// returns 2 +``` + + + +#### Uint8ClampedArray.prototype.some( predicate\[, thisArg] ) + +Tests whether at least one array element passes a test implemented by a `predicate` function. + + + +```javascript +function predicate( v ) { + return ( v >= 2 ); +} + +var arr = new Uint8ClampedArray( [ 1, 2 ] ); + +var bool = arr.some( predicate ); +// returns true +``` + +A `predicate` function is provided three arguments: + +- `value`: array element +- `index`: array index +- `arr`: array on which the method is invoked + +To set the callback execution context, provide a `thisArg`. + + + +```javascript +function predicate( v ) { + this.count += 1; + return ( v >= 2 ); +} + +var ctx = { + 'count': 0 +}; + +var arr = new Uint8ClampedArray( [ 1, 1 ] ); + +var bool = arr.some( predicate, ctx ); +// returns false + +var n = ctx.count; +// returns 2 +``` + + + +#### Uint8ClampedArray.prototype.sort( \[compareFunction] ) + +Sorts an array **in-place** (thus mutating the array on which the method is invoked). + + + +```javascript +var arr = new Uint8ClampedArray( [ 2, 3, 0 ] ); + +// Sort the array (in ascending order): +arr.sort(); + +var v = arr[ 0 ]; +// returns 0 + +v = arr[ 1 ]; +// returns 2 + +v = arr[ 2 ]; +// returns 3 +``` + +By default, the method sorts array elements in ascending order. To impose a custom order, provide a `compareFunction`. + + + +```javascript +function descending( a, b ) { + return b - a; +} + +var arr = new Uint8ClampedArray( [ 2, 3, 0 ] ); + +// Sort the array (in descending order): +arr.sort( descending ); + +var v = arr[ 0 ]; +// returns 3 + +v = arr[ 1 ]; +// returns 2 + +v = arr[ 2 ]; +// returns 0 +``` + +The comparison function is provided two array elements, `a` and `b`, per invocation, and its return value determines the sort order as follows: + +- If the comparison function returns a value **less** than zero, then the method sorts `a` to an index lower than `b` (i.e., `a` should come **before** `b`). +- If the comparison function returns a value **greater** than zero, then the method sorts `a` to an index higher than `b` (i.e., `b` should come **before** `a`). +- If the comparison function returns **zero**, then the relative order of `a` and `b` _should_ remain unchanged. + + + +#### Uint8ClampedArray.prototype.subarray( \[begin\[, end]] ) + +Creates a new typed array view over the same underlying [`ArrayBuffer`][@stdlib/array/buffer] and with the same underlying data type as the host array. + + + +```javascript +var arr1 = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray(); +// returns [ 1, 2, 3 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +By default, the method creates a typed array view beginning with the first array element. To specify an alternative array index at which to begin, provide a `begin` index (inclusive). + + + +```javascript +var arr1 = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 1 ); +// returns [ 2, 3 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +By default, the method creates a typed array view which includes all array elements after `begin`. To limit the number of array elements after `begin`, provide an `end` index (exclusive). + + + +```javascript +var arr1 = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 0, 2 ); +// returns [ 1, 2 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +When a `begin` and/or `end` index is negative, the respective index is determined relative to the last array element. + + + +```javascript +var arr1 = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( -arr1.length, -1 ); +// returns [ 1, 2 ] + +var bool = ( arr1.buffer === arr2.buffer ); +// returns true +``` + +If the method is unable to resolve indices to a non-empty array subsequence, the method returns an empty typed array. + + + +```javascript +var arr1 = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var arr2 = arr1.subarray( 10, -1 ); +// returns [] +``` + + + +#### Uint8ClampedArray.prototype.toLocaleString( \[locales\[, options]] ) + +Serializes an array as a locale-specific `string`. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var str = arr.toLocaleString(); +// returns '1,2,3' +``` + + + +#### Uint8ClampedArray.prototype.toString() + +Serializes an array as a `string`. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 2, 3 ] ); + +var str = arr.toString(); +// returns '1,2,3' +``` + + + +#### Uint8ClampedArray.prototype.values() + +Returns an iterator for iterating over array elements. + + + +```javascript +var arr = new Uint8ClampedArray( [ 1, 2 ] ); + +// Create an iterator: +var it = arr.values(); + +// Iterate over array elements... +var v = it.next().value; +// returns 1 + +v = it.next().value; +// returns 2 + +var bool = it.next().done; +// returns true +``` + +
+ + + +* * * + + + +
+ +
+ + + + + +
+ +## Examples + + + +```javascript +var randu = require( '@stdlib/random/base/randu' ); +var round = require( '@stdlib/math/base/special/round' ); +var ctor = require( '@stdlib/array/uint8c' ); + +var arr; +var i; + +arr = new ctor( 10 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = round( randu()*100.0 ); +} +console.log( arr ); +``` + +
+ + + + + +
+ +
+ + + + + + + + diff --git a/uint8c/benchmark/benchmark.copy_within.js b/uint8c/benchmark/benchmark.copy_within.js new file mode 100644 index 00000000..e2731bd2 --- /dev/null +++ b/uint8c/benchmark/benchmark.copy_within.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':copyWithin', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr[ 0 ] = v; + arr = arr.copyWithin( 1, 0 ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/benchmark/benchmark.copy_within.length.js b/uint8c/benchmark/benchmark.copy_within.length.js new file mode 100644 index 00000000..bd70626c --- /dev/null +++ b/uint8c/benchmark/benchmark.copy_within.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8ClampedArray( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr[ 0 ] = v; + arr = arr.copyWithin( 1, 0 ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':copyWithin:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.data.js b/uint8c/benchmark/benchmark.data.js new file mode 100644 index 00000000..5cbb9007 --- /dev/null +++ b/uint8c/benchmark/benchmark.data.js @@ -0,0 +1,75 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::get,index', function benchmark( b ) { + var arr; + var N; + var v; + var i; + + arr = new Uint8ClampedArray( 2 ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr[ i%N ]; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::set,index', function benchmark( b ) { + var arr; + var N; + var i; + + arr = new Uint8ClampedArray( 2 ); + N = arr.length; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ i%N ] = i; + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] || arr[ 1 ] !== arr[ 1 ] ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/benchmark/benchmark.entries.js b/uint8c/benchmark/benchmark.entries.js new file mode 100644 index 00000000..0b2af25f --- /dev/null +++ b/uint8c/benchmark/benchmark.entries.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':entries', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Uint8ClampedArray( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.entries(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/benchmark/benchmark.every.js b/uint8c/benchmark/benchmark.every.js new file mode 100644 index 00000000..c2dea91d --- /dev/null +++ b/uint8c/benchmark/benchmark.every.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':every', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); + +bench( pkg+'::this_context:every', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate, {} ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); diff --git a/uint8c/benchmark/benchmark.every.length.js b/uint8c/benchmark/benchmark.every.length.js new file mode 100644 index 00000000..0ec67464 --- /dev/null +++ b/uint8c/benchmark/benchmark.every.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value >= 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8ClampedArray( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.every( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':every:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.fill.js b/uint8c/benchmark/benchmark.fill.js new file mode 100644 index 00000000..d9810959 --- /dev/null +++ b/uint8c/benchmark/benchmark.fill.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':fill', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr = arr.fill( v ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/benchmark/benchmark.fill.length.js b/uint8c/benchmark/benchmark.fill.length.js new file mode 100644 index 00000000..60c5757a --- /dev/null +++ b/uint8c/benchmark/benchmark.fill.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8ClampedArray( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = i % 128; + arr = arr.fill( v ); + if ( arr[ 0 ] !== v ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( arr[ 0 ] !== arr[ 0 ] ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':fill:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.filter.js b/uint8c/benchmark/benchmark.filter.js new file mode 100644 index 00000000..e1c52ee7 --- /dev/null +++ b/uint8c/benchmark/benchmark.filter.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':filter', function benchmark( b ) { + var arr; + var out; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( out ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); + +bench( pkg+'::this_context:filter', function benchmark( b ) { + var arr; + var out; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate, {} ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( out ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v >= 0; + } +}); diff --git a/uint8c/benchmark/benchmark.filter.length.js b/uint8c/benchmark/benchmark.filter.length.js new file mode 100644 index 00000000..dffa04ec --- /dev/null +++ b/uint8c/benchmark/benchmark.filter.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value >= 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8ClampedArray( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.filter( predicate ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( out ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':filter:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.find.js b/uint8c/benchmark/benchmark.find.js new file mode 100644 index 00000000..d1f8b343 --- /dev/null +++ b/uint8c/benchmark/benchmark.find.js @@ -0,0 +1,82 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':find', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:find', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate, {} ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/uint8c/benchmark/benchmark.find.length.js b/uint8c/benchmark/benchmark.find.length.js new file mode 100644 index 00000000..bbdca594 --- /dev/null +++ b/uint8c/benchmark/benchmark.find.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - tuple length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8ClampedArray( len ); + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.find( predicate ); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof out !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':find:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.find_index.js b/uint8c/benchmark/benchmark.find_index.js new file mode 100644 index 00000000..439909a4 --- /dev/null +++ b/uint8c/benchmark/benchmark.find_index.js @@ -0,0 +1,82 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':findIndex', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:findIndex', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate, {} ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/uint8c/benchmark/benchmark.find_index.length.js b/uint8c/benchmark/benchmark.find_index.length.js new file mode 100644 index 00000000..5aadd9b1 --- /dev/null +++ b/uint8c/benchmark/benchmark.find_index.length.js @@ -0,0 +1,104 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8ClampedArray( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.findIndex( predicate ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':findIndex:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.for_each.js b/uint8c/benchmark/benchmark.for_each.js new file mode 100644 index 00000000..0666c43c --- /dev/null +++ b/uint8c/benchmark/benchmark.for_each.js @@ -0,0 +1,88 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':forEach', function benchmark( b ) { + var count; + var arr; + var N; + var i; + + arr = new Uint8ClampedArray( 2 ); + N = arr.length; + + count = 0; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn ); + if ( count !== N*(i+1) ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( count !== N*i ) { + b.fail( 'unexpected result' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn() { + count += 1; + } +}); + +bench( pkg+'::this_context:forEach', function benchmark( b ) { + var count; + var arr; + var N; + var i; + + arr = new Uint8ClampedArray( 2 ); + N = arr.length; + + count = 0; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn, {} ); + if ( count !== N*(i+1) ) { + b.fail( 'unexpected result' ); + } + } + b.toc(); + if ( count !== N*i ) { + b.fail( 'unexpected result' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn() { + count += 1; + } +}); diff --git a/uint8c/benchmark/benchmark.for_each.length.js b/uint8c/benchmark/benchmark.for_each.length.js new file mode 100644 index 00000000..e24aed6a --- /dev/null +++ b/uint8c/benchmark/benchmark.for_each.length.js @@ -0,0 +1,106 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var count; + var arr; + + arr = new Uint8ClampedArray( len ); + count = 0; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr.forEach( fcn ); + if ( count !== count ) { + b.fail( 'should not be NaN' ); + } + } + b.toc(); + if ( count !== count ) { + b.fail( 'should not be NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } + + /** + * Callback invoked for each tuple element. + * + * @private + */ + function fcn() { + count += 1; + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':forEach:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.from.js b/uint8c/benchmark/benchmark.from.js new file mode 100644 index 00000000..9ed431a3 --- /dev/null +++ b/uint8c/benchmark/benchmark.from.js @@ -0,0 +1,237 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var ITERATOR_SYMBOL = require( '@stdlib/symbol/iterator' ); +var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// VARIABLES // + +var opts = { + 'skip': ( ITERATOR_SYMBOL === null ) +}; + + +// MAIN // + +bench( pkg+'::typed_array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Uint8ClampedArray( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint8ClampedArray.from( buf ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( arr ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array,clbk:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = new Uint8ClampedArray( [ 1, 2 ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint8ClampedArray.from( buf, clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( arr ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1; + } +}); + +bench( pkg+'::array:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1, 2 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint8ClampedArray.from( buf ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( arr ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::array,clbk:from', function benchmark( b ) { + var buf; + var arr; + var i; + + buf = [ 1, 2 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint8ClampedArray.from( buf, clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( arr ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function clbk( v ) { + return v + 1; + } +}); + +bench( pkg+'::iterable:from', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint8ClampedArray.from( createIterable() ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( arr ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out; + var i; + + out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + + i = 0; + + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + i += 1; + if ( i <= 2 ) { + return { + 'value': 0, + 'done': false + }; + } + return { + 'done': true + }; + } + } +}); + +bench( pkg+'::iterable,clbk:from:', opts, function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint8ClampedArray.from( createIterable(), clbk ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( arr ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function createIterable() { + var out; + var i; + + out = {}; + out[ ITERATOR_SYMBOL ] = iterator; + + i = 0; + + return out; + + function iterator() { + return { + 'next': next + }; + } + + function next() { + i += 1; + if ( i <= 2 ) { + return { + 'value': 1, + 'done': false + }; + } + return { + 'done': true + }; + } + } + + function clbk( v ) { + return v + 1; + } +}); diff --git a/uint8c/benchmark/benchmark.includes.js b/uint8c/benchmark/benchmark.includes.js new file mode 100644 index 00000000..b709e50c --- /dev/null +++ b/uint8c/benchmark/benchmark.includes.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':includes', function benchmark( b ) { + var bool; + var arr; + var v; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + bool = arr.includes( v ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/benchmark/benchmark.includes.length.js b/uint8c/benchmark/benchmark.includes.length.js new file mode 100644 index 00000000..d6ff5c71 --- /dev/null +++ b/uint8c/benchmark/benchmark.includes.length.js @@ -0,0 +1,96 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8ClampedArray( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + bool = arr.includes( v ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':includes:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.index_of.js b/uint8c/benchmark/benchmark.index_of.js new file mode 100644 index 00000000..8cb37832 --- /dev/null +++ b/uint8c/benchmark/benchmark.index_of.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':indexOf', function benchmark( b ) { + var out; + var arr; + var v; + var i; + + arr = new Uint8ClampedArray( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.indexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/benchmark/benchmark.index_of.length.js b/uint8c/benchmark/benchmark.index_of.length.js new file mode 100644 index 00000000..9b55a7f8 --- /dev/null +++ b/uint8c/benchmark/benchmark.index_of.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8ClampedArray( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.indexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':indexOf:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.join.js b/uint8c/benchmark/benchmark.join.js new file mode 100644 index 00000000..ee4ac625 --- /dev/null +++ b/uint8c/benchmark/benchmark.join.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':join', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i % 127; + out = arr.join(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/benchmark/benchmark.join.length.js b/uint8c/benchmark/benchmark.join.length.js new file mode 100644 index 00000000..7b7c9d89 --- /dev/null +++ b/uint8c/benchmark/benchmark.join.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8ClampedArray( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i % 127; + out = arr.join(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':join:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.js b/uint8c/benchmark/benchmark.js new file mode 100644 index 00000000..19af7aad --- /dev/null +++ b/uint8c/benchmark/benchmark.js @@ -0,0 +1,47 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// MAIN // + +bench( pkg, function benchmark( b ) { + var arr; + var i; + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new ctor( 0 ); + if ( arr.length !== 0 ) { + b.fail( 'should have length 0' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( arr ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/benchmark/benchmark.keys.js b/uint8c/benchmark/benchmark.keys.js new file mode 100644 index 00000000..9f472e0b --- /dev/null +++ b/uint8c/benchmark/benchmark.keys.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':keys', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.keys(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/benchmark/benchmark.last_index_of.js b/uint8c/benchmark/benchmark.last_index_of.js new file mode 100644 index 00000000..97746402 --- /dev/null +++ b/uint8c/benchmark/benchmark.last_index_of.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':lastIndexOf', function benchmark( b ) { + var out; + var arr; + var v; + var i; + + arr = new Uint8ClampedArray( 2 ); + + // Benchmark worst case scenario... + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.lastIndexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/benchmark/benchmark.last_index_of.length.js b/uint8c/benchmark/benchmark.last_index_of.length.js new file mode 100644 index 00000000..e509fd02 --- /dev/null +++ b/uint8c/benchmark/benchmark.last_index_of.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8ClampedArray( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = (i%127) + 1; + out = arr.lastIndexOf( v ); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + } + b.toc(); + if ( out !== -1 ) { + b.fail( 'should return -1' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':lastIndexOf:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.length.js b/uint8c/benchmark/benchmark.length.js new file mode 100644 index 00000000..faf73d88 --- /dev/null +++ b/uint8c/benchmark/benchmark.length.js @@ -0,0 +1,93 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); +var pkg = require( './../package.json' ).name; +var ctor = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = new ctor( len ); + if ( arr.length !== len ) { + b.fail( 'unexpected length' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( arr ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.map.js b/uint8c/benchmark/benchmark.map.js new file mode 100644 index 00000000..a28681c8 --- /dev/null +++ b/uint8c/benchmark/benchmark.map.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':map', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( out ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); + +bench( pkg+'::this_context:map', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn, {} ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( out ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/uint8c/benchmark/benchmark.map.length.js b/uint8c/benchmark/benchmark.map.length.js new file mode 100644 index 00000000..40011ea5 --- /dev/null +++ b/uint8c/benchmark/benchmark.map.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Maps an array element to a new value. +* +* @private +* @param {*} value - array element +* @returns {*} new value +*/ +function fcn( value ) { + return value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8ClampedArray( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.map( fcn ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( out ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':map:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.of.js b/uint8c/benchmark/benchmark.of.js new file mode 100644 index 00000000..41b32ac8 --- /dev/null +++ b/uint8c/benchmark/benchmark.of.js @@ -0,0 +1,48 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':of', function benchmark( b ) { + var arr; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr = Uint8ClampedArray.of( i, 2 ); + if ( arr.length !== 2 ) { + b.fail( 'should have length 2' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( arr ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/benchmark/benchmark.properties.js b/uint8c/benchmark/benchmark.properties.js new file mode 100644 index 00000000..ca8f308c --- /dev/null +++ b/uint8c/benchmark/benchmark.properties.js @@ -0,0 +1,145 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isArrayBuffer = require( '@stdlib/assert/is-arraybuffer' ); +var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::get:buffer', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.buffer; + if ( typeof v !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isArrayBuffer( v ) ) { + b.fail( 'should return an ArrayBuffer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteLength', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteLength; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:byteOffset', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.byteOffset; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:BYTES_PER_ELEMENT', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.BYTES_PER_ELEMENT; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::get:length', function benchmark( b ) { + var arr; + var v; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + // Note: the following may be optimized away due to loop invariant code motion and/or other compiler optimizations, rendering this benchmark meaningless... + v = arr.length; + if ( v !== v ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( !isNonNegativeInteger( v ) ) { + b.fail( 'should return a nonnegative integer' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/benchmark/benchmark.reduce.js b/uint8c/benchmark/benchmark.reduce.js new file mode 100644 index 00000000..b28a5ddb --- /dev/null +++ b/uint8c/benchmark/benchmark.reduce.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reduce', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( acc, v ) { + return acc + v + 1; + } +}); + +bench( pkg+'::initial_value:reduce', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn, 3 ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/uint8c/benchmark/benchmark.reduce.length.js b/uint8c/benchmark/benchmark.reduce.length.js new file mode 100644 index 00000000..eb3e2e50 --- /dev/null +++ b/uint8c/benchmark/benchmark.reduce.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Updates an accumulated value. +* +* @private +* @param {*} acc - accumulated value +* @param {*} value - array element +* @returns {*} accumulated value +*/ +function fcn( acc, value ) { + return acc + value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8ClampedArray( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduce( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reduce:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.reduce_right.js b/uint8c/benchmark/benchmark.reduce_right.js new file mode 100644 index 00000000..0e2cefa2 --- /dev/null +++ b/uint8c/benchmark/benchmark.reduce_right.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reduceRight', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( acc, v ) { + return acc + v + 1; + } +}); + +bench( pkg+'::initial_value:reduceRight', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn, 3 ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function fcn( v ) { + return v + 1; + } +}); diff --git a/uint8c/benchmark/benchmark.reduce_right.length.js b/uint8c/benchmark/benchmark.reduce_right.length.js new file mode 100644 index 00000000..cd48ec9e --- /dev/null +++ b/uint8c/benchmark/benchmark.reduce_right.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Updates an accumulated value. +* +* @private +* @param {*} acc - accumulated value +* @param {*} value - array element +* @returns {*} accumulated value +*/ +function fcn( acc, value ) { + return acc + value + 1; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8ClampedArray( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.reduceRight( fcn ); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( out !== out ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reduceRight:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.reverse.js b/uint8c/benchmark/benchmark.reverse.js new file mode 100644 index 00000000..17e6ec0e --- /dev/null +++ b/uint8c/benchmark/benchmark.reverse.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':reverse', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.reverse(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( out ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/benchmark/benchmark.reverse.length.js b/uint8c/benchmark/benchmark.reverse.length.js new file mode 100644 index 00000000..6e77be0c --- /dev/null +++ b/uint8c/benchmark/benchmark.reverse.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8ClampedArray( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.reverse(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( out ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':reverse:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.set.js b/uint8c/benchmark/benchmark.set.js new file mode 100644 index 00000000..f4076722 --- /dev/null +++ b/uint8c/benchmark/benchmark.set.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::array:set', function benchmark( b ) { + var values; + var buf; + var arr; + var N; + var v; + var i; + + values = []; + for ( i = 0; i < 10; i++ ) { + values.push( i ); + } + N = values.length; + + arr = new Uint8ClampedArray( 2 ); + buf = [ 0 ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = values[ i%N ]; + v = arr.set( buf ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::typed_array:set', function benchmark( b ) { + var values; + var buf; + var arr; + var N; + var v; + var i; + + values = new Uint8ClampedArray( 20 ); + N = values.length; + for ( i = 0; i < N; i++ ) { + values[ i ] = i; + } + + arr = new Uint8ClampedArray( 2 ); + buf = new Uint8ClampedArray( 1 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + buf[ 0 ] = values[ i%N ]; + v = arr.set( buf ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/benchmark/benchmark.set.length.js b/uint8c/benchmark/benchmark.set.length.js new file mode 100644 index 00000000..8aa89388 --- /dev/null +++ b/uint8c/benchmark/benchmark.set.length.js @@ -0,0 +1,114 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randi = require( '@stdlib/random/base/randi' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var values; + var arr1; + var arr2; + var arr; + var N; + var i; + + arr1 = []; + arr2 = []; + for ( i = 0; i < len; i++ ) { + arr1.push( randi() ); + arr2.push( randi() ); + } + arr = new Uint8ClampedArray( len ); + + values = [ + arr1, + arr2 + ]; + N = values.length; + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var v; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + v = arr.set( values[ i%N ] ); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + } + b.toc(); + if ( typeof v !== 'undefined' ) { + b.fail( 'should return undefined' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':set:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.slice.js b/uint8c/benchmark/benchmark.slice.js new file mode 100644 index 00000000..d1e0cda9 --- /dev/null +++ b/uint8c/benchmark/benchmark.slice.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':slice', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.slice(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( out ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/benchmark/benchmark.slice.length.js b/uint8c/benchmark/benchmark.slice.length.js new file mode 100644 index 00000000..82e5f691 --- /dev/null +++ b/uint8c/benchmark/benchmark.slice.length.js @@ -0,0 +1,95 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8ClampedArray( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.slice(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( out ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':slice:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.some.js b/uint8c/benchmark/benchmark.some.js new file mode 100644 index 00000000..ad545e25 --- /dev/null +++ b/uint8c/benchmark/benchmark.some.js @@ -0,0 +1,81 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':some', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); + +bench( pkg+'::this_context:some', function benchmark( b ) { + var bool; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate, {} ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + + function predicate( v ) { + return v > 0; + } +}); diff --git a/uint8c/benchmark/benchmark.some.length.js b/uint8c/benchmark/benchmark.some.length.js new file mode 100644 index 00000000..79f4623f --- /dev/null +++ b/uint8c/benchmark/benchmark.some.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Returns a boolean indicating whether an array element passes a test. +* +* @private +* @param {*} value - value to test +* @returns {boolean} boolean indicating whether an array element passes a test +*/ +function predicate( value ) { + return value > 0; +} + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8ClampedArray( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var bool; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + bool = arr.some( predicate ); + if ( typeof bool !== 'boolean' ) { + b.fail( 'should return a boolean' ); + } + } + b.toc(); + if ( !isBoolean( bool ) ) { + b.fail( 'should return a boolean' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':some:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.sort.js b/uint8c/benchmark/benchmark.sort.js new file mode 100644 index 00000000..291a1735 --- /dev/null +++ b/uint8c/benchmark/benchmark.sort.js @@ -0,0 +1,53 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var randi = require( '@stdlib/random/base/randi' ); +var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':sort', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8ClampedArray( [ randi(), randi() ] ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = randi(); + out = arr.sort(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( out ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/benchmark/benchmark.sort.length.js b/uint8c/benchmark/benchmark.sort.length.js new file mode 100644 index 00000000..cc519786 --- /dev/null +++ b/uint8c/benchmark/benchmark.sort.length.js @@ -0,0 +1,105 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var randi = require( '@stdlib/random/base/randi' ); +var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var data; + var arr; + var i; + + data = []; + for ( i = 0; i < len; i++ ) { + data.push( randi() ); + } + arr = new Uint8ClampedArray( data ); + + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ i%len ] = randi(); + out = arr.sort(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( out ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':sort:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.subarray.js b/uint8c/benchmark/benchmark.subarray.js new file mode 100644 index 00000000..6fac854f --- /dev/null +++ b/uint8c/benchmark/benchmark.subarray.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':subarray', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.subarray(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( out ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/benchmark/benchmark.subarray.length.js b/uint8c/benchmark/benchmark.subarray.length.js new file mode 100644 index 00000000..70c5d0c4 --- /dev/null +++ b/uint8c/benchmark/benchmark.subarray.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8ClampedArray( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = arr.subarray(); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isUint8ClampedArray( out ) ) { + b.fail( 'should return a Uint8ClampedArray' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':subarray:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.to_locale_string.js b/uint8c/benchmark/benchmark.to_locale_string.js new file mode 100644 index 00000000..d214048e --- /dev/null +++ b/uint8c/benchmark/benchmark.to_locale_string.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':toLocaleString', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toLocaleString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/benchmark/benchmark.to_locale_string.length.js b/uint8c/benchmark/benchmark.to_locale_string.length.js new file mode 100644 index 00000000..0963f1db --- /dev/null +++ b/uint8c/benchmark/benchmark.to_locale_string.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8ClampedArray( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toLocaleString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':toLocaleString:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.to_string.js b/uint8c/benchmark/benchmark.to_string.js new file mode 100644 index 00000000..0eb5fa46 --- /dev/null +++ b/uint8c/benchmark/benchmark.to_string.js @@ -0,0 +1,51 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':toString', function benchmark( b ) { + var out; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/benchmark/benchmark.to_string.length.js b/uint8c/benchmark/benchmark.to_string.length.js new file mode 100644 index 00000000..d0eaa01f --- /dev/null +++ b/uint8c/benchmark/benchmark.to_string.length.js @@ -0,0 +1,94 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var arr = new Uint8ClampedArray( len ); + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var out; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + arr[ 0 ] = i; + out = arr.toString(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + } + b.toc(); + if ( typeof out !== 'string' ) { + b.fail( 'should return a string' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 5; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+':toString:len='+len, f ); + } +} + +main(); diff --git a/uint8c/benchmark/benchmark.values.js b/uint8c/benchmark/benchmark.values.js new file mode 100644 index 00000000..64345b08 --- /dev/null +++ b/uint8c/benchmark/benchmark.values.js @@ -0,0 +1,50 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var pkg = require( './../package.json' ).name; +var Uint8ClampedArray = require( './../lib' ); + + +// MAIN // + +bench( pkg+':values', function benchmark( b ) { + var iter; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + iter = arr.values(); + if ( typeof iter !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( typeof iter !== 'object' || typeof iter.next !== 'function' ) { + b.fail( 'should return an iterator protocol-compliant object' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/uint8c/docs/repl.txt b/uint8c/docs/repl.txt new file mode 100644 index 00000000..6a6ff10a --- /dev/null +++ b/uint8c/docs/repl.txt @@ -0,0 +1,953 @@ + +{{alias}}() + A typed array constructor which returns a typed array representing an array + of 8-bit unsigned integers in the platform byte order clamped to 0-255. + + Returns + ------- + out: Uint8ClampedArray + A typed array. + + Examples + -------- + > var arr = new {{alias}}() + + + +{{alias}}( length ) + Returns a typed array having a specified length. + + Parameters + ---------- + length: integer + Typed array length. + + Returns + ------- + out: Uint8ClampedArray + A typed array. + + Examples + -------- + > var arr = new {{alias}}( 5 ) + [ 0, 0, 0, 0, 0 ] + + +{{alias}}( typedarray ) + Creates a typed array from another typed array. + + Parameters + ---------- + typedarray: TypedArray + Typed array from which to generate another typed array. + + Returns + ------- + out: Uint8ClampedArray + A typed array. + + Examples + -------- + > var arr1 = new {{alias:@stdlib/array/int32}}( [ 5, 5, 5 ] ); + > var arr2 = new {{alias}}( arr1 ) + [ 5, 5, 5 ] + + +{{alias}}( obj ) + Creates a typed array from an array-like object or iterable. + + Parameters + ---------- + obj: Object + Array-like object or iterable from which to generate a typed array. + + Returns + ------- + out: Uint8ClampedArray + A typed array. + + Examples + -------- + > var arr1 = [ 5.0, 5.0, 5.0 ]; + > var arr2 = new {{alias}}( arr1 ) + [ 5, 5, 5 ] + + +{{alias}}( buffer[, byteOffset[, length]] ) + Returns a typed array view of an ArrayBuffer. + + Parameters + ---------- + buffer: ArrayBuffer + Underlying ArrayBuffer. + + byteOffset: integer (optional) + Integer byte offset specifying the location of the first typed array + element. Default: 0. + + length: integer (optional) + View length. If not provided, the view spans from the byteOffset to + the end of the underlying ArrayBuffer. + + Returns + ------- + out: Uint8ClampedArray + A typed array. + + Examples + -------- + > var buf = new {{alias:@stdlib/array/buffer}}( 4 ); + > var arr = new {{alias}}( buf, 0, 4 ) + [ 0, 0, 0, 0 ] + + +{{alias}}.from( src[, map[, thisArg]] ) + Creates a new typed array from an array-like object or an iterable. + + A callback is provided the following arguments: + + - value: source value. + - index: source index. + + Parameters + ---------- + src: ArrayLike|Iterable + Source of array elements. + + map: Function (optional) + Callback to invoke for each source element. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Uint8ClampedArray + A typed array. + + Examples + -------- + > function mapFcn( v ) { return v * 2; }; + > var arr = {{alias}}.from( [ 1, 2 ], mapFcn ) + [ 2, 4 ] + + +{{alias}}.of( element0[, element1[, ...elementN]] ) + Creates a new typed array from a variable number of arguments. + + Parameters + ---------- + element0: number + Array element. + + element1: number (optional) + Array element. + + elementN: number (optional) + Array elements. + + Returns + ------- + out: Uint8ClampedArray + A typed array. + + Examples + -------- + > var arr = {{alias}}.of( 1, 2 ) + [ 1, 2 ] + + +{{alias}}.BYTES_PER_ELEMENT + Number of bytes per view element. + + Examples + -------- + > {{alias}}.BYTES_PER_ELEMENT + 1 + + +{{alias}}.name + Typed array constructor name. + + Examples + -------- + > {{alias}}.name + 'Uint8ClampedArray' + + +{{alias}}.prototype.buffer + Read-only property which returns the ArrayBuffer referenced by the typed + array. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.buffer + + + +{{alias}}.prototype.byteLength + Read-only property which returns the length (in bytes) of the typed array. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.byteLength + 5 + + +{{alias}}.prototype.byteOffset + Read-only property which returns the offset (in bytes) of the typed array + from the start of its ArrayBuffer. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.byteOffset + 0 + + +{{alias}}.prototype.BYTES_PER_ELEMENT + Number of bytes per view element. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.BYTES_PER_ELEMENT + 1 + + +{{alias}}.prototype.length + Read-only property which returns the number of view elements. + + Examples + -------- + > var arr = new {{alias}}( 5 ); + > arr.length + 5 + + +{{alias}}.prototype.copyWithin( target, start[, end] ) + Copies a sequence of elements within the array starting at `start` and + ending at `end` (non-inclusive) to the position starting at `target`. + + Parameters + ---------- + target: integer + Target start index position. + + start: integer + Source start index position. + + end: integer (optional) + Source end index position. Default: out.length. + + Returns + ------- + out: Uint8ClampedArray + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3, 4, 5 ] ); + > arr.copyWithin( 3, 0, 2 ); + > arr[ 3 ] + 1 + > arr[ 4 ] + 2 + + +{{alias}}.prototype.entries() + Returns an iterator for iterating over array key-value pairs. + + Returns + ------- + iter: Iterator + Iterator for iterating over array key-value pairs. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.entries(); + > it.next().value + [ 0, 1 ] + > it.next().value + [ 1, 2 ] + > it.next().done + true + + +{{alias}}.prototype.every( predicate[, thisArg] ) + Tests whether all array elements pass a test implemented by a predicate + function. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. If a predicate function + returns a truthy value, an array element passes; otherwise, an array + element fails. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + bool: boolean + Boolean indicating whether all array elements pass. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > function predicate( v ) { return ( v <= 1 ); }; + > arr.every( predicate ) + false + + +{{alias}}.prototype.fill( value[, start[, end]] ) + Fills an array from a start index to an end index (non-inclusive) with a + provided value. + + Parameters + ---------- + value: number + Fill value. + + start: integer (optional) + Start index. If less than zero, the start index is resolved relative to + the last array element. Default: 0. + + end: integer (optional) + End index (non-inclusive). If less than zero, the end index is resolved + relative to the last array element. Default: out.length. + + Returns + ------- + out: Uint8ClampedArray + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > arr.fill( 3 ); + > arr[ 0 ] + 3 + > arr[ 1 ] + 3 + + +{{alias}}.prototype.filter( predicate[, thisArg] ) + Creates a new array which includes those elements for which a predicate + function returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + The returned array has the same data type as the host array. + + If a predicate function does not return a truthy value for any array + element, the method returns `null`. + + Parameters + ---------- + predicate: Function + Predicate function which filters array elements. If a predicate function + returns a truthy value, an array element is included in the output + array; otherwise, an array element is not included in the output array. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Uint8ClampedArray + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 1 ); }; + > var arr2 = arr1.filter( predicate ); + > arr2.length + 2 + + +{{alias}}.prototype.find( predicate[, thisArg] ) + Returns the first array element for which a provided predicate function + returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + If a predicate function never returns a truthy value, the method returns + `undefined`. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + value: number|undefined + Array element. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 2 ); }; + > var v = arr.find( predicate ) + 3 + + +{{alias}}.prototype.findIndex( predicate[, thisArg] ) + Returns the index of the first array element for which a provided predicate + function returns a truthy value. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + If a predicate function never returns a truthy value, the method returns + `-1`. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + idx: integer + Array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function predicate( v ) { return ( v > 2 ); }; + > var idx = arr.findIndex( predicate ) + 2 + + +{{alias}}.prototype.forEach( fcn[, thisArg] ) + Invokes a callback for each array element. + + A provided function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + fcn: Function + Function to invoke for each array element. + + thisArg: Any (optional) + Callback execution context. + + Examples + -------- + > var arr = new {{alias}}( [ 3, 2, 1 ] ); + > var str = ' '; + > function fcn( v, i ) { str += i + ':' + v + ' '; }; + > arr.forEach( fcn ); + > str + ' 0:3 1:2 2:1 ' + + +{{alias}}.prototype.includes( searchElement[, fromIndex] ) + Returns a boolean indicating whether an array includes a search element. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: 0. + + Returns + ------- + bool: boolean + Boolean indicating whether an array includes a search element. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > var bool = arr.includes( 4 ) + false + > bool = arr.includes( 3 ) + true + + +{{alias}}.prototype.indexOf( searchElement[, fromIndex] ) + Returns the index of the first array element strictly equal to a search + element. + + If unable to locate a search element, the method returns `-1`. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: 0. + + Returns + ------- + idx: integer + Array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > var idx = arr.indexOf( 4 ) + -1 + > idx = arr.indexOf( 3 ) + 2 + + +{{alias}}.prototype.join( [separator] ) + Serializes an array by joining all array elements as a string. + + Parameters + ---------- + separator: string (optional) + String delineating array elements. Default: ','. + + Returns + ------- + str: string + Array serialized as a string. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.join( '|' ) + '1|2|3' + + +{{alias}}.prototype.keys() + Returns an iterator for iterating over array keys. + + Returns + ------- + iter: Iterator + Iterator for iterating over array keys. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.keys(); + > it.next().value + 0 + > it.next().value + 1 + > it.next().done + true + + +{{alias}}.prototype.lastIndexOf( searchElement[, fromIndex] ) + Returns the index of the last array element strictly equal to a search + element. + + The method iterates from the last array element to the first array element. + + If unable to locate a search element, the method returns `-1`. + + Parameters + ---------- + searchElement: number + Search element. + + fromIndex: integer (optional) + Array index from which to begin searching. If provided a negative value, + the method resolves the start index relative to the last array element. + Default: -1. + + Returns + ------- + idx: integer + array index. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 0, 2, 0, 1 ] ); + > var idx = arr.lastIndexOf( 3 ) + -1 + > idx = arr.lastIndexOf( 0 ) + 3 + + +{{alias}}.prototype.map( fcn[, thisArg] ) + Maps each array element to an element in a new typed array. + + A provided function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + The returned array has the same data type as the host array. + + Parameters + ---------- + fcn: Function + Function which maps array elements to elements in the new array. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + out: Uint8ClampedArray + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( v ) { return v * 2; }; + > var arr2 = arr1.map( fcn ); + [ 2, 4, 6 ] + + +{{alias}}.prototype.reduce( fcn[, initialValue] ) + Applies a function against an accumulator and each element in an array and + returns the accumulated result. + + The provided function is provided the following arguments: + + - acc: accumulated result. + - value: current array element. + - index: index of the current array element. + - arr: array on which the method is invoked. + + If provided an initial value, the method invokes a provided function with + the initial value as the first argument and the first array element as the + second argument. + + If not provided an initial value, the method invokes a provided function + with the first array element as the first argument and the second array + element as the second argument. + + Parameters + ---------- + fcn: Function + Function to apply. + + initialValue: Any (optional) + Initial accumulation value. + + Returns + ------- + out: Any + Accumulated result. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( acc, v ) { return acc + (v*v); }; + > var v = arr.reduce( fcn, 0 ) + 14 + + +{{alias}}.prototype.reduceRight( fcn[, initialValue] ) + Applies a function against an accumulator and each element in an array and + returns the accumulated result, iterating from right to left. + + The provided function is provided the following arguments: + + - acc: accumulated result. + - value: current array element. + - index: index of the current array element. + - arr: array on which the method is invoked. + + If provided an initial value, the method invokes a provided function with + the initial value as the first argument and the last array element as the + second argument. + + If not provided an initial value, the method invokes a provided function + with the last array element as the first argument and the second-to-last + array element as the second argument. + + Parameters + ---------- + fcn: Function + Function to apply. + + initialValue: Any (optional) + Initial accumulation value. + + Returns + ------- + out: Any + Accumulated result. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > function fcn( acc, v ) { return acc + (v*v); }; + > var v = arr.reduceRight( fcn, 0 ) + 14 + + +{{alias}}.prototype.reverse() + Reverses an array *in-place*. + + This method mutates the array on which the method is invoked. + + Returns + ------- + out: Uint8ClampedArray + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ) + [ 1, 2, 3 ] + > arr.reverse() + [ 3, 2, 1 ] + + +{{alias}}.prototype.set( arr[, offset] ) + Sets array elements. + + Parameters + ---------- + arr: ArrayLike + Source array containing array values to set. + + offset: integer (optional) + Array index at which to start writing values. Default: 0. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.set( [ 4, 4 ], 1 ); + > arr[ 1 ] + 4 + > arr[ 2 ] + 4 + + +{{alias}}.prototype.slice( [begin[, end]] ) + Copies array elements to a new array with the same underlying data type as + the host array. + + If the method is unable to resolve indices to a non-empty array subsequence, + the method returns `null`. + + Parameters + ---------- + begin: integer (optional) + Start element index (inclusive). If less than zero, the start index is + resolved relative to the last array element. Default: 0. + + end: integer (optional) + End element index (exclusive). If less than zero, the end index is + resolved relative to the last array element. Default: arr.length. + + Returns + ------- + out: Uint8ClampedArray + A typed array. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3 ] ); + > var arr2 = arr1.slice( 1 ); + > arr2.length + 2 + > arr2[ 0 ] + 1 + > arr2[ 1 ] + 2 + + +{{alias}}.prototype.some( predicate[, thisArg] ) + Tests whether at least one array element passes a test implemented by a + predicate function. + + A predicate function is provided the following arguments: + + - value: array element. + - index: array index. + - arr: array on which the method is invoked. + + Parameters + ---------- + predicate: Function + Predicate function which tests array elements. If a predicate function + returns a truthy value, a array element passes; otherwise, an array + element fails. + + thisArg: Any (optional) + Callback execution context. + + Returns + ------- + bool: boolean + Boolean indicating whether at least one array element passes. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > function predicate( v ) { return ( v > 1 ); }; + > arr.some( predicate ) + true + + +{{alias}}.prototype.sort( [compareFunction] ) + Sorts an array *in-place*. + + The comparison function is provided two array elements per invocation: `a` + and `b`. + + The comparison function return value determines the sort order as follows: + + - If the comparison function returns a value less than zero, then the method + sorts `a` to an index lower than `b` (i.e., `a` should come *before* `b`). + + - If the comparison function returns a value greater than zero, then the + method sorts `a` to an index higher than `b` (i.e., `b` should come *before* + `a`). + + - If the comparison function returns zero, then the relative order of `a` + and `b` should remain unchanged. + + This method mutates the array on which the method is invoked. + + Parameters + ---------- + compareFunction: Function (optional) + Function which specifies the sort order. The default sort order is + ascending order. + + Returns + ------- + out: Uint8ClampedArray + Modified array. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 0, 2, 1 ] ); + > arr.sort() + [ 0, 1, 1, 2, 2 ] + + +{{alias}}.prototype.subarray( [begin[, end]] ) + Creates a new typed array over the same underlying ArrayBuffer and with the + same underlying data type as the host array. + + If the method is unable to resolve indices to a non-empty array subsequence, + the method returns an empty typed array. + + Parameters + ---------- + begin: integer (optional) + Start element index (inclusive). If less than zero, the start index is + resolved relative to the last array element. Default: 0. + + end: integer (optional) + End element index (exclusive). If less than zero, the end index is + resolved relative to the last array element. Default: arr.length. + + Returns + ------- + out: Uint8ClampedArray + A new typed array view. + + Examples + -------- + > var arr1 = new {{alias}}( [ 1, 2, 3, 4, 5 ] ); + > var arr2 = arr1.subarray( 2 ) + [ 3, 4, 5 ] + + +{{alias}}.prototype.toLocaleString( [locales[, options]] ) + Serializes an array as a locale-specific string. + + Parameters + ---------- + locales: string|Array (optional) + A BCP 47 language tag, or an array of such tags. + + options: Object (optional) + Options. + + Returns + ------- + str: string + A typed array string representation. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.toLocaleString() + '1,2,3' + + +{{alias}}.prototype.toString() + Serializes an array as a string. + + Returns + ------- + str: string + A typed array string representation. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2, 3 ] ); + > arr.toString() + '1,2,3' + + +{{alias}}.prototype.values() + Returns an iterator for iterating over array elements. + + Returns + ------- + iter: Iterator + Iterator for iterating over array elements. + + Examples + -------- + > var arr = new {{alias}}( [ 1, 2 ] ); + > it = arr.values(); + > it.next().value + 1 + > it.next().value + 2 + > it.next().done + true + + + See Also + -------- + diff --git a/uint8c/docs/types/index.d.ts b/uint8c/docs/types/index.d.ts new file mode 100644 index 00000000..1dd26b1b --- /dev/null +++ b/uint8c/docs/types/index.d.ts @@ -0,0 +1,26 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 2.0 + +// EXPORTS // + +/** +* Typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order clamped to 0-255. +*/ +export = Uint8ClampedArray; diff --git a/uint8c/docs/types/test.ts b/uint8c/docs/types/test.ts new file mode 100644 index 00000000..a262ddf7 --- /dev/null +++ b/uint8c/docs/types/test.ts @@ -0,0 +1,37 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// tslint:disable: no-construct +// tslint:disable: no-unused-expression + +import Uint8ClampedArray = require( './index' ); + + +// TESTS // + +// The function returns a typed array instance... +{ + new Uint8ClampedArray( 10 ); // $ExpectType Uint8ClampedArray + new Uint8ClampedArray( [ 2, 5, 5, 7 ] ); // $ExpectType Uint8ClampedArray +} + +// The constructor function has to be invoked with `new`... +{ + Uint8ClampedArray( 10 ); // $ExpectError + Uint8ClampedArray( [ 2, 5, 5, 7 ] ); // $ExpectError +} diff --git a/uint8c/examples/index.js b/uint8c/examples/index.js new file mode 100644 index 00000000..d0978bec --- /dev/null +++ b/uint8c/examples/index.js @@ -0,0 +1,32 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var randu = require( '@stdlib/random/base/randu' ); +var round = require( '@stdlib/math/base/special/round' ); +var ctor = require( './../lib' ); + +var arr; +var i; + +arr = new ctor( 10 ); +for ( i = 0; i < arr.length; i++ ) { + arr[ i ] = round( randu()*100.0 ); +} +console.log( arr ); diff --git a/uint8c/lib/index.js b/uint8c/lib/index.js new file mode 100644 index 00000000..8d9bfc6f --- /dev/null +++ b/uint8c/lib/index.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order clamped to 0-255. +* +* @module @stdlib/array/uint8c +* +* @example +* var ctor = require( '@stdlib/array/uint8c' ); +* +* var arr = new ctor( 10 ); +* // returns +*/ + +// MODULES // + +var hasUint8ClampedArraySupport = require( '@stdlib/assert/has-uint8clampedarray-support' ); // eslint-disable-line id-length +var builtin = require( './uint8clampedarray.js' ); +var polyfill = require( './polyfill.js' ); + + +// MAIN // + +var ctor; +if ( hasUint8ClampedArraySupport() ) { + ctor = builtin; +} else { + ctor = polyfill; +} + + +// EXPORTS // + +module.exports = ctor; diff --git a/uint8c/lib/polyfill.js b/uint8c/lib/polyfill.js new file mode 100644 index 00000000..76e599e0 --- /dev/null +++ b/uint8c/lib/polyfill.js @@ -0,0 +1,37 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// TODO: write polyfill + +// MAIN // + +/** +* Typed array which represents an array of 8-bit unsigned integers in the platform byte order clamped to 0-255. +* +* @throws {Error} not implemented +*/ +function polyfill() { + throw new Error( 'not implemented' ); +} + + +// EXPORTS // + +module.exports = polyfill; diff --git a/uint8c/lib/uint8clampedarray.js b/uint8c/lib/uint8clampedarray.js new file mode 100644 index 00000000..ea97aa45 --- /dev/null +++ b/uint8c/lib/uint8clampedarray.js @@ -0,0 +1,28 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MAIN // + +var ctor = ( typeof Uint8ClampedArray === 'function' ) ? Uint8ClampedArray : void 0; // eslint-disable-line stdlib/require-globals + + +// EXPORTS // + +module.exports = ctor; diff --git a/uint8c/package.json b/uint8c/package.json new file mode 100644 index 00000000..1ac54931 --- /dev/null +++ b/uint8c/package.json @@ -0,0 +1,73 @@ +{ + "name": "@stdlib/array/uint8c", + "version": "0.0.0", + "description": "Uint8ClampedArray.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "data", + "structure", + "array", + "typed", + "typed array", + "typed-array", + "uint8clampedarray", + "uint8clamped", + "clamped", + "uint8", + "uint8_t", + "integer", + "int", + "uint", + "unsigned", + "byte", + "octet" + ] +} diff --git a/uint8c/test/test.copy_within.js b/uint8c/test/test.copy_within.js new file mode 100644 index 00000000..386560bf --- /dev/null +++ b/uint8c/test/test.copy_within.js @@ -0,0 +1,320 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var hasProp = require( '@stdlib/assert/has-property' ); +var isFunction = require( '@stdlib/assert/is-function' ); +var Uint8ClampedArray = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof Uint8ClampedArray, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'a typed array instance has a `copyWithin` method for copying a sequence of elements within a typed array', function test( t ) { + var arr = new Uint8ClampedArray( 2 ); + t.strictEqual( hasProp( arr, 'copyWithin' ), true, 'has property' ); + t.strictEqual( isFunction( arr.copyWithin ), true, 'has method' ); + t.end(); +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a typed array instance', function test( t ) { + var values; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0 ); + }; + } +}); + +tape( 'the method throws an error if invoked with a `this` context which is not a typed array instance (end)', function test( t ) { + var values; + var arr; + var i; + + arr = new Uint8ClampedArray( 2 ); + + values = [ + '5', + 5, + NaN, + true, + false, + null, + void 0, + {}, + [] + ]; + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + return arr.copyWithin.call( value, 3, 0, 5 ); + }; + } +}); + +tape( 'the method copies a sequence of elements within a typed array', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint8ClampedArray( arr ); + p.copyWithin( 0, 3 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative target)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint8ClampedArray( arr ); + p.copyWithin( -p.length, 3 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative start)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint8ClampedArray( arr ); + p.copyWithin( 0, -2 ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (end=length)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint8ClampedArray( arr ); + p.copyWithin( 0, 3, p.length ); + + // Overwritten: + t.strictEqual( p[ 0 ], 3, 'returns expected value' ); + t.strictEqual( p[ 1 ], 4, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (non-inclusive end)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint8ClampedArray( arr ); + p.copyWithin( 2, 0, 2 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (negative end)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint8ClampedArray( arr ); + p.copyWithin( 2, 0, -3 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + + // Remain the same: + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (target >= length)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint8ClampedArray( arr ); + p.copyWithin( p.length, 3 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + t.strictEqual( p[ 2 ], 2, 'returns expected value' ); + t.strictEqual( p[ 3 ], 3, 'returns expected value' ); + t.strictEqual( p[ 4 ], 4, 'returns expected value' ); + + t.end(); +}); + +tape( 'the method copies a sequence of elements within a typed array (target > start)', function test( t ) { + var arr; + var p; + + arr = [ + 0, + 1, + 2, + 3, + 4 + ]; + + p = new Uint8ClampedArray( arr ); + p.copyWithin( 2, 0 ); + + // Remain the same: + t.strictEqual( p[ 0 ], 0, 'returns expected value' ); + t.strictEqual( p[ 1 ], 1, 'returns expected value' ); + + // Overwritten: + t.strictEqual( p[ 2 ], 0, 'returns expected value' ); + t.strictEqual( p[ 3 ], 1, 'returns expected value' ); + t.strictEqual( p[ 4 ], 2, 'returns expected value' ); + + t.end(); +}); diff --git a/uint8c/test/test.js b/uint8c/test/test.js new file mode 100644 index 00000000..c820df8d --- /dev/null +++ b/uint8c/test/test.js @@ -0,0 +1,80 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var hasUint8ClampedArraySupport = require( '@stdlib/assert/has-uint8clampedarray-support' ); +var polyfill = require( './../lib/polyfill.js' ); +var ctor = require( './../lib' ); + + +// VARIABLES // + +var hasUint8ClampedArrays = hasUint8ClampedArraySupport(); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'if an environment supports `Uint8ClampedArray`, the export is an alias for `Uint8ClampedArray`', function test( t ) { + var Foo; + + Foo = proxyquire( './../lib', { + '@stdlib/assert/has-uint8clampedarray-support': isTrue, + './uint8clampedarray.js': Mock + }); + t.strictEqual( Foo, Mock, 'returns builtin' ); + + if ( hasUint8ClampedArrays ) { + t.strictEqual( ctor, Uint8ClampedArray, 'is alias' ); // eslint-disable-line stdlib/require-globals + } + + t.end(); + + function Mock() { + return this; + } + + function isTrue() { + return true; + } +}); + +tape( 'if an environment does not support `Uint8ClampedArray`, the export is a polyfill', function test( t ) { + var Foo; + + Foo = proxyquire( './../lib', { + '@stdlib/assert/has-uint8clampedarray-support': isFalse + }); + + t.strictEqual( Foo, polyfill, 'returns polyfill' ); + t.end(); + + function isFalse() { + return false; + } +}); diff --git a/uint8c/test/test.polyfill.js b/uint8c/test/test.polyfill.js new file mode 100644 index 00000000..9d6fcb19 --- /dev/null +++ b/uint8c/test/test.polyfill.js @@ -0,0 +1,44 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var ctor = require( './../lib/polyfill.js' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ctor, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error when invoked', function test( t ) { + t.throws( foo, Error, 'throws an error' ); + t.end(); + + function foo() { + var f = new ctor(); // eslint-disable-line no-unused-vars + } +}); + +// TODO: tests