diff --git a/.codeclimate.yml b/.codeclimate.yml
new file mode 100644
index 000000000..629be083a
--- /dev/null
+++ b/.codeclimate.yml
@@ -0,0 +1,45 @@
+version: "2" # required to adjust maintainability checks
+plugins:
+ eslint:
+ enabled: true
+ markdownlint:
+ enabled: true
+ # initial: .mdlrc
+ # config: .mdlrc.style.rb
+ fixme:
+ enabled: true
+checks:
+ argument-count:
+ config:
+ threshold: 4
+ complex-logic:
+ config:
+ threshold: 4
+ file-lines:
+ config:
+ threshold: 250
+ method-complexity:
+ config:
+ threshold: 5
+ method-count:
+ config:
+ threshold: 20
+ method-lines:
+ config:
+ threshold: 25
+ nested-control-flow:
+ config:
+ threshold: 4
+ return-statements:
+ config:
+ threshold: 4
+ similar-code:
+ config:
+ threshold: # language-specific defaults. an override will affect all languages.
+ identical-code:
+ config:
+ threshold: # language-specific defaults. an override will affect all languages
+exclude_patterns:
+ - "locale/"
+ - "**/test/"
+ - "dist/"
diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
deleted file mode 100644
index 80717b4fd..000000000
--- a/.github/ISSUE_TEMPLATE.md
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
-
-
-## [FEATURE] _REPLACE THIS WITH A BRIEF SUMMARY OF THE SUGGESTED SNIPPET_
-**Category:**
-### Description
-
-
-
-
-
-## [BUG] _REPLACE THIS WITH A BRIEF SUMMARY OF YOUR ISSUE_
-### Expected Snippet Behavior
-
-
-
-### Current Snippet Behavior
-
-
-
-### Possible Solution
-
-
diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md
new file mode 100644
index 000000000..02b176d69
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug-report.md
@@ -0,0 +1,20 @@
+---
+name: Bug report
+about: Create a report to help us improve
+
+---
+
+## Bug description
+
+
+## Steps to reproduce
+
+
+## Expected behavior
+
+
+## Screenshots
+
+
+## Environment
+
diff --git a/.github/ISSUE_TEMPLATE/discussion.md b/.github/ISSUE_TEMPLATE/discussion.md
new file mode 100644
index 000000000..7a2df3f90
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/discussion.md
@@ -0,0 +1,8 @@
+---
+name: Discussion
+about: Discuss something with us
+
+---
+
+## Description
+
diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 000000000..59b6f461d
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,9 @@
+---
+name: Feature request
+about: Suggest an idea for this project
+
+---
+
+## Description
+
+
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index c3ed31c2e..dea9a381e 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -1,36 +1,16 @@
-
-
-
+
## Description
-
-**Resolves** #(issue number)
+
+
+
-
-**Lodash[ACTION]** #100 -> https://lodash.com/docs/4.17.4#(method)
+## PR Type
+- [ ] Snippets, Tests & Tags (new snippets, updated snippets, re-tagging of snippets, added/updated tests)
+- [ ] Scripts & Website & Meta (anything related to files in the [scripts folder](https://github.com/30-seconds/30-seconds-of-code/tree/master/scripts), how the repository's automated procedures work and the website)
+- [ ] Glossary & Secondary Features (anything related to the glossary, such as new or updated terms or other secondary features)
+- [ ] General, Typos, Misc. & Meta (everything else, typos, general stuff and meta files in the repository - e.g. the issue template)
-## What does your PR belong to?
-- [ ] Website
-- [ ] Snippets
-- [ ] General / Things regarding the repository (like CI Integration)
-
-## Types of changes
-- [ ] Bug fix (non-breaking change which fixes an issue)
-- [ ] Enhancement (non-breaking improvement of a snippet)
-- [ ] New feature (non-breaking change which adds functionality)
-- [ ] Breaking change (fix or feature that would cause existing functionality to change)
-
-## [Lodash Backlog](https://github.com/Chalarangelo/30-seconds-of-code/issues/100)
-
-
-- [ ] I added the prefix [UPDATE: `method.md`] or [ADD: `method.md`]
-- [ ] I have referenced the `method` to the lodash backlog.
-
-## Checklist:
-
-- [ ] My code follows the code style of this project.
-- [ ] My change requires a change to the documentation.
-- [ ] I have updated the documentation accordingly.
-- [ ] I have checked that the changes are working properly
-- [ ] I have checked that there isn't any PR doing the same
-- [ ] I have read the **CONTRIBUTING** document.
+## Guidelines
+- [ ] I have read the guidelines in the [CONTRIBUTING](https://github.com/30-seconds/30-seconds-of-code/blob/master/CONTRIBUTING.md) document.
+- [ ] My PR doesn't include any `testlog` changes.
diff --git a/.gitignore b/.gitignore
index 1672226d8..6b3794e52 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,4 +3,10 @@ currentSnippet\.js
*.md.temp.js
.idea
test.sh
-test/
+/*.log
+
+dist/flavor\.min\.css
+
+dist/flavor\.css
+
+test_old/
diff --git a/.mdlrc b/.mdlrc
new file mode 100644
index 000000000..1399044eb
--- /dev/null
+++ b/.mdlrc
@@ -0,0 +1,12 @@
+rules "MD003", // header style - atx
+ "MD004", // ul list style - asterisk
+ "MD009", // no trailing whitespaces
+ "MD010", // no hard tabs
+ "MD011", // no reversed links
+ "MD018", // no space after hash on atx style header
+ "MD023", // headers should start on the start of the line
+ "MD025", // no multiple h1 headers
+ "MD031", // blanks around fences
+ "MD038", // no spaces inside code elements
+ "MD040" // fenced code blocks need to have a language specified
+style ".mdlrc.style.rb"
diff --git a/.mdlrc.style.rb b/.mdlrc.style.rb
new file mode 100644
index 000000000..5118afccf
--- /dev/null
+++ b/.mdlrc.style.rb
@@ -0,0 +1,7 @@
+all
+rule 'header-style', :style => "atx"
+rule 'ul-style', :style => "asterisk"
+
+exclude_rule 'first-header-h1'
+exclude_rule 'first-line-h1'
+exclude_rule 'no-inline-html'
diff --git a/.npmignore b/.npmignore
new file mode 100644
index 000000000..d01bec1b1
--- /dev/null
+++ b/.npmignore
@@ -0,0 +1,19 @@
+snippet-template.md
+tag_database
+travis.log
+CONTRIBUTING.md
+COLLABORATING.md
+CODE_OF_CONDUCT.md
+.travis.yml
+.mdlrc.style.rb
+.mdlrc
+.codeclimate.yml
+test/*
+static-parts/*
+snippet_data/*
+snippets_archive/*
+scripts/*
+locale/*
+docs/*
+.travis/*
+.github/*
diff --git a/.travis.yml b/.travis.yml
index ffb9c3da1..611fd5ae7 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -10,9 +10,13 @@ before_install:
script:
- npm run tagger
- npm run linter
-- npm run builder
- npm run webber
-- npm run module
+- npm run builder
+- npm run packager
+- npm run tester
+- npm run extractor
+- npm run glossary:keymaker
+- npm run glossary:librarian
after_success:
- chmod +x .travis/push.sh
- .travis/push.sh
diff --git a/.travis/push.sh b/.travis/push.sh
index 174bb5311..3b45d56a5 100755
--- a/.travis/push.sh
+++ b/.travis/push.sh
@@ -1,3 +1,4 @@
+#!/bin/bash
setup_git() {
git config --global user.email "30secondsofcode@gmail.com"
git config --global user.name "30secondsofcode"
@@ -24,7 +25,7 @@ upload_files() {
if [ $TRAVIS_EVENT_TYPE != "pull_request" ]; then
if [ $TRAVIS_BRANCH == "master" ]; then
echo "Pushing to master branch..."
- git push --force --quiet "https://${GH_TOKEN}@github.com/Chalarangelo/30-seconds-of-code.git" master > /dev/null 2>&1
+ git push --force --quiet "https://${GH_TOKEN}@github.com/30-seconds/30-seconds-of-code.git" master > /dev/null 2>&1
fi
fi
}
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
index df46a145a..53001a0b0 100644
--- a/CODE_OF_CONDUCT.md
+++ b/CODE_OF_CONDUCT.md
@@ -34,7 +34,7 @@ This Code of Conduct applies both within project spaces and in public spaces whe
## Enforcement
-Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at chalarangelo@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
+Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at 30secondsofcode@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
diff --git a/COLLABORATING.md b/COLLABORATING.md
index a38c4d52d..56562d5d4 100644
--- a/COLLABORATING.md
+++ b/COLLABORATING.md
@@ -8,17 +8,17 @@ As a member of the team that manages **30 seconds of code**, you have the follow
- **Be part of the conversation in the issue tracker.** That includes (but is not limited to) helping out new members, discussing new features and explaining decisions to people.
- **Review pull requests.** You do not have to read through all of the pull requests and review them, but taking the time each day to review a few can help a great deal.
-- **Be civil and polite.** If you are about to lose your temper, take a step back and go do something else. We want our interactions with the community to be polite, so that more people can join the project and contribute in any way they can. Remember to always thank contributors for their help, even if it's minor changes or changes that did not make it into the project. This way we can reward and encourage people to keep being part of the community.
+- **Be civil and polite.** If you are about to lose your temper, take a step back and do something else. We want our interactions with the community to be polite so that more people can join the project and contribute in any way they can. Remember to always thank contributors for their help, even if it's minor changes or changes that did not make it into the project. This way we can reward and encourage people to keep being part of the community.
- **Contribute when you want, moderate when you can.** If you have a lot on your plate outside of this project, it's alright. It's better to take a break for a few days rather than hastily deal with issues and pull requests that might break things.
## Guidelines for merging pull requests and making changes to the project
-- **[Usual guidelines](https://github.com/Chalarangelo/30-seconds-of-code/blob/master/CONTRIBUTING.md) apply.** Make sure to follow them, like everybody else.
+- **[Usual guidelines](https://github.com/30-seconds/30-seconds-of-code/blob/master/CONTRIBUTING.md) apply.** Make sure to follow them, like everybody else.
- **For a pull request to be considered ready to merge, there should be at least 2 (preferably 3) reviews approving it for merge.** There are, however, certain exceptions:
- - **If a pull request only fixes typos**, there is no need to wait for a second reviewer (unless you are not absolutely certain these were not typos in the first place).
- - **If a pull request only clarifies a snippet's description or enforces the styleguide for an existng snippet**, you might be able to merge it without getting a second reviewer to review it, but only if you are absolutely certain about it.
+ - **If a pull request only fixes typos**, there is no need to wait for a second reviewer (unless you are not certain these were not typos in the first place).
+ - **If a pull request only clarifies a snippet's description or enforces the style guide for an existing snippet**, you might be able to merge it without getting a second reviewer to review it, but only if you are certain about it.
- **Make sure pull requests pass the Travis CI build**, otherwise try and find out what's wrong and inform the author of the pull request.
- **Changes to build scripts, guidelines and things that might break the processes we have in place need to be reviewed by [@Chalarangelo](https://github.com/Chalarangelo)** (this is temporary, but we need a baseline to make sure we break as few things as possible in the beginning).
- **After merging a pull request, make sure to check for untagged snippets and tag them appropriately.** Try to keep all snippets tagged, so that the list and website are up to date.
-- **If you make changes or additions to existing snippets or if you want to add you own snippets, you will go through the pull request process that everyone else goes.** Exceptions apply similarly to the ones mentioned above about merging pull requests (i.e. typos, description clarification and the way script and build process changes are handled). Pull requests suggested by collaborators should be reviewed by at least two other collaborators to be considered ready to merge.
+- **If you make changes or additions to existing snippets or if you want to add your own snippets, you will go through the pull request process that everyone else goes.** Exceptions apply similarly to the ones mentioned above about merging pull requests (i.e. typos, description clarification and the way script and build process changes are handled). Pull requests suggested by collaborators should be reviewed by at least two other collaborators to be considered ready to merge.
- **Pull requests that are inactive for over a week should be closed or put on hold.**
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index c274e0e09..7b5b4cdcc 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,23 +1,23 @@
-## Contributing
+
**30 seconds of code** is a community effort, so feel free to contribute in any way you can. Every contribution helps!
Here's what you can do to help:
-- [Open issues](https://github.com/Chalarangelo/30-seconds-of-code/issues/new) for things you want to see added or modified.
-- Be part of the discussion by helping out with [existing issues](https://github.com/Chalarangelo/30-seconds-of-code/issues) or talking on our [gitter channel](https://gitter.im/30-seconds-of-code/Lobby).
-- Submit [pull requests](https://github.com/Chalarangelo/30-seconds-of-code/pulls) with snippets you have created (see below for guidelines).
-- Tag uncategorized snippets by running `npm run tagger` and adding the appropriate tag next to the script name in `tag_database`.
+- Submit [pull requests](https://github.com/30-seconds/30-seconds-of-code/pulls) with snippets and tests that you have created (see below for guidelines).
+- [Open issues](https://github.com/30-seconds/30-seconds-of-code/issues/new) for things you want to see added or modified.
+- Be part of the discussion by helping out with [existing issues](https://github.com/30-seconds/30-seconds-of-code/issues) or talking on our [gitter channel](https://gitter.im/30-seconds-of-code/Lobby).
+- Tag uncategorized snippets by running `npm run tagger` and adding the appropriate tags next to the script name in `tag_database`.
- Fix typos in existing snippets, improve snippet descriptions and explanations or provide better examples.
+- Write tests for existing snippets (see below for guidelines).
### Snippet submission and Pull request guidelines
-- **DO NOT MODIFY THE README.md FILE!** Make changes to individual snippet files. You can optionally run `npm run builder` to update the README.md file automatically, based on the changes you have made.
-- **DO NOT MODIFY THE index.html FILE!** Make changes to individual snippet files. You can optionally run `npm run webber` to update the index.md file automatically, based on the changes you have made.
+- **DO NOT MODIFY THE README.md or index.html FILES!** Make changes to individual snippet files. **Travis CI** will automatically build the `README.md` and `index.html` files when your pull request is merged.
- **Snippet filenames** must correspond to the title of the snippet. For example, if your snippet is titled `### awesomeSnippet` the filename should be `awesomeSnippet.md`.
- Use `camelCase`, not `kebab-case` or `snake_case`.
- Avoid capitalization of words, except if the whole word is capitalized (e.g. `URL` should be capitalized in the filename and the snippet title).
-- **Snippet titles** should have be the same as the name of the function that is present in the snippet.
+- **Snippet titles** should be the same as the name of the function that is present in the snippet.
- All snippet titles must be prefixed with `###` and be at the very first line of your snippet.
- Snippet titles must be unique (although if you cannot find a better title, just add some placeholder at the end of the filename and title and we will figure it out).
- Follow snippet titles with an empty line.
@@ -26,7 +26,7 @@ Here's what you can do to help:
- **Snippet code** must be enclosed inside ` ```js ` and ` ``` `.
- Remember to start your snippet's code on a new line below the opening backticks.
- Use ES6 notation to define your function. For example `const myFunction = ( arg1, arg2 ) => { }`.
- - Please use Javacript [Semi-Standard Style](https://github.com/Flet/semistandard).
+ - Please use Javascript [Semi-Standard Style](https://github.com/Flet/semistandard).
- Try to keep your snippets' code short and to the point. Use modern techniques and features. Make sure to test your code before submitting.
- All snippets must be followed by one (more if necessary) test case after the code, in a new block enclosed inside ` ```js ` and ` ``` `. The syntax for this is `myFunction('testInput') // 'testOutput'`. Use multiline examples only if necessary.
- Try to make your function name unique, so that it does not conflict with existing snippets.
@@ -36,11 +36,23 @@ Here's what you can do to help:
- Snippets *should* be abstract enough to be applied to different scenarios.
- It is not mandatory but highly appreciated if you provide **test cases** and/or performance tests (we recommend using [jsPerf](https://jsperf.com/)).
- You can start creating a new snippet, by using the [snippet template](snippet-template.md) to format your snippets.
-- Updating the index.html or README.md files should only be done by altering the scripts in the **scripts** folder or altering their relative static parts in the **static-parts** folder.
+
+### Writing tests
+- Before writing any tests run `npm run tester` script. It will update test directory to include new snippets as well as update old ones if needed.
+- **DO NOT MODIFY THE snippetName.js files** under test directory.
+- We are using [tape](https://github.com/substack/tape) for testing.
+- Write tests under `snippetName.test.js` file. If you have trouble doing so, check out tests of other snippets.
+- Be sure to run `npm run test`. It is going to run all tests for all snippets.
+- Make a new pull request **only if all the tests are passing**.
+
+#### Browser specific tests
+- If your snippet belongs to `browser` category, then you will need to modify the tests to make them work.
+- By default, `Node.js` isn't browser environment. That said we have to use an external package to help us simulate the browser for our tests.
+- We use [jsdom](https://www.npmjs.com/package/jsdom) for our browser specific tests. You can find their [documentation](https://github.com/jsdom/jsdom) on GitHub as well.
### Additional guidelines and conventions regarding snippets
-- When describing snippets, refer to methods, using their full name. For example, use `Array.reduce()`, instead of `reduce()`.
+- When describing snippets, refer to methods, using their full name. For example, use `Array.prototype.reduce()`, instead of `reduce()`.
- If your snippet contains argument with default parameters, explain what happens if they are omitted when calling the function and what the default case is.
- If your snippet uses recursion, explain the base cases.
- Always use `const functionName` for function definitions.
@@ -49,16 +61,16 @@ Here's what you can do to help:
- Try to give meaningful names to variables. For example use `letter`, instead of `lt`. Some exceptions to convention are:
- `arr` for arrays (usually as the snippet function's argument).
- `str` for strings.
- - `n` for a numeric value (usually as the snippet function's argument).
+ - `num` or `n` for a numeric value (usually as the snippet function's argument).
- `el` for DOM elements (usually as the snippet function's argument).
- `val` or `v` for value (usually when iterating a list, mapping, sorting etc.).
- - `acc` for accumulators in `Array.reduce()`.
- - `(a,b)` for the two values compared when using `Array.sort()`.
+ - `acc` for accumulators in `Array.prototype.reduce()`.
+ - `(a,b)` for the two values compared when using `Array.prototype.sort()`.
- `i` for indexes.
- - `func` for function arguments.
+ - `fn` for function arguments.
- `nums` for arrays of numbers.
- Use `()` if your function takes no arguments.
-- Use `_` if an argument inside some function (e.g. `Array.reduce()`) is not used anywhere in your code.
+- Use `_` if an argument inside some function (e.g. `Array.prototype.reduce()`) is not used anywhere in your code.
- Specify default parameters for arguments, if necessary. It is preferred to put default parameters last unless you have pretty good reason not to.
- If your snippet's function takes variadic arguments, use `...args` (although in certain cases, it might be needed to use a different name).
- If your snippet function's body is a single statement, omit the `return` keyword and use an expression instead.
@@ -67,7 +79,7 @@ Here's what you can do to help:
- Always use single quotes for string literals. Use template literals, instead, if necessary.
- If your snippet's code is short enough (around 80 characters), you can make it a single-line function (although not mandatory). Otherwise, use multiple lines.
- Prefer using `Array` methods whenever possible.
-- Prefer `Array.concat()` instead of `Array.push()` when working with `Array.reduce()`.
+- Prefer `Array.prototype.concat()` instead of `Array.prototype.push()` when working with `Array.prototype.reduce()`.
- Use strict equality checking (`===` and `!==` instead of `==` and `!=`), unless you specifically have reason not to.
- Prefer using the ternary operator (`condition ? trueResult : falseResult`) instead of `if else` statements whenever possible.
- Avoid nesting ternary operators (but you can do it if you feel like you should).
diff --git a/README.md b/README.md
index eb88d68c1..7f59de281 100644
--- a/README.md
+++ b/README.md
@@ -2,26 +2,40 @@
# 30 seconds of code
-[](https://github.com/Chalarangelo/30-seconds-of-code/blob/master/LICENSE) [](https://www.npmjs.com/package/30-seconds-of-code) [](https://www.npmjs.com/package/30-seconds-of-code) [](https://gitter.im/30-seconds-of-code/Lobby) [](http://makeapullrequest.com) [](https://travis-ci.org/Chalarangelo/30-seconds-of-code) [](https://insight.io/github.com/Chalarangelo/30-seconds-of-code/tree/master/?source=0) [](https://github.com/Flet/semistandard) [](https://www.producthunt.com/posts/30-seconds-of-code)
+[](https://github.com/30-seconds/30-seconds-of-code/blob/master/LICENSE) [](https://www.npmjs.com/package/30-seconds-of-code) [](https://www.npmjs.com/package/30-seconds-of-code) [](https://gitter.im/30-seconds-of-code/Lobby) [](http://makeapullrequest.com) [](https://travis-ci.com/30-seconds/30-seconds-of-code) [](https://www.codacy.com/app/Chalarangelo/30-seconds-of-code?utm_source=github.com&utm_medium=referral&utm_content=30-seconds/30-seconds-of-code&utm_campaign=Badge_Grade) [](https://codeclimate.com/github/30-seconds/30-seconds-of-code/maintainability) [](https://github.com/Flet/semistandard) [](https://snyk.io/test/github/30-seconds/30-seconds-of-code?targetFile=package.json) [](https://www.producthunt.com/posts/30-seconds-of-code)
> Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
+[](https://www.digitalocean.com)
+
- Use Ctrl + F or command + F to search for a snippet.
- Contributions welcome, please read the [contribution guide](CONTRIBUTING.md).
- Snippets are written in ES6, use the [Babel transpiler](https://babeljs.io/) to ensure backwards-compatibility.
- You can import these snippets into your text editor of choice (VSCode, Atom, Sublime) using the files found in [this repo](https://github.com/Rob-Rychs/30-seconds-of-code-texteditorsnippets).
- You can import these snippets into Alfred 3, using [this file](https://github.com/lslvxy/30-seconds-of-code-alfredsnippets).
+- If you want to follow 30-seconds-of-code on social media, you can find us on [Facebook](https://www.facebook.com/30secondsofcode), [Instagram](https://www.instagram.com/30secondsofcode) and [Twitter](https://twitter.com/30secondsofcode).
+
+#### Related projects
+
+- [30 Seconds of CSS](https://30-seconds.github.io/30-seconds-of-css/)
+- [30 Seconds of Interviews](https://30secondsofinterviews.org/)
+- [30 Seconds of Python](https://github.com/kriadmin/30-seconds-of-python-code) *(unofficial)*
+- [30 Seconds of PHP](https://github.com/appzcoder/30-seconds-of-php-code) *(unofficial)*
#### Package
-⚠️ **WARNING:** Snippets are not production ready.
+⚠️ **NOTICE:** A few of our snippets are not yet optimized for production (see disclaimers for individual snippet issues).
-You can find a package with all the snippets on [npm](https://www.npmjs.com/package/30-seconds-of-code).
+You can find a package with all the snippets on [npm](https://www.npmjs.com/package/30-seconds-of-code).
-```
+```bash
+# With npm
npm install 30-seconds-of-code
+
+# With yarn
+yarn add 30-seconds-of-code
```
CDN links
@@ -29,6 +43,7 @@ CDN links
- [ES5 Minified (UMD)](https://unpkg.com/30-seconds-of-code/dist/_30s.es5.min.js)
+Details
**Browser**
@@ -73,12 +88,18 @@ average(1, 2, 3);
View contents
+* [`ary`](#ary)
* [`call`](#call)
* [`collectInto`](#collectinto)
* [`flip`](#flip)
+* [`over`](#over)
+* [`overArgs`](#overargs)
+* [`pipeAsyncFunctions`](#pipeasyncfunctions)
* [`pipeFunctions`](#pipefunctions)
* [`promisify`](#promisify)
+* [`rearg`](#rearg)
* [`spreadOver`](#spreadover)
+* [`unary`](#unary)
@@ -87,53 +108,98 @@ average(1, 2, 3);
View contents
+* [`all`](#all)
+* [`allEqual`](#allequal)
+* [`any`](#any)
+* [`arrayToCSV`](#arraytocsv)
+* [`bifurcate`](#bifurcate)
+* [`bifurcateBy`](#bifurcateby)
* [`chunk`](#chunk)
* [`compact`](#compact)
+* [`countBy`](#countby)
* [`countOccurrences`](#countoccurrences)
* [`deepFlatten`](#deepflatten)
* [`difference`](#difference)
+* [`differenceBy`](#differenceby)
* [`differenceWith`](#differencewith)
-* [`distinctValuesOfArray`](#distinctvaluesofarray)
-* [`dropElements`](#dropelements)
+* [`drop`](#drop)
* [`dropRight`](#dropright)
+* [`dropRightWhile`](#droprightwhile)
+* [`dropWhile`](#dropwhile)
* [`everyNth`](#everynth)
* [`filterNonUnique`](#filternonunique)
+* [`filterNonUniqueBy`](#filternonuniqueby)
+* [`findLast`](#findlast)
+* [`findLastIndex`](#findlastindex)
* [`flatten`](#flatten)
-* [`flattenDepth`](#flattendepth)
+* [`forEachRight`](#foreachright)
* [`groupBy`](#groupby)
* [`head`](#head)
+* [`indexOfAll`](#indexofall)
* [`initial`](#initial)
* [`initialize2DArray`](#initialize2darray)
* [`initializeArrayWithRange`](#initializearraywithrange)
+* [`initializeArrayWithRangeRight`](#initializearraywithrangeright)
* [`initializeArrayWithValues`](#initializearraywithvalues)
+* [`initializeNDArray`](#initializendarray)
* [`intersection`](#intersection)
+* [`intersectionBy`](#intersectionby)
+* [`intersectionWith`](#intersectionwith)
* [`isSorted`](#issorted)
* [`join`](#join)
+* [`JSONtoCSV`](#jsontocsv-)
* [`last`](#last)
-* [`mapObject`](#mapobject)
+* [`longestItem`](#longestitem)
+* [`mapObject`](#mapobject-)
* [`maxN`](#maxn)
* [`minN`](#minn)
+* [`none`](#none)
* [`nthElement`](#nthelement)
-* [`pick`](#pick)
+* [`offset`](#offset)
+* [`partition`](#partition)
+* [`permutations`](#permutations-)
* [`pull`](#pull)
-* [`pullAtIndex`](#pullatindex)
-* [`pullAtValue`](#pullatvalue)
-* [`quickSort`](#quicksort)
+* [`pullAtIndex`](#pullatindex-)
+* [`pullAtValue`](#pullatvalue-)
+* [`pullBy`](#pullby-)
* [`reducedFilter`](#reducedfilter)
+* [`reduceSuccessive`](#reducesuccessive)
+* [`reduceWhich`](#reducewhich)
+* [`reject`](#reject)
* [`remove`](#remove)
* [`sample`](#sample)
* [`sampleSize`](#samplesize)
+* [`shank`](#shank)
* [`shuffle`](#shuffle)
* [`similarity`](#similarity)
* [`sortedIndex`](#sortedindex)
+* [`sortedIndexBy`](#sortedindexby)
+* [`sortedLastIndex`](#sortedlastindex)
+* [`sortedLastIndexBy`](#sortedlastindexby)
+* [`stableSort`](#stablesort-)
* [`symmetricDifference`](#symmetricdifference)
+* [`symmetricDifferenceBy`](#symmetricdifferenceby)
+* [`symmetricDifferenceWith`](#symmetricdifferencewith)
* [`tail`](#tail)
* [`take`](#take)
* [`takeRight`](#takeright)
+* [`takeRightWhile`](#takerightwhile)
+* [`takeWhile`](#takewhile)
+* [`toHash`](#tohash)
* [`union`](#union)
+* [`unionBy`](#unionby)
+* [`unionWith`](#unionwith)
+* [`uniqueElements`](#uniqueelements)
+* [`uniqueElementsBy`](#uniqueelementsby)
+* [`uniqueElementsByRight`](#uniqueelementsbyright)
+* [`uniqueSymmetricDifference`](#uniquesymmetricdifference)
+* [`unzip`](#unzip)
+* [`unzipWith`](#unzipwith-)
* [`without`](#without)
+* [`xProd`](#xprod)
* [`zip`](#zip)
* [`zipObject`](#zipobject)
+* [`zipWith`](#zipwith-)
@@ -144,23 +210,39 @@ average(1, 2, 3);
* [`arrayToHtmlList`](#arraytohtmllist)
* [`bottomVisible`](#bottomvisible)
-* [`copyToClipboard`](#copytoclipboard)
+* [`copyToClipboard`](#copytoclipboard-)
+* [`counter`](#counter-)
+* [`createElement`](#createelement)
+* [`createEventHub`](#createeventhub-)
* [`currentURL`](#currenturl)
* [`detectDeviceType`](#detectdevicetype)
-* [`elementIsVisibleInViewport`](#elementisvisibleinviewport)
+* [`elementContains`](#elementcontains)
+* [`elementIsVisibleInViewport`](#elementisvisibleinviewport-)
+* [`getImages`](#getimages)
* [`getScrollPosition`](#getscrollposition)
* [`getStyle`](#getstyle)
* [`hasClass`](#hasclass)
+* [`hashBrowser`](#hashbrowser-)
* [`hide`](#hide)
* [`httpsRedirect`](#httpsredirect)
-* [`onUserInputChange`](#onuserinputchange)
+* [`insertAfter`](#insertafter)
+* [`insertBefore`](#insertbefore)
+* [`isBrowserTabFocused`](#isbrowsertabfocused)
+* [`nodeListToArray`](#nodelisttoarray)
+* [`observeMutations`](#observemutations-)
+* [`off`](#off)
+* [`on`](#on)
+* [`onUserInputChange`](#onuserinputchange-)
+* [`prefix`](#prefix)
+* [`recordAnimationFrames`](#recordanimationframes)
* [`redirect`](#redirect)
-* [`runAsync`](#runasync)
+* [`runAsync`](#runasync-)
* [`scrollToTop`](#scrolltotop)
* [`setStyle`](#setstyle)
* [`show`](#show)
-* [`speechSynthesis`](#speechsynthesis)
+* [`smoothScroll`](#smoothscroll)
* [`toggleClass`](#toggleclass)
+* [`triggerEvent`](#triggerevent)
* [`UUIDGeneratorBrowser`](#uuidgeneratorbrowser)
@@ -170,10 +252,16 @@ average(1, 2, 3);
View contents
+* [`dayOfYear`](#dayofyear)
* [`formatDuration`](#formatduration)
+* [`getColonTimeFromDate`](#getcolontimefromdate)
* [`getDaysDiffBetweenDates`](#getdaysdiffbetweendates)
-* [`JSONToDate`](#jsontodate)
-* [`toEnglishDate`](#toenglishdate)
+* [`getMeridiemSuffixOfInteger`](#getmeridiemsuffixofinteger)
+* [`isAfterDate`](#isafterdate)
+* [`isBeforeDate`](#isbeforedate)
+* [`isSameDate`](#issamedate)
+* [`maxDate`](#maxdate)
+* [`minDate`](#mindate)
* [`tomorrow`](#tomorrow)
@@ -183,24 +271,31 @@ average(1, 2, 3);
View contents
+* [`attempt`](#attempt)
+* [`bind`](#bind)
+* [`bindKey`](#bindkey)
* [`chainAsync`](#chainasync)
* [`compose`](#compose)
+* [`composeRight`](#composeright)
+* [`converge`](#converge)
* [`curry`](#curry)
+* [`debounce`](#debounce)
* [`defer`](#defer)
+* [`delay`](#delay)
* [`functionName`](#functionname)
-* [`memoize`](#memoize)
+* [`hz`](#hz)
+* [`memoize`](#memoize-)
+* [`negate`](#negate)
* [`once`](#once)
+* [`partial`](#partial)
+* [`partialRight`](#partialright)
* [`runPromisesInSeries`](#runpromisesinseries)
* [`sleep`](#sleep)
-
-
-
-### 🔮 Logic
-
-
-View contents
-
-* [`negate`](#negate)
+* [`throttle`](#throttle-)
+* [`times`](#times)
+* [`uncurry`](#uncurry)
+* [`unfold`](#unfold)
+* [`when`](#when)
@@ -209,39 +304,43 @@ average(1, 2, 3);
View contents
+* [`approximatelyEqual`](#approximatelyequal)
* [`average`](#average)
+* [`averageBy`](#averageby)
+* [`binomialCoefficient`](#binomialcoefficient)
* [`clampNumber`](#clampnumber)
-* [`collatz`](#collatz)
+* [`degreesToRads`](#degreestorads)
* [`digitize`](#digitize)
* [`distance`](#distance)
-* [`elo`](#elo)
+* [`elo`](#elo-)
* [`factorial`](#factorial)
-* [`factors`](#factors)
* [`fibonacci`](#fibonacci)
-* [`fibonacciCountUntilNum`](#fibonaccicountuntilnum)
-* [`fibonacciUntilNum`](#fibonacciuntilnum)
* [`gcd`](#gcd)
* [`geometricProgression`](#geometricprogression)
* [`hammingDistance`](#hammingdistance)
-* [`howManyTimes`](#howmanytimes)
* [`inRange`](#inrange)
-* [`isArmstrongNumber`](#isarmstrongnumber)
* [`isDivisible`](#isdivisible)
* [`isEven`](#iseven)
* [`isPrime`](#isprime)
* [`lcm`](#lcm)
-* [`luhnCheck`](#luhncheck)
+* [`luhnCheck`](#luhncheck-)
+* [`maxBy`](#maxby)
* [`median`](#median)
+* [`minBy`](#minby)
* [`percentile`](#percentile)
* [`powerset`](#powerset)
* [`primes`](#primes)
+* [`radsToDegrees`](#radstodegrees)
+* [`randomIntArrayInRange`](#randomintarrayinrange)
* [`randomIntegerInRange`](#randomintegerinrange)
* [`randomNumberInRange`](#randomnumberinrange)
* [`round`](#round)
-* [`solveRPN`](#solverpn)
+* [`sdbm`](#sdbm)
* [`standardDeviation`](#standarddeviation)
* [`sum`](#sum)
+* [`sumBy`](#sumby)
* [`sumPower`](#sumpower)
+* [`toSafeInteger`](#tosafeinteger)
@@ -250,8 +349,16 @@ average(1, 2, 3);
View contents
+* [`atob`](#atob)
+* [`btoa`](#btoa)
+* [`colorize`](#colorize)
* [`hasFlags`](#hasflags)
+* [`hashNode`](#hashnode)
+* [`isDuplexStream`](#isduplexstream)
+* [`isReadableStream`](#isreadablestream)
+* [`isStream`](#isstream)
* [`isTravisCI`](#istravisci)
+* [`isWritableStream`](#iswritablestream)
* [`JSONToFile`](#jsontofile)
* [`readFileLines`](#readfilelines)
* [`untildify`](#untildify)
@@ -264,16 +371,40 @@ average(1, 2, 3);
View contents
-* [`cleanObj`](#cleanobj)
+* [`bindAll`](#bindall)
+* [`deepClone`](#deepclone)
+* [`deepFreeze`](#deepfreeze)
+* [`defaults`](#defaults)
+* [`dig`](#dig)
+* [`equals`](#equals-)
+* [`findKey`](#findkey)
+* [`findLastKey`](#findlastkey)
+* [`flattenObject`](#flattenobject)
+* [`forOwn`](#forown)
+* [`forOwnRight`](#forownright)
+* [`functions`](#functions)
+* [`get`](#get)
* [`invertKeyValues`](#invertkeyvalues)
* [`lowercaseKeys`](#lowercasekeys)
+* [`mapKeys`](#mapkeys)
+* [`mapValues`](#mapvalues)
+* [`matches`](#matches)
+* [`matchesWith`](#matcheswith)
+* [`merge`](#merge)
+* [`nest`](#nest)
* [`objectFromPairs`](#objectfrompairs)
* [`objectToPairs`](#objecttopairs)
+* [`omit`](#omit)
+* [`omitBy`](#omitby)
* [`orderBy`](#orderby)
-* [`select`](#select)
+* [`pick`](#pick)
+* [`pickBy`](#pickby)
+* [`renameKeys`](#renamekeys)
* [`shallowClone`](#shallowclone)
* [`size`](#size)
+* [`transform`](#transform)
* [`truthCheckCollection`](#truthcheckcollection)
+* [`unflattenObject`](#unflattenobject-)
@@ -282,59 +413,91 @@ average(1, 2, 3);
View contents
-* [`anagrams`](#anagrams)
* [`byteSize`](#bytesize)
* [`capitalize`](#capitalize)
* [`capitalizeEveryWord`](#capitalizeeveryword)
-* [`countVowels`](#countvowels)
+* [`CSVToArray`](#csvtoarray)
+* [`CSVToJSON`](#csvtojson-)
+* [`decapitalize`](#decapitalize)
* [`escapeHTML`](#escapehtml)
* [`escapeRegExp`](#escaperegexp)
* [`fromCamelCase`](#fromcamelcase)
+* [`indentString`](#indentstring)
* [`isAbsoluteURL`](#isabsoluteurl)
+* [`isAnagram`](#isanagram)
+* [`isLowerCase`](#islowercase)
+* [`isUpperCase`](#isuppercase)
+* [`mapString`](#mapstring)
* [`mask`](#mask)
+* [`pad`](#pad)
* [`palindrome`](#palindrome)
* [`pluralize`](#pluralize)
-* [`repeatString`](#repeatstring)
+* [`removeNonASCII`](#removenonascii)
* [`reverseString`](#reversestring)
* [`sortCharactersInString`](#sortcharactersinstring)
* [`splitLines`](#splitlines)
+* [`stringPermutations`](#stringpermutations-)
+* [`stripHTMLTags`](#striphtmltags)
* [`toCamelCase`](#tocamelcase)
* [`toKebabCase`](#tokebabcase)
* [`toSnakeCase`](#tosnakecase)
* [`truncateString`](#truncatestring)
* [`unescapeHTML`](#unescapehtml)
+* [`URLJoin`](#urljoin-)
* [`words`](#words)
+### 📃 Type
+
+
+View contents
+
+* [`getType`](#gettype)
+* [`is`](#is)
+* [`isArrayLike`](#isarraylike)
+* [`isBoolean`](#isboolean)
+* [`isEmpty`](#isempty)
+* [`isFunction`](#isfunction)
+* [`isNil`](#isnil)
+* [`isNull`](#isnull)
+* [`isNumber`](#isnumber)
+* [`isObject`](#isobject)
+* [`isObjectLike`](#isobjectlike)
+* [`isPlainObject`](#isplainobject)
+* [`isPrimitive`](#isprimitive)
+* [`isPromiseLike`](#ispromiselike)
+* [`isString`](#isstring)
+* [`isSymbol`](#issymbol)
+* [`isUndefined`](#isundefined)
+* [`isValidJSON`](#isvalidjson)
+
+
+
### 🔧 Utility
View contents
+* [`castArray`](#castarray)
* [`cloneRegExp`](#cloneregexp)
* [`coalesce`](#coalesce)
* [`coalesceFactory`](#coalescefactory)
* [`extendHex`](#extendhex)
-* [`getType`](#gettype)
* [`getURLParameters`](#geturlparameters)
-* [`hexToRGB`](#hextorgb)
-* [`isArray`](#isarray)
-* [`isArrayLike`](#isarraylike)
-* [`isBoolean`](#isboolean)
-* [`isFunction`](#isfunction)
-* [`isNull`](#isnull)
-* [`isNumber`](#isnumber)
-* [`isPrimitive`](#isprimitive)
-* [`isPromiseLike`](#ispromiselike)
-* [`isString`](#isstring)
-* [`isSymbol`](#issymbol)
-* [`isValidJSON`](#isvalidjson)
-* [`prettyBytes`](#prettybytes)
+* [`hexToRGB`](#hextorgb-)
+* [`httpGet`](#httpget)
+* [`httpPost`](#httppost)
+* [`isBrowser`](#isbrowser)
+* [`mostPerformant`](#mostperformant)
+* [`nthArg`](#ntharg)
+* [`parseCookie`](#parsecookie)
+* [`prettyBytes`](#prettybytes-)
* [`randomHexColorCode`](#randomhexcolorcode)
* [`RGBToHex`](#rgbtohex)
-* [`sdbm`](#sdbm)
+* [`serializeCookie`](#serializecookie)
* [`timeTaken`](#timetaken)
+* [`toCurrency`](#tocurrency)
* [`toDecimalMark`](#todecimalmark)
* [`toOrdinalSuffix`](#toordinalsuffix)
* [`validateNumber`](#validatenumber)
@@ -342,8 +505,32 @@ average(1, 2, 3);
+
---
- ## 🔌 Adapter
+
+## 🔌 Adapter
+
+### ary
+
+Creates a function that accepts up to `n` arguments, ignoring any additional arguments.
+
+Call the provided function, `fn`, with up to `n` arguments, using `Array.prototype.slice(0,n)` and the spread operator (`...`).
+
+```js
+const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
+```
+
+
+Examples
+
+```js
+const firstTwoMax = ary(Math.max, 2);
+[[2, 6, 'a'], [8, 4, 6], [10]].map(x => firstTwoMax(...x)); // [6, 8, 10]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### call
@@ -353,8 +540,8 @@ Use a closure to call a stored key with stored arguments.
```js
const call = (key, ...args) => context => context[key](...args);
-```
-
+```
+
Examples
@@ -372,7 +559,6 @@ Promise.resolve([1, 2, 3])
[⬆ Back to top](#table-of-contents)
-
### collectInto
Changes a function that accepts an array into a variadic function.
@@ -381,8 +567,8 @@ Given a function, return a closure that collects all inputs into an array-accept
```js
const collectInto = fn => (...args) => fn(args);
-```
-
+```
+
Examples
@@ -391,24 +577,23 @@ const Pall = collectInto(Promise.all.bind(Promise));
let p1 = Promise.resolve(1);
let p2 = Promise.resolve(2);
let p3 = new Promise(resolve => setTimeout(resolve, 2000, 3));
-Pall(p1, p2, p3).then(console.log);
+Pall(p1, p2, p3).then(console.log); // [1, 2, 3] (after about 2 seconds)
```
[⬆ Back to top](#table-of-contents)
-
### flip
-Flip takes a function as an argument, then makes the first argument the last
+Flip takes a function as an argument, then makes the first argument the last.
Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest.
```js
-const flip = fn => (...args) => fn(args.pop(), ...args);
-```
-
+const flip = fn => (first, ...rest) => fn(...rest, first);
+```
+
Examples
@@ -426,12 +611,88 @@ Object.assign(b, a); // == b
[⬆ Back to top](#table-of-contents)
+### over
+
+Creates a function that invokes each provided function with the arguments it receives and returns the results.
+
+Use `Array.prototype.map()` and `Function.prototype.apply()` to apply each function to the given arguments.
+
+```js
+const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args));
+```
+
+
+Examples
+
+```js
+const minMax = over(Math.min, Math.max);
+minMax(1, 2, 3, 4, 5); // [1,5]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### overArgs
+
+Creates a function that invokes the provided function with its arguments transformed.
+
+Use `Array.prototype.map()` to apply `transforms` to `args` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`.
+
+```js
+const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val)));
+```
+
+
+Examples
+
+```js
+const square = n => n * n;
+const double = n => n * 2;
+const fn = overArgs((x, y) => [x, y], [square, double]);
+fn(9, 3); // [81, 6]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### pipeAsyncFunctions
+
+Performs left-to-right function composition for asynchronous functions.
+
+Use `Array.prototype.reduce()` with the spread operator (`...`) to perform left-to-right function composition using `Promise.then()`.
+The functions can return a combination of: simple values, `Promise`'s, or they can be defined as `async` ones returning through `await`.
+All functions must be unary.
+
+```js
+const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg));
+```
+
+
+Examples
+
+```js
+const sum = pipeAsyncFunctions(
+ x => x + 1,
+ x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)),
+ x => x + 3,
+ async x => (await x) + 4
+);
+(async () => {
+ console.log(await sum(5)); // 15 (after one second)
+})();
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### pipeFunctions
Performs left-to-right function composition.
-Use `Array.reduce()` with the spread operator (`...`) to perform left-to-right function composition.
+Use `Array.prototype.reduce()` with the spread operator (`...`) to perform left-to-right function composition.
The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.
```js
@@ -452,7 +713,6 @@ multiplyAndAdd5(5, 2); // 15
[⬆ Back to top](#table-of-contents)
-
### promisify
Converts an asynchronous function to return a promise.
@@ -481,6 +741,32 @@ delay(2000).then(() => console.log('Hi!')); // // Promise resolves after 2s
[⬆ Back to top](#table-of-contents)
+### rearg
+
+Creates a function that invokes the provided function with its arguments arranged according to the specified indexes.
+
+Use `Array.prototype.map()` to reorder arguments based on `indexes` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`.
+
+```js
+const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i]));
+```
+
+
+Examples
+
+```js
+var rearged = rearg(
+ function(a, b, c) {
+ return [a, b, c];
+ },
+ [2, 0, 1]
+);
+rearged('b', 'c', 'a'); // ['a', 'b', 'c']
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### spreadOver
@@ -490,8 +776,8 @@ Use closures and the spread operator (`...`) to map the array of arguments to th
```js
const spreadOver = fn => argsArr => fn(...argsArr);
-```
-
+```
+
Examples
@@ -504,15 +790,175 @@ arrayMax([1, 2, 3]); // 3
[⬆ Back to top](#table-of-contents)
+### unary
+
+Creates a function that accepts up to one argument, ignoring any additional arguments.
+
+Call the provided function, `fn`, with just the first argument given.
+
+```js
+const unary = fn => val => fn(val);
+```
+
+
+Examples
+
+```js
+['6', '8', '10'].map(unary(parseInt)); // [6, 8, 10]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+
---
- ## 📚 Array
+
+## 📚 Array
+
+### all
+
+Returns `true` if the provided predicate function returns `true` for all elements in a collection, `false` otherwise.
+
+Use `Array.prototype.every()` to test if all elements in the collection return `true` based on `fn`.
+Omit the second argument, `fn`, to use `Boolean` as a default.
+
+```js
+const all = (arr, fn = Boolean) => arr.every(fn);
+```
+
+
+Examples
+
+```js
+all([4, 2, 3], x => x > 1); // true
+all([1, 2, 3]); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### allEqual
+
+Check if all elements in an array are equal.
+
+Use `Array.prototype.every()` to check if all the elements of the array are the same as the first one.
+
+```js
+const allEqual = arr => arr.every(val => val === arr[0]);
+```
+
+
+Examples
+
+```js
+allEqual([1, 2, 3, 4, 5, 6]); // false
+allEqual([1, 1, 1, 1]); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### any
+
+Returns `true` if the provided predicate function returns `true` for at least one element in a collection, `false` otherwise.
+
+Use `Array.prototype.some()` to test if any elements in the collection return `true` based on `fn`.
+Omit the second argument, `fn`, to use `Boolean` as a default.
+
+```js
+const any = (arr, fn = Boolean) => arr.some(fn);
+```
+
+
+Examples
+
+```js
+any([0, 1, 2, 0], x => x >= 2); // true
+any([0, 0, 1, 0]); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### arrayToCSV
+
+Converts a 2D array to a comma-separated values (CSV) string.
+
+Use `Array.prototype.map()` and `Array.prototype.join(delimiter)` to combine individual 1D arrays (rows) into strings.
+Use `Array.prototype.join('\n')` to combine all rows into a CSV string, separating each row with a newline.
+Omit the second argument, `delimiter`, to use a default delimiter of `,`.
+
+```js
+const arrayToCSV = (arr, delimiter = ',') =>
+ arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n');
+```
+
+
+Examples
+
+```js
+arrayToCSV([['a', 'b'], ['c', 'd']]); // '"a","b"\n"c","d"'
+arrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '"a";"b"\n"c";"d"'
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### bifurcate
+
+Splits values into two groups. If an element in `filter` is truthy, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.
+
+Use `Array.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on `filter`.
+
+```js
+const bifurcate = (arr, filter) =>
+ arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);
+```
+
+
+Examples
+
+```js
+bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); // [ ['beep', 'boop', 'bar'], ['foo'] ]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### bifurcateBy
+
+Splits values into two groups according to a predicate function, which specifies which group an element in the input collection belongs to. If the predicate function returns a truthy value, the collection element belongs to the first group; otherwise, it belongs to the second group.
+
+Use `Array.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on the value returned by `fn` for each element.
+
+```js
+const bifurcateBy = (arr, fn) =>
+ arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);
+```
+
+
+Examples
+
+```js
+bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b'); // [ ['beep', 'boop', 'bar'], ['foo'] ]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### chunk
Chunks an array into smaller arrays of a specified size.
Use `Array.from()` to create a new array, that fits the number of chunks that will be produced.
-Use `Array.slice()` to map each element of the new array to a chunk the length of `size`.
+Use `Array.prototype.slice()` to map each element of the new array to a chunk the length of `size`.
If the original array can't be split evenly, the final chunk will contain the remaining elements.
```js
@@ -533,12 +979,11 @@ chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]]
[⬆ Back to top](#table-of-contents)
-
### compact
Removes falsey values from an array.
-Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`).
+Use `Array.prototype.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`).
```js
const compact = arr => arr.filter(Boolean);
@@ -555,15 +1000,41 @@ compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [ 1, 2, 3, 'a'
[⬆ Back to top](#table-of-contents)
+### countBy
+
+Groups the elements of an array based on the given function and returns the count of elements in each group.
+
+Use `Array.prototype.map()` to map the values of an array to a function or property name.
+Use `Array.prototype.reduce()` to create an object, where the keys are produced from the mapped results.
+
+```js
+const countBy = (arr, fn) =>
+ arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {
+ acc[val] = (acc[val] || 0) + 1;
+ return acc;
+ }, {});
+```
+
+
+Examples
+
+```js
+countBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2}
+countBy(['one', 'two', 'three'], 'length'); // {3: 2, 5: 1}
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### countOccurrences
Counts the occurrences of a value in an array.
-Use `Array.reduce()` to increment a counter each time you encounter the specific value inside the array.
+Use `Array.prototype.reduce()` to increment a counter each time you encounter the specific value inside the array.
```js
-const countOccurrences = (arr, value) => arr.reduce((a, v) => (v === value ? a + 1 : a + 0), 0);
+const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
```
@@ -577,13 +1048,12 @@ countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3
[⬆ Back to top](#table-of-contents)
-
### deepFlatten
Deep flattens an array.
Use recursion.
-Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array.
+Use `Array.prototype.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array.
Recursively flatten each element that is an array.
```js
@@ -601,12 +1071,11 @@ deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]
[⬆ Back to top](#table-of-contents)
-
### difference
Returns the difference between two arrays.
-Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values not contained in `b`.
+Create a `Set` from `b`, then use `Array.prototype.filter()` on `a` to only keep values not contained in `b`.
```js
const difference = (a, b) => {
@@ -626,12 +1095,36 @@ difference([1, 2, 3], [1, 2, 4]); // [3]
[⬆ Back to top](#table-of-contents)
+### differenceBy
+
+Returns the difference between two arrays, after applying the provided function to each array element of both.
+
+Create a `Set` by applying `fn` to each element in `b`, then use `Array.prototype.filter()` in combination with `fn` on `a` to only keep values not contained in the previously created set.
+
+```js
+const differenceBy = (a, b, fn) => {
+ const s = new Set(b.map(v => fn(v)));
+ return a.filter(x => !s.has(fn(x)));
+};
+```
+
+
+Examples
+
+```js
+differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1.2]
+differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x); // [ { x: 2 } ]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### differenceWith
Filters out all values from an array for which the comparator function does not return `true`.
-Use `Array.filter()` and `Array.findIndex()` to find the appropriate values.
+Use `Array.prototype.filter()` and `Array.prototype.findIndex()` to find the appropriate values.
```js
const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);
@@ -648,60 +1141,34 @@ differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Mat
[⬆ Back to top](#table-of-contents)
+### drop
-### distinctValuesOfArray
+Returns a new array with `n` elements removed from the left.
-Returns all the distinct values of an array.
-
-Use ES6 `Set` and the `...rest` operator to discard all duplicated values.
+Use `Array.prototype.slice()` to slice the remove the specified number of elements from the left.
```js
-const distinctValuesOfArray = arr => [...new Set(arr)];
+const drop = (arr, n = 1) => arr.slice(n);
```
Examples
```js
-distinctValuesOfArray([1, 2, 2, 3, 4, 4, 5]); // [1,2,3,4,5]
+drop([1, 2, 3]); // [2,3]
+drop([1, 2, 3], 2); // [3]
+drop([1, 2, 3], 42); // []
```
[⬆ Back to top](#table-of-contents)
-
-### dropElements
-
-Removes elements in an array until the passed function returns `true`. Returns the remaining elements in the array.
-
-Loop through the array, using `Array.slice()` to drop the first element of the array until the returned value from the function is `true`.
-Returns the remaining elements.
-
-```js
-const dropElements = (arr, func) => {
- while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
- return arr;
-};
-```
-
-
-Examples
-
-```js
-dropElements([1, 2, 3, 4], n => n >= 3); // [3,4]
-```
-
-
-
- [⬆ Back to top](#table-of-contents)
-
-
### dropRight
Returns a new array with `n` elements removed from the right.
-Use `Array.slice()` to slice the remove the specified number of elements from the right.
+Use `Array.prototype.slice()` to slice the remove the specified number of elements from the right.
```js
const dropRight = (arr, n = 1) => arr.slice(0, -n);
@@ -720,12 +1187,61 @@ dropRight([1, 2, 3], 42); // []
[⬆ Back to top](#table-of-contents)
+### dropRightWhile
+
+Removes elements from the end of an array until the passed function returns `true`. Returns the remaining elements in the array.
+
+Loop through the array, using `Array.prototype.slice()` to drop the last element of the array until the returned value from the function is `true`.
+Returns the remaining elements.
+
+```js
+const dropRightWhile = (arr, func) => {
+ while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1);
+ return arr;
+};
+```
+
+
+Examples
+
+```js
+dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### dropWhile
+
+Removes elements in an array until the passed function returns `true`. Returns the remaining elements in the array.
+
+Loop through the array, using `Array.prototype.slice()` to drop the first element of the array until the returned value from the function is `true`.
+Returns the remaining elements.
+
+```js
+const dropWhile = (arr, func) => {
+ while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
+ return arr;
+};
+```
+
+
+Examples
+
+```js
+dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### everyNth
Returns every nth element in an array.
-Use `Array.filter()` to create a new array that contains every nth element of a given array.
+Use `Array.prototype.filter()` to create a new array that contains every nth element of a given array.
```js
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
@@ -742,12 +1258,11 @@ everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ]
[⬆ Back to top](#table-of-contents)
-
### filterNonUnique
Filters out the non-unique values in an array.
-Use `Array.filter()` for an array containing only the unique values.
+Use `Array.prototype.filter()` for an array containing only the unique values.
```js
const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
@@ -757,74 +1272,153 @@ const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexO
Examples
```js
-filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1,3,5]
+filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1, 3, 5]
```
[⬆ Back to top](#table-of-contents)
+### filterNonUniqueBy
-### flatten
+Filters out the non-unique values in an array, based on a provided comparator function.
-Flattens an array.
-
-Use a new array and concatenate it with the spread input array causing a shallow denesting of any contained arrays.
+Use `Array.prototype.filter()` and `Array.prototype.every()` for an array containing only the unique values, based on the comparator function, `fn`.
+The comparator function takes four arguments: the values of the two elements being compared and their indexes.
```js
-const flatten = arr => [].concat(...arr);
+const filterNonUniqueBy = (arr, fn) =>
+ arr.filter((v, i) => arr.every((x, j) => (i === j) === fn(v, x, i, j)));
```
Examples
```js
-flatten([1, [2], 3, 4]); // [1,2,3,4]
+filterNonUniqueBy(
+ [
+ { id: 0, value: 'a' },
+ { id: 1, value: 'b' },
+ { id: 2, value: 'c' },
+ { id: 1, value: 'd' },
+ { id: 0, value: 'e' }
+ ],
+ (a, b) => a.id == b.id
+); // [ { id: 2, value: 'c' } ]
```
[⬆ Back to top](#table-of-contents)
+### findLast
-### flattenDepth
+Returns the last element for which the provided function returns a truthy value.
+
+Use `Array.prototype.filter()` to remove elements for which `fn` returns falsey values, `Array.prototype.pop()` to get the last one.
+
+```js
+const findLast = (arr, fn) => arr.filter(fn).pop();
+```
+
+
+Examples
+
+```js
+findLast([1, 2, 3, 4], n => n % 2 === 1); // 3
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### findLastIndex
+
+Returns the index of the last element for which the provided function returns a truthy value.
+
+Use `Array.prototype.map()` to map each element to an array with its index and value.
+Use `Array.prototype.filter()` to remove elements for which `fn` returns falsey values, `Array.prototype.pop()` to get the last one.
+
+```js
+const findLastIndex = (arr, fn) =>
+ arr
+ .map((val, i) => [i, val])
+ .filter(([i, val]) => fn(val, i, arr))
+ .pop()[0];
+```
+
+
+Examples
+
+```js
+findLastIndex([1, 2, 3, 4], n => n % 2 === 1); // 2 (index of the value 3)
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### flatten
Flattens an array up to the specified depth.
Use recursion, decrementing `depth` by 1 for each level of depth.
-Use `Array.reduce()` and `Array.concat()` to merge elements or arrays.
+Use `Array.prototype.reduce()` and `Array.prototype.concat()` to merge elements or arrays.
Base case, for `depth` equal to `1` stops recursion.
-Omit the second element, `depth` to flatten only to a depth of `1` (single flatten).
+Omit the second argument, `depth` to flatten only to a depth of `1` (single flatten).
```js
-const flattenDepth = (arr, depth = 1) =>
- depth != 1
- ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flattenDepth(v, depth - 1) : v), [])
- : arr.reduce((a, v) => a.concat(v), []);
+const flatten = (arr, depth = 1) =>
+ arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);
```
Examples
```js
-flattenDepth([1, [2], 3, 4]); // [1,2,3,4]
+flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
+flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]
```
[⬆ Back to top](#table-of-contents)
+### forEachRight
+
+Executes a provided function once for each array element, starting from the array's last element.
+
+Use `Array.prototype.slice(0)` to clone the given array, `Array.prototype.reverse()` to reverse it and `Array.prototype.forEach()` to iterate over the reversed array.
+
+```js
+const forEachRight = (arr, callback) =>
+ arr
+ .slice(0)
+ .reverse()
+ .forEach(callback);
+```
+
+
+Examples
+
+```js
+forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1'
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### groupBy
Groups the elements of an array based on the given function.
-Use `Array.map()` to map the values of an array to a function or property name.
-Use `Array.reduce()` to create an object, where the keys are produced from the mapped results.
+Use `Array.prototype.map()` to map the values of an array to a function or property name.
+Use `Array.prototype.reduce()` to create an object, where the keys are produced from the mapped results.
```js
-const groupBy = (arr, func) =>
- arr.map(typeof func === 'function' ? func : val => val[func]).reduce((acc, val, i) => {
+const groupBy = (arr, fn) =>
+ arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {
acc[val] = (acc[val] || []).concat(arr[i]);
return acc;
}, {});
@@ -842,7 +1436,6 @@ groupBy(['one', 'two', 'three'], 'length'); // {3: ['one', 'two'], 5: ['three']}
[⬆ Back to top](#table-of-contents)
-
### head
Returns the head of a list.
@@ -864,6 +1457,29 @@ head([1, 2, 3]); // 1
[⬆ Back to top](#table-of-contents)
+### indexOfAll
+
+Returns all indices of `val` in an array.
+If `val` never occurs, returns `[]`.
+
+Use `Array.prototype.reduce()` to loop over elements and store indices for matching elements.
+Return the array of indices.
+
+```js
+const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);
+```
+
+
+Examples
+
+```js
+indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3]
+indexOfAll([1, 2, 3], 4); // []
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### initial
@@ -886,18 +1502,15 @@ initial([1, 2, 3]); // [1,2]
[⬆ Back to top](#table-of-contents)
-
### initialize2DArray
Initializes a 2D array of given width and height and value.
-Use `Array.map()` to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to `null`.
+Use `Array.prototype.map()` to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to `null`.
```js
const initialize2DArray = (w, h, val = null) =>
- Array(h)
- .fill()
- .map(() => Array(w).fill(val));
+ Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val));
```
@@ -911,18 +1524,17 @@ initialize2DArray(2, 2, 0); // [[0,0], [0,0]]
[⬆ Back to top](#table-of-contents)
-
### initializeArrayWithRange
-Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive with there common difference `step`.
+Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive with their common difference `step`.
-Use `Array(Math.ceil((end+1-start)/step)` to create an array of the desired length(the amounts of elements is equal to `(end-start)/step` or `(end+1-start)/step` for inclusive end), `Array.map()` to fill with the desired values in a range.
+Use `Array.from()` to create an array of the desired length, `(end - start + 1)/step`, and a map function to fill it with the desired values in the given range.
You can omit `start` to use a default value of `0`.
You can omit `step` to use a default value of `1`.
```js
const initializeArrayWithRange = (end, start = 0, step = 1) =>
- Array.from({ length: Math.ceil((end + 1 - start) / step) }).map((v, i) => i * step + start);
+ Array.from({ length: Math.ceil((end - start + 1) / step) }, (v, i) => i * step + start);
```
@@ -938,35 +1550,87 @@ initializeArrayWithRange(9, 0, 2); // [0,2,4,6,8]
[⬆ Back to top](#table-of-contents)
+### initializeArrayWithRangeRight
-### initializeArrayWithValues
+Initializes an array containing the numbers in the specified range (in reverse) where `start` and `end` are inclusive with their common difference `step`.
-Initializes and fills an array with the specified values.
-
-Use `Array(n)` to create an array of the desired length, `fill(v)` to fill it with the desired values.
-You can omit `value` to use a default value of `0`.
+Use `Array.from(Math.ceil((end+1-start)/step))` to create an array of the desired length(the amounts of elements is equal to `(end-start)/step` or `(end+1-start)/step` for inclusive end), `Array.prototype.map()` to fill with the desired values in a range.
+You can omit `start` to use a default value of `0`.
+You can omit `step` to use a default value of `1`.
```js
-const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value);
+const initializeArrayWithRangeRight = (end, start = 0, step = 1) =>
+ Array.from({ length: Math.ceil((end + 1 - start) / step) }).map(
+ (v, i, arr) => (arr.length - i - 1) * step + start
+ );
```
Examples
```js
-initializeArrayWithValues(5, 2); // [2,2,2,2,2]
+initializeArrayWithRangeRight(5); // [5,4,3,2,1,0]
+initializeArrayWithRangeRight(7, 3); // [7,6,5,4,3]
+initializeArrayWithRangeRight(9, 0, 2); // [8,6,4,2,0]
```
[⬆ Back to top](#table-of-contents)
+### initializeArrayWithValues
+
+Initializes and fills an array with the specified values.
+
+Use `Array(n)` to create an array of the desired length, `fill(v)` to fill it with the desired values.
+You can omit `val` to use a default value of `0`.
+
+```js
+const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val);
+```
+
+
+Examples
+
+```js
+initializeArrayWithValues(5, 2); // [2, 2, 2, 2, 2]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### initializeNDArray
+
+Create a n-dimensional array with given value.
+
+Use recursion.
+Use `Array.prototype.map()` to generate rows where each is a new array initialized using `initializeNDArray`.
+
+```js
+const initializeNDArray = (val, ...args) =>
+ args.length === 0
+ ? val
+ : Array.from({ length: args[0] }).map(() => initializeNDArray(val, ...args.slice(1)));
+```
+
+
+Examples
+
+```js
+initializeNDArray(1, 3); // [1,1,1]
+initializeNDArray(5, 2, 2, 2); // [[[5,5],[5,5]],[[5,5],[5,5]]]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### intersection
Returns a list of elements that exist in both arrays.
-Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values contained in `b`.
+Create a `Set` from `b`, then use `Array.prototype.filter()` on `a` to only keep values contained in `b`.
```js
const intersection = (a, b) => {
@@ -979,13 +1643,57 @@ const intersection = (a, b) => {
Examples
```js
-intersection([1, 2, 3], [4, 3, 2]); // [2,3]
+intersection([1, 2, 3], [4, 3, 2]); // [2, 3]
```
[⬆ Back to top](#table-of-contents)
+### intersectionBy
+
+Returns a list of elements that exist in both arrays, after applying the provided function to each array element of both.
+
+Create a `Set` by applying `fn` to all elements in `b`, then use `Array.prototype.filter()` on `a` to only keep elements, which produce values contained in `b` when `fn` is applied to them.
+
+```js
+const intersectionBy = (a, b, fn) => {
+ const s = new Set(b.map(fn));
+ return a.filter(x => s.has(fn(x)));
+};
+```
+
+
+Examples
+
+```js
+intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### intersectionWith
+
+Returns a list of elements that exist in both arrays, using a provided comparator function.
+
+Use `Array.prototype.filter()` and `Array.prototype.findIndex()` in combination with the provided comparator to determine intersecting values.
+
+```js
+const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1);
+```
+
+
+Examples
+
+```js
+intersectionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // [1.5, 3, 0]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### isSorted
@@ -997,10 +1705,12 @@ Return `0` if the `direction` changes or the `direction` if the last element is
```js
const isSorted = arr => {
- const direction = arr[0] > arr[1] ? -1 : 1;
- for (let [i, val] of arr.entries())
- if (i === arr.length - 1) return direction;
+ let direction = -(arr[0] - arr[1]);
+ for (let [i, val] of arr.entries()) {
+ direction = !direction ? -(arr[i - 1] - arr[i]) : direction;
+ if (i === arr.length - 1) return !direction ? 0 : direction;
else if ((val - arr[i + 1]) * direction > 0) return 0;
+ }
};
```
@@ -1017,12 +1727,12 @@ isSorted([4, 3, 5]); // 0
[⬆ Back to top](#table-of-contents)
-
### join
-Joins all elements of an array into a string and returns this string. Uses a separator and an end separator.
+Joins all elements of an array into a string and returns this string.
+Uses a separator and an end separator.
-Use `Array.reduce()` to combine elements into a string.
+Use `Array.prototype.reduce()` to combine elements into a string.
Omit the second argument, `separator`, to use a default separator of `','`.
Omit the third argument, `end`, to use the same value as `separator` by default.
@@ -1030,9 +1740,11 @@ Omit the third argument, `end`, to use the same value as `separator` by default.
const join = (arr, separator = ',', end = separator) =>
arr.reduce(
(acc, val, i) =>
- i == arr.length - 2
+ i === arr.length - 2
? acc + val + end
- : i == arr.length - 1 ? acc + val : acc + val + separator,
+ : i === arr.length - 1
+ ? acc + val
+ : acc + val + separator,
''
);
```
@@ -1050,6 +1762,39 @@ join(['pen', 'pineapple', 'apple', 'pen']); // "pen,pineapple,apple,pen"
[⬆ Back to top](#table-of-contents)
+### JSONtoCSV 
+
+Converts an array of objects to a comma-separated values (CSV) string that contains only the `columns` specified.
+
+Use `Array.prototype.join(demiliter)` to combine all the names in `columns` to create the first row.
+Use `Array.prototype.map()` and `Array.prototype.reduce()` to create a row for each object, substituting non-existent values with empty strings and only mapping values in `columns`.
+Use `Array.prototype.join('\n')` to combine all rows into a string.
+Omit the third argument, `delimiter`, to use a default delimiter of `,`.
+
+```js
+const JSONtoCSV = (arr, columns, delimiter = ',') =>
+ [
+ columns.join(delimiter),
+ ...arr.map(obj =>
+ columns.reduce(
+ (acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`,
+ ''
+ )
+ )
+ ].join('\n');
+```
+
+
+Examples
+
+```js
+JSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b']); // 'a,b\n"1","2"\n"3","4"\n"6",""\n"","7"'
+JSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b'], ';'); // 'a;b\n"1";"2"\n"3";"4"\n"6";""\n"";"7"'
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### last
@@ -1072,8 +1817,35 @@ last([1, 2, 3]); // 3
[⬆ Back to top](#table-of-contents)
+### longestItem
-### mapObject
+Takes any number of iterable objects or objects with a `length` property and returns the longest one.
+If multiple objects have the same length, the first one will be returned.
+Returns `undefined` if no arguments are provided.
+
+Use `Array.prototype.reduce()`, comparing the `length` of objects to find the longest one.
+
+```js
+const longestItem = (val, ...vals) =>
+ [val, ...vals].reduce((a, x) => (x.length > a.length ? x : a));
+```
+
+
+Examples
+
+```js
+longestItem('this', 'is', 'a', 'testcase'); // 'testcase'
+longestItem(...['a', 'ab', 'abc']); // 'abc'
+longestItem(...['a', 'ab', 'abc'], 'abcd'); // 'abcd'
+longestItem([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]); // [1, 2, 3, 4, 5]
+longestItem([1, 2, 3], 'foobar'); // 'foobar'
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### mapObject 
Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value.
@@ -1098,13 +1870,13 @@ squareIt([1, 2, 3]); // { 1: 1, 2: 4, 3: 9 }
[⬆ Back to top](#table-of-contents)
-
### maxN
-Returns the `n` maximum elements from the provided array. If `n` is greater than or equal to the provided array's length, then return the original array(sorted in descending order).
+Returns the `n` maximum elements from the provided array.
+If `n` is greater than or equal to the provided array's length, then return the original array (sorted in descending order).
-Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in descending order.
-Use `Array.slice()` to get the specified number of elements.
+Use `Array.prototype.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in descending order.
+Use `Array.prototype.slice()` to get the specified number of elements.
Omit the second argument, `n`, to get a one-element array.
```js
@@ -1123,18 +1895,19 @@ maxN([1, 2, 3], 2); // [3,2]
[⬆ Back to top](#table-of-contents)
-
### minN
-Returns the `n` minimum elements from the provided array. If `n` is greater than or equal to the provided array's length, then return the original array(sorted in ascending order).
+Returns the `n` minimum elements from the provided array.
+If `n` is greater than or equal to the provided array's length, then return the original array (sorted in ascending order).
-Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in ascending order.
-Use `Array.slice()` to get the specified number of elements.
+Use `Array.prototype.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in ascending order.
+Use `Array.prototype.slice()` to get the specified number of elements.
Omit the second argument, `n`, to get a one-element array.
```js
const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
```
+
Examples
@@ -1147,17 +1920,39 @@ minN([1, 2, 3], 2); // [1,2]
[⬆ Back to top](#table-of-contents)
+### none
+
+Returns `true` if the provided predicate function returns `false` for all elements in a collection, `false` otherwise.
+
+Use `Array.prototype.some()` to test if any elements in the collection return `true` based on `fn`.
+Omit the second argument, `fn`, to use `Boolean` as a default.
+
+```js
+const none = (arr, fn = Boolean) => !arr.some(fn);
+```
+
+
+Examples
+
+```js
+none([0, 1, 3, 0], x => x == 2); // true
+none([0, 0, 0]); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### nthElement
Returns the nth element of an array.
-Use `Array.slice()` to get an array containing the nth element at the first place.
-If the index is out of bounds, return `[]`.
+Use `Array.prototype.slice()` to get an array containing the nth element at the first place.
+If the index is out of bounds, return `undefined`.
Omit the second argument, `n`, to get the first element of the array.
```js
-const nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
+const nthElement = (arr, n = 0) => (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0];
```
@@ -1172,36 +1967,101 @@ nthElement(['a', 'b', 'b'], -3); // 'a'
[⬆ Back to top](#table-of-contents)
+### offset
-### pick
+Moves the specified amount of elements to the end of the array.
-Picks the key-value pairs corresponding to the given keys from an object.
-
-Use `Array.reduce()` to convert the filtered/picked keys back to an object with the corresponding key-value pair if the key exists in the obj.
+Use `Array.prototype.slice()` twice to get the elements after the specified index and the elements before that.
+Use the spread operator(`...`) to combine the two into one array.
+If `offset` is negative, the elements will be moved from end to start.
```js
-const pick = (obj, arr) =>
- arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
+const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)];
```
Examples
```js
-pick({ a: 1, b: '2', c: 3 }, ['a', 'c']); // { 'a': 1, 'c': 3 }
+offset([1, 2, 3, 4, 5], 2); // [3, 4, 5, 1, 2]
+offset([1, 2, 3, 4, 5], -2); // [4, 5, 1, 2, 3]
```
[⬆ Back to top](#table-of-contents)
+### partition
+
+Groups the elements into two arrays, depending on the provided function's truthiness for each element.
+
+Use `Array.prototype.reduce()` to create an array of two arrays.
+Use `Array.prototype.push()` to add elements for which `fn` returns `true` to the first array and elements for which `fn` returns `false` to the second one.
+
+```js
+const partition = (arr, fn) =>
+ arr.reduce(
+ (acc, val, i, arr) => {
+ acc[fn(val, i, arr) ? 0 : 1].push(val);
+ return acc;
+ },
+ [[], []]
+ );
+```
+
+
+Examples
+
+```js
+const users = [{ user: 'barney', age: 36, active: false }, { user: 'fred', age: 40, active: true }];
+partition(users, o => o.active); // [[{ 'user': 'fred', 'age': 40, 'active': true }],[{ 'user': 'barney', 'age': 36, 'active': false }]]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### permutations 
+
+⚠️ **WARNING**: This function's execution time increases exponentially with each array element. Anything more than 8 to 10 entries will cause your browser to hang as it tries to solve all the different combinations.
+
+Generates all permutations of an array's elements (contains duplicates).
+
+Use recursion.
+For each element in the given array, create all the partial permutations for the rest of its elements.
+Use `Array.prototype.map()` to combine the element with each partial permutation, then `Array.prototype.reduce()` to combine all permutations in one array.
+Base cases are for array `length` equal to `2` or `1`.
+
+```js
+const permutations = arr => {
+ if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
+ return arr.reduce(
+ (acc, item, i) =>
+ acc.concat(
+ permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [item, ...val])
+ ),
+ []
+ );
+};
+```
+
+
+Examples
+
+```js
+permutations([1, 33, 5]); // [ [ 1, 33, 5 ], [ 1, 5, 33 ], [ 33, 1, 5 ], [ 33, 5, 1 ], [ 5, 1, 33 ], [ 5, 33, 1 ] ]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### pull
Mutates the original array to filter out the values specified.
-Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed.
-Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
+Use `Array.prototype.filter()` and `Array.prototype.includes()` to pull out the values that are not needed.
+Use `Array.prototype.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.prototype.push()` to re-populate it with only the pulled values.
_(For a snippet that does not mutate the original array see [`without`](#without))_
@@ -1226,14 +2086,13 @@ pull(myArray, 'a', 'c'); // myArray = [ 'b', 'b' ]
[⬆ Back to top](#table-of-contents)
-
-### pullAtIndex
+### pullAtIndex 
Mutates the original array to filter out the values at the specified indexes.
-Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed.
-Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
-Use `Array.push()` to keep track of pulled values
+Use `Array.prototype.filter()` and `Array.prototype.includes()` to pull out the values that are not needed.
+Use `Array.prototype.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.prototype.push()` to re-populate it with only the pulled values.
+Use `Array.prototype.push()` to keep track of pulled values
```js
const pullAtIndex = (arr, pullArr) => {
@@ -1259,14 +2118,13 @@ let pulled = pullAtIndex(myArray, [1, 3]); // myArray = [ 'a', 'c' ] , pulled =
[⬆ Back to top](#table-of-contents)
-
-### pullAtValue
+### pullAtValue 
Mutates the original array to filter out the values specified. Returns the removed elements.
-Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed.
-Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
-Use `Array.push()` to keep track of pulled values
+Use `Array.prototype.filter()` and `Array.prototype.includes()` to pull out the values that are not needed.
+Use `Array.prototype.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.prototype.push()` to re-populate it with only the pulled values.
+Use `Array.prototype.push()` to keep track of pulled values
```js
const pullAtValue = (arr, pullArr) => {
@@ -1291,45 +2149,45 @@ let pulled = pullAtValue(myArray, ['b', 'd']); // myArray = [ 'a', 'c' ] , pulle
[⬆ Back to top](#table-of-contents)
+### pullBy 
-### quickSort
+Mutates the original array to filter out the values specified, based on a given iterator function.
-QuickSort an Array (ascending sort by default).
-
-Use recursion.
-Use `Array.filter` and spread operator (`...`) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it.
-If the parameter `desc` is truthy, return array sorts in descending order.
+Check if the last argument provided in a function.
+Use `Array.prototype.map()` to apply the iterator function `fn` to all array elements.
+Use `Array.prototype.filter()` and `Array.prototype.includes()` to pull out the values that are not needed.
+Use `Array.prototype.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.prototype.push()` to re-populate it with only the pulled values.
```js
-const quickSort = ([n, ...nums], desc) =>
- isNaN(n)
- ? []
- : [
- ...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc),
- n,
- ...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc)
- ];
+const pullBy = (arr, ...args) => {
+ const length = args.length;
+ let fn = length > 1 ? args[length - 1] : undefined;
+ fn = typeof fn == 'function' ? (args.pop(), fn) : undefined;
+ let argState = (Array.isArray(args[0]) ? args[0] : args).map(val => fn(val));
+ let pulled = arr.filter((v, i) => !argState.includes(fn(v)));
+ arr.length = 0;
+ pulled.forEach(v => arr.push(v));
+};
```
Examples
```js
-quickSort([4, 1, 3, 2]); // [1,2,3,4]
-quickSort([4, 1, 3, 2], true); // [4,3,2,1]
+var myArray = [{ x: 1 }, { x: 2 }, { x: 3 }, { x: 1 }];
+pullBy(myArray, [{ x: 1 }, { x: 3 }], o => o.x); // myArray = [{ x: 2 }]
```
[⬆ Back to top](#table-of-contents)
-
### reducedFilter
Filter an array of objects based on a condition while also filtering out unspecified keys.
-Use `Array.filter()` to filter the array based on the predicate `fn` so that it returns the objects for which the condition returned a truthy value.
-On the filtered array, use `Array.map()` to return the new object using `Array.reduce()` to filter out the keys which were not supplied as the `keys` argument.
+Use `Array.prototype.filter()` to filter the array based on the predicate `fn` so that it returns the objects for which the condition returned a truthy value.
+On the filtered array, use `Array.prototype.map()` to return the new object using `Array.prototype.reduce()` to filter out the keys which were not supplied as the `keys` argument.
```js
const reducedFilter = (data, keys, fn) =>
@@ -1365,12 +2223,81 @@ reducedFilter(data, ['id', 'name'], item => item.age > 24); // [{ id: 2, name: '
[⬆ Back to top](#table-of-contents)
+### reduceSuccessive
+
+Applies a function against an accumulator and each element in the array (from left to right), returning an array of successively reduced values.
+
+Use `Array.prototype.reduce()` to apply the given function to the given array, storing each new result.
+
+```js
+const reduceSuccessive = (arr, fn, acc) =>
+ arr.reduce((res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res), [acc]);
+```
+
+
+Examples
+
+```js
+reduceSuccessive([1, 2, 3, 4, 5, 6], (acc, val) => acc + val, 0); // [0, 1, 3, 6, 10, 15, 21]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### reduceWhich
+
+Returns the minimum/maximum value of an array, after applying the provided function to set comparing rule.
+
+Use `Array.prototype.reduce()` in combination with the `comparator` function to get the appropriate element in the array.
+You can omit the second parameter, `comparator`, to use the default one that returns the minimum element in the array.
+
+```js
+const reduceWhich = (arr, comparator = (a, b) => a - b) =>
+ arr.reduce((a, b) => (comparator(a, b) >= 0 ? b : a));
+```
+
+
+Examples
+
+```js
+reduceWhich([1, 3, 2]); // 1
+reduceWhich([1, 3, 2], (a, b) => b - a); // 3
+reduceWhich(
+ [{ name: 'Tom', age: 12 }, { name: 'Jack', age: 18 }, { name: 'Lucy', age: 9 }],
+ (a, b) => a.age - b.age
+); // {name: "Lucy", age: 9}
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### reject
+
+Takes a predicate and array, like `Array.prototype.filter()`, but only keeps `x` if `pred(x) === false`.
+
+```js
+const reject = (pred, array) => array.filter((...args) => !pred(...args));
+```
+
+
+Examples
+
+```js
+reject(x => x % 2 === 0, [1, 2, 3, 4, 5]); // [1, 3, 5]
+reject(word => word.length > 4, ['Apple', 'Pear', 'Kiwi', 'Banana']); // ['Pear', 'Kiwi']
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### remove
Removes elements from an array for which the given function returns `false`.
-Use `Array.filter()` to find array elements that return truthy values and `Array.reduce()` to remove elements using `Array.splice()`.
+Use `Array.prototype.filter()` to find array elements that return truthy values and `Array.prototype.reduce()` to remove elements using `Array.prototype.splice()`.
The `func` is invoked with three arguments (`value, index, array`).
```js
@@ -1387,14 +2314,13 @@ const remove = (arr, func) =>
Examples
```js
-remove([1, 2, 3, 4], n => n % 2 == 0); // [2, 4]
+remove([1, 2, 3, 4], n => n % 2 === 0); // [2, 4]
```
[⬆ Back to top](#table-of-contents)
-
### sample
Returns a random element from an array.
@@ -1417,13 +2343,12 @@ sample([3, 7, 9, 11]); // 9
[⬆ Back to top](#table-of-contents)
-
### sampleSize
Gets `n` random elements at unique keys from `array` up to the size of `array`.
-Shuffle the array using the [Fisher-Yates algorithm](https://github.com/chalarangelo/30-seconds-of-code#shuffle).
-Use `Array.slice()` to get the first `n` elements.
+Shuffle the array using the [Fisher-Yates algorithm](https://github.com/30-seconds/30-seconds-of-code#shuffle).
+Use `Array.prototype.slice()` to get the first `n` elements.
Omit the second argument, `n` to get only one element at random from the array.
```js
@@ -1449,12 +2374,43 @@ sampleSize([1, 2, 3], 4); // [2,3,1]
[⬆ Back to top](#table-of-contents)
+### shank
+
+Has the same functionality as [`Array.prototype.prototype.splice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice), but returning a new array instead of mutating the original array.
+
+Use `Array.prototype.slice()` and `Array.prototype.concat()` to get a new array with the new contents after removing existing elements and/or adding new elements.
+Omit the second argument, `index`, to start at `0`.
+Omit the third argument, `delCount`, to remove `0` elements.
+Omit the fourth argument, `elements`, in order to not add any new elements.
+
+```js
+const shank = (arr, index = 0, delCount = 0, ...elements) =>
+ arr
+ .slice(0, index)
+ .concat(elements)
+ .concat(arr.slice(index + delCount));
+```
+
+
+Examples
+
+```js
+const names = ['alpha', 'bravo', 'charlie'];
+const namesAndDelta = shank(names, 1, 0, 'delta'); // [ 'alpha', 'delta', 'bravo', 'charlie' ]
+const namesNoBravo = shank(names, 1, 1); // [ 'alpha', 'charlie' ]
+console.log(names); // ['alpha', 'bravo', 'charlie']
+```
+
+
+
+
+ [⬆ Back to top](#table-of-contents)
### shuffle
Randomizes the order of the values of an array, returning a new array.
-Uses the Fisher-Yates algorithm to reorder the elements of the array, based on the [Lodash implementation](https://github.com/lodash/lodash/blob/b2ea6b1cd251796dcb5f9700c4911a7b6223920b/shuffle.js), but as a pure function.
+Uses the [Fisher-Yates algorithm](https://github.com/30-seconds/30-seconds-of-code#shuffle) to reorder the elements of the array.
```js
const shuffle = ([...arr]) => {
@@ -1472,19 +2428,18 @@ const shuffle = ([...arr]) => {
```js
const foo = [1, 2, 3];
-shuffle(foo); // [2,3,1], foo = [1,2,3]
+shuffle(foo); // [2, 3, 1], foo = [1, 2, 3]
```
[⬆ Back to top](#table-of-contents)
-
### similarity
Returns an array of elements that appear in both arrays.
-Use `filter()` to remove values that are not part of `values`, determined using `includes()`.
+Use `Array.prototype.filter()` to remove values that are not part of `values`, determined using `Array.prototype.includes()`.
```js
const similarity = (arr, values) => arr.filter(v => values.includes(v));
@@ -1494,20 +2449,19 @@ const similarity = (arr, values) => arr.filter(v => values.includes(v));
Examples
```js
-similarity([1, 2, 3], [1, 2, 4]); // [1,2]
+similarity([1, 2, 3], [1, 2, 4]); // [1, 2]
```
[⬆ Back to top](#table-of-contents)
-
### sortedIndex
Returns the lowest index at which value should be inserted into array in order to maintain its sort order.
Check if the array is sorted in descending order (loosely).
-Use `Array.findIndex()` to find the appropriate index where the element should be inserted.
+Use `Array.prototype.findIndex()` to find the appropriate index where the element should be inserted.
```js
const sortedIndex = (arr, n) => {
@@ -1529,12 +2483,124 @@ sortedIndex([30, 50], 40); // 1
[⬆ Back to top](#table-of-contents)
+### sortedIndexBy
+
+Returns the lowest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function.
+
+Check if the array is sorted in descending order (loosely).
+Use `Array.prototype.findIndex()` to find the appropriate index where the element should be inserted, based on the iterator function `fn`.
+
+```js
+const sortedIndexBy = (arr, n, fn) => {
+ const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]);
+ const val = fn(n);
+ const index = arr.findIndex(el => (isDescending ? val >= fn(el) : val <= fn(el)));
+ return index === -1 ? arr.length : index;
+};
+```
+
+
+Examples
+
+```js
+sortedIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, o => o.x); // 0
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### sortedLastIndex
+
+Returns the highest index at which value should be inserted into array in order to maintain its sort order.
+
+Check if the array is sorted in descending order (loosely).
+Use `Array.prototype.reverse()` and `Array.prototype.findIndex()` to find the appropriate last index where the element should be inserted.
+
+```js
+const sortedLastIndex = (arr, n) => {
+ const isDescending = arr[0] > arr[arr.length - 1];
+ const index = arr.reverse().findIndex(el => (isDescending ? n <= el : n >= el));
+ return index === -1 ? 0 : arr.length - index;
+};
+```
+
+
+Examples
+
+```js
+sortedLastIndex([10, 20, 30, 30, 40], 30); // 4
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### sortedLastIndexBy
+
+Returns the highest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function.
+
+Check if the array is sorted in descending order (loosely).
+Use `Array.prototype.map()` to apply the iterator function to all elements of the array.
+Use `Array.prototype.reverse()` and `Array.prototype.findIndex()` to find the appropriate last index where the element should be inserted, based on the provided iterator function.
+
+```js
+const sortedLastIndexBy = (arr, n, fn) => {
+ const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]);
+ const val = fn(n);
+ const index = arr
+ .map(fn)
+ .reverse()
+ .findIndex(el => (isDescending ? val <= el : val >= el));
+ return index === -1 ? 0 : arr.length - index;
+};
+```
+
+
+Examples
+
+```js
+sortedLastIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, o => o.x); // 1
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### stableSort 
+
+Performs stable sorting of an array, preserving the initial indexes of items when their values are the same.
+Does not mutate the original array, but returns a new array instead.
+
+Use `Array.prototype.map()` to pair each element of the input array with its corresponding index.
+Use `Array.prototype.sort()` and a `compare` function to sort the list, preserving their initial order if the items compared are equal.
+Use `Array.prototype.map()` to convert back to the initial array items.
+
+```js
+const stableSort = (arr, compare) =>
+ arr
+ .map((item, index) => ({ item, index }))
+ .sort((a, b) => compare(a.item, b.item) || a.index - b.index)
+ .map(({ item }) => item);
+```
+
+
+Examples
+
+```js
+const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
+const stable = stableSort(arr, () => 0); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### symmetricDifference
-Returns the symmetric difference between two arrays.
+Returns the symmetric difference between two arrays, without filtering out duplicate values.
-Create a `Set` from each array, then use `Array.filter()` on each of them to only keep values not contained in the other.
+Create a `Set` from each array, then use `Array.prototype.filter()` on each of them to only keep values not contained in the other.
```js
const symmetricDifference = (a, b) => {
@@ -1548,19 +2614,72 @@ const symmetricDifference = (a, b) => {
Examples
```js
-symmetricDifference([1, 2, 3], [1, 2, 4]); // [3,4]
+symmetricDifference([1, 2, 3], [1, 2, 4]); // [3, 4]
+symmetricDifference([1, 2, 2], [1, 3, 1]); // [2, 2, 3]
```
[⬆ Back to top](#table-of-contents)
+### symmetricDifferenceBy
+
+Returns the symmetric difference between two arrays, after applying the provided function to each array element of both.
+
+Create a `Set` by applying `fn` to each array's elements, then use `Array.prototype.filter()` on each of them to only keep values not contained in the other.
+
+```js
+const symmetricDifferenceBy = (a, b, fn) => {
+ const sA = new Set(a.map(v => fn(v))),
+ sB = new Set(b.map(v => fn(v)));
+ return [...a.filter(x => !sB.has(fn(x))), ...b.filter(x => !sA.has(fn(x)))];
+};
+```
+
+
+Examples
+
+```js
+symmetricDifferenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [ 1.2, 3.4 ]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### symmetricDifferenceWith
+
+Returns the symmetric difference between two arrays, using a provided function as a comparator.
+
+Use `Array.prototype.filter()` and `Array.prototype.findIndex()` to find the appropriate values.
+
+```js
+const symmetricDifferenceWith = (arr, val, comp) => [
+ ...arr.filter(a => val.findIndex(b => comp(a, b)) === -1),
+ ...val.filter(a => arr.findIndex(b => comp(a, b)) === -1)
+];
+```
+
+
+Examples
+
+```js
+symmetricDifferenceWith(
+ [1, 1.2, 1.5, 3, 0],
+ [1.9, 3, 0, 3.9],
+ (a, b) => Math.round(a) === Math.round(b)
+); // [1, 1.2, 3.9]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### tail
Returns all elements in an array except for the first one.
-Return `arr.slice(1)` if the array's `length` is more than `1`, otherwise, return the whole array.
+Return `Array.prototype.slice(1)` if the array's `length` is more than `1`, otherwise, return the whole array.
```js
const tail = arr => (arr.length > 1 ? arr.slice(1) : arr);
@@ -1578,12 +2697,11 @@ tail([1]); // [1]
[⬆ Back to top](#table-of-contents)
-
### take
Returns an array with n elements removed from the beginning.
-Use `Array.slice()` to create a slice of the array with `n` elements taken from the beginning.
+Use `Array.prototype.slice()` to create a slice of the array with `n` elements taken from the beginning.
```js
const take = (arr, n = 1) => arr.slice(0, n);
@@ -1601,12 +2719,11 @@ take([1, 2, 3], 0); // []
[⬆ Back to top](#table-of-contents)
-
### takeRight
Returns an array with n elements removed from the end.
-Use `Array.slice()` to create a slice of the array with `n` elements taken from the end.
+Use `Array.prototype.slice()` to create a slice of the array with `n` elements taken from the end.
```js
const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length);
@@ -1624,6 +2741,90 @@ takeRight([1, 2, 3]); // [3]
[⬆ Back to top](#table-of-contents)
+### takeRightWhile
+
+Removes elements from the end of an array until the passed function returns `true`. Returns the removed elements.
+
+Loop through the array, using a `Array.prototype.reduceRight()` and accumulating elements while the function returns falsy value.
+
+```js
+const takeRightWhile = (arr, func) =>
+ arr.reduceRight((acc, el) => (func(el) ? acc : [el, ...acc]), []);
+```
+
+
+Examples
+
+```js
+takeRightWhile([1, 2, 3, 4], n => n < 3); // [3, 4]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### takeWhile
+
+Removes elements in an array until the passed function returns `true`. Returns the removed elements.
+
+Loop through the array, using a `for...of` loop over `Array.prototype.entries()` until the returned value from the function is `true`.
+Return the removed elements, using `Array.prototype.slice()`.
+
+```js
+const takeWhile = (arr, func) => {
+ for (const [i, val] of arr.entries()) if (func(val)) return arr.slice(0, i);
+ return arr;
+};
+```
+
+
+Examples
+
+```js
+takeWhile([1, 2, 3, 4], n => n >= 3); // [1, 2]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### toHash
+
+Reduces a given Array-like into a value hash (keyed data store).
+
+Given an Iterable or Array-like structure, call `Array.prototype.prototype.reduce.call()` on the provided object to step over it and return an Object, keyed by the reference value.
+
+```js
+const toHash = (object, key) =>
+ Array.prototype.reduce.call(
+ object,
+ (acc, data, index) => ((acc[!key ? index : data[key]] = data), acc),
+ {}
+ );
+```
+
+
+Examples
+
+```js
+toHash([4, 3, 2, 1]); // { 0: 4, 1: 3, 2: 2, 1: 1 }
+toHash([{ a: 'label' }], 'a'); // { label: { a: 'label' } }
+// A more in depth example:
+let users = [{ id: 1, first: 'Jon' }, { id: 2, first: 'Joe' }, { id: 3, first: 'Moe' }];
+let managers = [{ manager: 1, employees: [2, 3] }];
+// We use function here because we want a bindable reference, but a closure referencing the hash would work, too.
+managers.forEach(
+ manager =>
+ (manager.employees = manager.employees.map(function(id) {
+ return this[id];
+ }, toHash(users, 'id')))
+);
+managers; // [ { manager:1, employees: [ { id: 2, first: "Joe" }, { id: 3, first: "Moe" } ] } ]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### union
@@ -1646,12 +2847,234 @@ union([1, 2, 3], [4, 3, 2]); // [1,2,3,4]
[⬆ Back to top](#table-of-contents)
+### unionBy
+
+Returns every element that exists in any of the two arrays once, after applying the provided function to each array element of both.
+
+Create a `Set` by applying all `fn` to all values of `a`.
+Create a `Set` from `a` and all elements in `b` whose value, after applying `fn` does not match a value in the previously created set.
+Return the last set converted to an array.
+
+```js
+const unionBy = (a, b, fn) => {
+ const s = new Set(a.map(v => fn(v)));
+ return Array.from(new Set([...a, ...b.filter(x => !s.has(fn(x)))]));
+};
+```
+
+
+Examples
+
+```js
+unionBy([2.1], [1.2, 2.3], Math.floor); // [2.1, 1.2]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### unionWith
+
+Returns every element that exists in any of the two arrays once, using a provided comparator function.
+
+Create a `Set` with all values of `a` and values in `b` for which the comparator finds no matches in `a`, using `Array.prototype.findIndex()`.
+
+```js
+const unionWith = (a, b, comp) =>
+ Array.from(new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)]));
+```
+
+
+Examples
+
+```js
+unionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2, 1.5, 3, 0, 3.9]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### uniqueElements
+
+Returns all unique values of an array.
+
+Use ES6 `Set` and the `...rest` operator to discard all duplicated values.
+
+```js
+const uniqueElements = arr => [...new Set(arr)];
+```
+
+
+Examples
+
+```js
+uniqueElements([1, 2, 2, 3, 4, 4, 5]); // [1, 2, 3, 4, 5]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### uniqueElementsBy
+
+Returns all unique values of an array, based on a provided comparator function.
+
+Use `Array.prototype.reduce()` and `Array.prototype.some()` for an array containing only the first unique occurence of each value, based on the comparator function, `fn`.
+The comparator function takes two arguments: the values of the two elements being compared.
+
+```js
+const uniqueElementsBy = (arr, fn) =>
+ arr.reduce((acc, v) => {
+ if (!acc.some(x => fn(v, x))) acc.push(v);
+ return acc;
+ }, []);
+```
+
+
+Examples
+
+```js
+uniqueElementsBy(
+ [
+ { id: 0, value: 'a' },
+ { id: 1, value: 'b' },
+ { id: 2, value: 'c' },
+ { id: 1, value: 'd' },
+ { id: 0, value: 'e' }
+ ],
+ (a, b) => a.id == b.id
+); // [ { id: 0, value: 'a' }, { id: 1, value: 'b' }, { id: 2, value: 'c' } ]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### uniqueElementsByRight
+
+Returns all unique values of an array, based on a provided comparator function.
+
+Use `Array.prototype.reduce()` and `Array.prototype.some()` for an array containing only the last unique occurence of each value, based on the comparator function, `fn`.
+The comparator function takes two arguments: the values of the two elements being compared.
+
+```js
+const uniqueElementsByRight = (arr, fn) =>
+ arr.reduceRight((acc, v) => {
+ if (!acc.some(x => fn(v, x))) acc.push(v);
+ return acc;
+ }, []);
+```
+
+
+Examples
+
+```js
+uniqueElementsByRight(
+ [
+ { id: 0, value: 'a' },
+ { id: 1, value: 'b' },
+ { id: 2, value: 'c' },
+ { id: 1, value: 'd' },
+ { id: 0, value: 'e' }
+ ],
+ (a, b) => a.id == b.id
+); // [ { id: 0, value: 'e' }, { id: 1, value: 'd' }, { id: 2, value: 'c' } ]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### uniqueSymmetricDifference
+
+Returns the unique symmetric difference between two arrays, not containing duplicate values from either array.
+
+Use `Array.prototype.filter()` and `Array.prototype.includes()` on each array to remove values contained in the other, then create a `Set` from the results, removing duplicate values.
+
+```js
+const uniqueSymmetricDifference = (a, b) => [
+ ...new Set([...a.filter(v => !b.includes(v)), ...b.filter(v => !a.includes(v))])
+];
+```
+
+
+Examples
+
+```js
+uniqueSymmetricDifference([1, 2, 3], [1, 2, 4]); // [3, 4]
+uniqueSymmetricDifference([1, 2, 2], [1, 3, 1]); // [2, 3]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### unzip
+
+Creates an array of arrays, ungrouping the elements in an array produced by [zip](#zip).
+
+Use `Math.max.apply()` to get the longest subarray in the array, `Array.prototype.map()` to make each element an array.
+Use `Array.prototype.reduce()` and `Array.prototype.forEach()` to map grouped values to individual arrays.
+
+```js
+const unzip = arr =>
+ arr.reduce(
+ (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc),
+ Array.from({
+ length: Math.max(...arr.map(x => x.length))
+ }).map(x => [])
+ );
+```
+
+
+Examples
+
+```js
+unzip([['a', 1, true], ['b', 2, false]]); //[['a', 'b'], [1, 2], [true, false]]
+unzip([['a', 1, true], ['b', 2]]); //[['a', 'b'], [1, 2], [true]]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### unzipWith 
+
+Creates an array of elements, ungrouping the elements in an array produced by [zip](#zip) and applying the provided function.
+
+Use `Math.max.apply()` to get the longest subarray in the array, `Array.prototype.map()` to make each element an array.
+Use `Array.prototype.reduce()` and `Array.prototype.forEach()` to map grouped values to individual arrays.
+Use `Array.prototype.map()` and the spread operator (`...`) to apply `fn` to each individual group of elements.
+
+```js
+const unzipWith = (arr, fn) =>
+ arr
+ .reduce(
+ (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc),
+ Array.from({
+ length: Math.max(...arr.map(x => x.length))
+ }).map(x => [])
+ )
+ .map(val => fn(...val));
+```
+
+
+Examples
+
+```js
+unzipWith([[1, 10, 100], [2, 20, 200]], (...args) => args.reduce((acc, v) => acc + v, 0)); // [3, 30, 300]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### without
Filters out the elements of an array, that have one of the specified values.
-Use `Array.filter()` to create an array excluding(using `!Array.includes()`) all given values.
+Use `Array.prototype.filter()` to create an array excluding(using `!Array.includes()`) all given values.
_(For a snippet that mutates the original array see [`pull`](#pull))_
@@ -1670,6 +3093,26 @@ without([2, 1, 2, 3], 1, 2); // [3]
[⬆ Back to top](#table-of-contents)
+### xProd
+
+Creates a new array out of the two supplied by creating each possible pair from the arrays.
+
+Use `Array.prototype.reduce()`, `Array.prototype.map()` and `Array.prototype.concat()` to produce every possible pair from the elements of the two arrays and save them in an array.
+
+```js
+const xProd = (a, b) => a.reduce((acc, x) => acc.concat(b.map(y => [x, y])), []);
+```
+
+
+Examples
+
+```js
+xProd([1, 2], ['a', 'b']); // [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### zip
@@ -1700,12 +3143,11 @@ zip(['a'], [1, 2], [true, false]); // [['a', 1, true], [undefined, 2, false]]
[⬆ Back to top](#table-of-contents)
-
### zipObject
Given an array of valid property identifiers and an array of values, return an object associating the properties to the values.
-Since an object can have undefined values but not undefined property pointers, the array of properties is used to decide the structure of the resulting object using `Array.reduce()`.
+Since an object can have undefined values but not undefined property pointers, the array of properties is used to decide the structure of the resulting object using `Array.prototype.reduce()`.
```js
const zipObject = (props, values) =>
@@ -1724,18 +3166,60 @@ zipObject(['a', 'b'], [1, 2, 3]); // {a: 1, b: 2}
[⬆ Back to top](#table-of-contents)
+### zipWith 
+
+Creates an array of elements, grouped based on the position in the original arrays and using function as the last value to specify how grouped values should be combined.
+
+Check if the last argument provided is a function.
+Use `Math.max()` to get the longest array in the arguments.
+Creates an array with that length as return value and use `Array.from()` with a map-function to create an array of grouped elements.
+If lengths of the argument-arrays vary, `undefined` is used where no value could be found.
+The function is invoked with the elements of each group `(...group)`.
+
+```js
+const zipWith = (...array) => {
+ const fn = typeof array[array.length - 1] === 'function' ? array.pop() : undefined;
+ return Array.from(
+ { length: Math.max(...array.map(a => a.length)) },
+ (_, i) => (fn ? fn(...array.map(a => a[i])) : array.map(a => a[i]))
+ );
+};
+```
+
+
+Examples
+
+```js
+zipWith([1, 2], [10, 20], [100, 200], (a, b, c) => a + b + c); // [111,222]
+zipWith(
+ [1, 2, 3],
+ [10, 20],
+ [100, 200],
+ (a, b, c) => (a != null ? a : 'a') + (b != null ? b : 'b') + (c != null ? c : 'c')
+); // [111, 222, '3bc']
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+
---
- ## 🌐 Browser
+
+## 🌐 Browser
### arrayToHtmlList
Converts the given array elements into `
` tags and appends them to the list of the given id.
-Use `Array.map()` and `document.querySelector()` to create a list of html tags.
+Use `Array.prototype.map()`, `document.querySelector()`, and an anonymous inner closure to create a list of html tags.
```js
const arrayToHtmlList = (arr, listID) =>
- arr.map(item => (document.querySelector('#' + listID).innerHTML += `
`).join(''))
+ ))();
```
@@ -1749,7 +3233,6 @@ arrayToHtmlList(['item 1', 'item 2'], 'myListID');
[⬆ Back to top](#table-of-contents)
-
### bottomVisible
Returns `true` if the bottom of the page is visible, `false` otherwise.
@@ -1773,10 +3256,12 @@ bottomVisible(); // true
[⬆ Back to top](#table-of-contents)
+### copyToClipboard 
-### copyToClipboard
+⚠️ **NOTICE:** The same functionality can be easily implemented by using the new asynchronous Clipboard API, which is still experimental but should be used in the future instead of this snippet. Find out more about it [here](https://github.com/w3c/clipboard-apis/blob/master/explainer.adoc#writing-to-the-clipboard).
-Copy a string to the clipboard. Only works as a result of user action (i.e. inside a `click` event listener).
+Copy a string to the clipboard.
+Only works as a result of user action (i.e. inside a `click` event listener).
Create a new ` [⬆ Back to top](#table-of-contents)
-
### standardDeviation
Returns the standard deviation of an array of numbers.
-Use `Array.reduce()` to calculate the mean, variance and the sum of the variance of the values, the variance of the values, then
+Use `Array.prototype.reduce()` to calculate the mean, variance and the sum of the variance of the values, the variance of the values, then
determine the standard deviation.
You can omit the second argument to get the sample standard deviation or set it to `true` to get the population standard deviation.
@@ -3596,34 +6075,55 @@ standardDeviation([10, 2, 38, 23, 38, 23, 21], true); // 12.29899614287479 (popu
[⬆ Back to top](#table-of-contents)
-
### sum
Returns the sum of two or more numbers/arrays.
-Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`.
+Use `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`.
```js
-const sum = (...arr) => [].concat(...arr).reduce((acc, val) => acc + val, 0);
+const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);
```
Examples
```js
-sum([1, 2, 3, 4]); // 10
+sum(...[1, 2, 3, 4]); // 10
```
[⬆ Back to top](#table-of-contents)
+### sumBy
+
+Returns the sum of an array, after mapping each element to a value using the provided function.
+
+Use `Array.prototype.map()` to map each element to the value returned by `fn`, `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`.
+
+```js
+const sumBy = (arr, fn) =>
+ arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0);
+```
+
+
+Examples
+
+```js
+sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 20
+sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 20
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### sumPower
Returns the sum of the powers of all the numbers from `start` to `end` (both inclusive).
-Use `Array.fill()` to create an array of all the numbers in the target range, `Array.map()` and the exponent operator (`**`) to raise them to `power` and `Array.reduce()` to add them together.
+Use `Array.prototype.fill()` to create an array of all the numbers in the target range, `Array.prototype.map()` and the exponent operator (`**`) to raise them to `power` and `Array.prototype.reduce()` to add them together.
Omit the second argument, `power`, to use a default power of `2`.
Omit the third argument, `start`, to use a default starting value of `1`.
@@ -3648,14 +6148,123 @@ sumPower(10, 3, 5); //2925
[⬆ Back to top](#table-of-contents)
+### toSafeInteger
+
+Converts a value to a safe integer.
+
+Use `Math.max()` and `Math.min()` to find the closest safe value.
+Use `Math.round()` to convert to an integer.
+
+```js
+const toSafeInteger = num =>
+ Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER));
+```
+
+
+Examples
+
+```js
+toSafeInteger('3.2'); // 3
+toSafeInteger(Infinity); // 9007199254740991
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+
---
- ## 📦 Node
+
+## 📦 Node
+
+### atob
+
+Decodes a string of data which has been encoded using base-64 encoding.
+
+Create a `Buffer` for the given string with base-64 encoding and use `Buffer.toString('binary')` to return the decoded string.
+
+```js
+const atob = str => Buffer.from(str, 'base64').toString('binary');
+```
+
+
+Examples
+
+```js
+atob('Zm9vYmFy'); // 'foobar'
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### btoa
+
+Creates a base-64 encoded ASCII string from a String object in which each character in the string is treated as a byte of binary data.
+
+Create a `Buffer` for the given string with binary encoding and use `Buffer.toString('base64')` to return the encoded string.
+
+```js
+const btoa = str => Buffer.from(str, 'binary').toString('base64');
+```
+
+
+Examples
+
+```js
+btoa('foobar'); // 'Zm9vYmFy'
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### colorize
+
+Add special characters to text to print in color in the console (combined with `console.log()`).
+
+Use template literals and special characters to add the appropriate color code to the string output.
+For background colors, add a special character that resets the background color at the end of the string.
+
+```js
+const colorize = (...args) => ({
+ black: `\x1b[30m${args.join(' ')}`,
+ red: `\x1b[31m${args.join(' ')}`,
+ green: `\x1b[32m${args.join(' ')}`,
+ yellow: `\x1b[33m${args.join(' ')}`,
+ blue: `\x1b[34m${args.join(' ')}`,
+ magenta: `\x1b[35m${args.join(' ')}`,
+ cyan: `\x1b[36m${args.join(' ')}`,
+ white: `\x1b[37m${args.join(' ')}`,
+ bgBlack: `\x1b[40m${args.join(' ')}\x1b[0m`,
+ bgRed: `\x1b[41m${args.join(' ')}\x1b[0m`,
+ bgGreen: `\x1b[42m${args.join(' ')}\x1b[0m`,
+ bgYellow: `\x1b[43m${args.join(' ')}\x1b[0m`,
+ bgBlue: `\x1b[44m${args.join(' ')}\x1b[0m`,
+ bgMagenta: `\x1b[45m${args.join(' ')}\x1b[0m`,
+ bgCyan: `\x1b[46m${args.join(' ')}\x1b[0m`,
+ bgWhite: `\x1b[47m${args.join(' ')}\x1b[0m`
+});
+```
+
+
+Examples
+
+```js
+console.log(colorize('foo').red); // 'foo' (red letters)
+console.log(colorize('foo', 'bar').bgBlue); // 'foo bar' (blue background)
+console.log(colorize(colorize('foo').yellow, colorize('foo').green).bgWhite); // 'foo bar' (first word in yellow letters, second word in green letters, white background for both)
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### hasFlags
Check if the current process's arguments contain the specified flags.
-Use `Array.every()` and `Array.includes()` to check if `process.argv` contains all the specified flags.
+Use `Array.prototype.every()` and `Array.prototype.includes()` to check if `process.argv` contains all the specified flags.
Use a regular expression to test if the specified flags are prefixed with `-` or `--` and prefix them accordingly.
```js
@@ -3677,6 +6286,119 @@ hasFlags('special'); // false
[⬆ Back to top](#table-of-contents)
+### hashNode
+
+Creates a hash for a value using the [SHA-256](https://en.wikipedia.org/wiki/SHA-2) algorithm. Returns a promise.
+
+Use `crypto` API to create a hash for the given value.
+
+```js
+const crypto = require('crypto');
+const hashNode = val =>
+ new Promise(resolve =>
+ setTimeout(
+ () =>
+ resolve(
+ crypto
+ .createHash('sha256')
+ .update(val)
+ .digest('hex')
+ ),
+ 0
+ )
+ );
+```
+
+
+Examples
+
+```js
+hashNode(JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })).then(console.log); // '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isDuplexStream
+
+Checks if the given argument is a duplex (readable and writable) stream.
+
+Check if the value is different from `null`, use `typeof` to check if a value is of type `object` and the `pipe` property is of type `function`.
+Additionally check if the `typeof` the `_read`, `_write` and `_readableState`, `_writableState` properties are `function` and `object` respectively.
+
+```js
+const isDuplexStream = val =>
+ val !== null &&
+ typeof val === 'object' &&
+ typeof val.pipe === 'function' &&
+ typeof val._read === 'function' &&
+ typeof val._readableState === 'object' &&
+ typeof val._write === 'function' &&
+ typeof val._writableState === 'object';
+```
+
+
+Examples
+
+```js
+const Stream = require('stream');
+isDuplexStream(new Stream.Duplex()); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isReadableStream
+
+Checks if the given argument is a readable stream.
+
+Check if the value is different from `null`, use `typeof` to check if the value is of type `object` and the `pipe` property is of type `function`.
+Additionally check if the `typeof` the `_read` and `_readableState` properties are `function` and `object` respectively.
+
+```js
+const isReadableStream = val =>
+ val !== null &&
+ typeof val === 'object' &&
+ typeof val.pipe === 'function' &&
+ typeof val._read === 'function' &&
+ typeof val._readableState === 'object';
+```
+
+
+Examples
+
+```js
+const fs = require('fs');
+isReadableStream(fs.createReadStream('test.txt')); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isStream
+
+Checks if the given argument is a stream.
+
+Check if the value is different from `null`, use `typeof` to check if the value is of type `object` and the `pipe` property is of type `function`.
+
+```js
+const isStream = val => val !== null && typeof val === 'object' && typeof val.pipe === 'function';
+```
+
+
+Examples
+
+```js
+const fs = require('fs');
+isStream(fs.createReadStream('test.txt')); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### isTravisCI
@@ -3699,6 +6421,33 @@ isTravisCI(); // true (if code is running on Travis CI)
[⬆ Back to top](#table-of-contents)
+### isWritableStream
+
+Checks if the given argument is a writable stream.
+
+Check if the value is different from `null`, use `typeof` to check if the value is of type `object` and the `pipe` property is of type `function`.
+Additionally check if the `typeof` the `_write` and `_writableState` properties are `function` and `object` respectively.
+
+```js
+const isWritableStream = val =>
+ val !== null &&
+ typeof val === 'object' &&
+ typeof val.pipe === 'function' &&
+ typeof val._write === 'function' &&
+ typeof val._writableState === 'object';
+```
+
+
+Examples
+
+```js
+const fs = require('fs');
+isWritableStream(fs.createWriteStream('test.txt')); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### JSONToFile
@@ -3723,7 +6472,6 @@ JSONToFile({ test: 'is passed' }, 'testJsonFile'); // writes the object to 'test
[⬆ Back to top](#table-of-contents)
-
### readFileLines
Returns an array of lines from the specified file.
@@ -3761,12 +6509,11 @@ console.log(arr); // ['line1', 'line2', 'line3']
[⬆ Back to top](#table-of-contents)
-
### untildify
Converts a tilde path to an absolute path.
-Use `String.replace()` with a regular expression and `OS.homedir()` to replace the `~` in the start of the path with the home directory.
+Use `String.prototype.replace()` with a regular expression and `OS.homedir()` to replace the `~` in the start of the path with the home directory.
```js
const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`);
@@ -3783,7 +6530,6 @@ untildify('~/node'); // '/Users/aUser/node'
[⬆ Back to top](#table-of-contents)
-
### UUIDGeneratorNode
Generates a UUID in Node.JS.
@@ -3809,26 +6555,62 @@ UUIDGeneratorNode(); // '79c7c136-60ee-40a2-beb2-856f1feabefc'
[⬆ Back to top](#table-of-contents)
+
---
- ## 🗃️ Object
-### cleanObj
+## 🗃️ Object
-Removes any properties except the ones specified from a JSON object.
+### bindAll
-Use `Object.keys()` method to loop over given JSON object and deleting keys that are not `include`d in given array.
-Also if you give it a special key (`childIndicator`) it will search deeply inside it to apply function to inner objects too.
+Binds methods of an object to the object itself, overwriting the existing method.
+
+Use `Array.prototype.forEach()` to return a `function` that uses `Function.prototype.apply()` to apply the given context (`obj`) to `fn` for each function specified.
```js
-const cleanObj = (obj, keysToKeep = [], childIndicator) => {
- Object.keys(obj).forEach(key => {
- if (key === childIndicator) {
- cleanObj(obj[key], keysToKeep, childIndicator);
- } else if (!keysToKeep.includes(key)) {
- delete obj[key];
- }
- });
- return obj;
+const bindAll = (obj, ...fns) =>
+ fns.forEach(
+ fn => (
+ (f = obj[fn]),
+ (obj[fn] = function() {
+ return f.apply(obj);
+ })
+ )
+ );
+```
+
+
+Examples
+
+```js
+var view = {
+ label: 'docs',
+ click: function() {
+ console.log('clicked ' + this.label);
+ }
+};
+bindAll(view, 'click');
+jQuery(element).on('click', view.click); // Logs 'clicked docs' when clicked.
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### deepClone
+
+Creates a deep clone of an object.
+
+Use recursion.
+Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original.
+Use `Object.keys()` and `Array.prototype.forEach()` to determine which key-value pairs need to be deep cloned.
+
+```js
+const deepClone = obj => {
+ let clone = Object.assign({}, obj);
+ Object.keys(clone).forEach(
+ key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
+ );
+ return Array.isArray(obj) ? (clone.length = obj.length) && Array.from(clone) : clone;
};
```
@@ -3836,25 +6618,210 @@ const cleanObj = (obj, keysToKeep = [], childIndicator) => {
Examples
```js
-const testObj = { a: 1, b: 2, children: { a: 1, b: 2 } };
-cleanObj(testObj, ['a'], 'children'); // { a: 1, children : { a: 1}}
+const a = { foo: 'bar', obj: { a: 1, b: 2 } };
+const b = deepClone(a); // a !== b, a.obj !== b.obj
```
[⬆ Back to top](#table-of-contents)
+### deepFreeze
-### invertKeyValues
+Deep freezes an object.
-Inverts the key-value pairs of an object, without mutating it.
-
-Use `Object.keys()` and `Array.reduce()` to invert the key-value pairs of an object.
+Calls `Object.freeze(obj)` recursively on all unfrozen properties of passed object that are `instanceof` object.
```js
-const invertKeyValues = obj =>
- Object.keys(obj).reduce((acc, key) => {
- acc[obj[key]] = key;
+const deepFreeze = obj =>
+ Object.keys(obj).forEach(
+ prop =>
+ !obj[prop] instanceof Object || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop])
+ ) || Object.freeze(obj);
+```
+
+
+Examples
+
+```js
+'use strict';
+
+const o = deepFreeze([1, [2, 3]]);
+
+o[0] = 3; // not allowed
+o[1][0] = 4; // not allowed as well
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### defaults
+
+Assigns default values for all properties in an object that are `undefined`.
+
+Use `Object.assign()` to create a new empty object and copy the original one to maintain key order, use `Array.prototype.reverse()` and the spread operator `...` to combine the default values from left to right, finally use `obj` again to overwrite properties that originally had a value.
+
+```js
+const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);
+```
+
+
+Examples
+
+```js
+defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }); // { a: 1, b: 2 }
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### dig
+
+Returns the target value in a nested JSON object, based on the given key.
+
+Use the `in` operator to check if `target` exists in `obj`.
+If found, return the value of `obj[target]`, otherwise use `Object.values(obj)` and `Array.prototype.reduce()` to recursively call `dig` on each nested object until the first matching key/value pair is found.
+
+```js
+const dig = (obj, target) =>
+ target in obj
+ ? obj[target]
+ : Object.values(obj).reduce((acc, val) => {
+ if (acc !== undefined) return acc;
+ if (typeof val === 'object') return dig(val, target);
+ }, undefined);
+```
+
+
+Examples
+
+```js
+const data = {
+ level1: {
+ level2: {
+ level3: 'some data'
+ }
+ }
+};
+dig(data, 'level3'); // 'some data'
+dig(data, 'level4'); // undefined
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### equals 
+
+Performs a deep comparison between two values to determine if they are equivalent.
+
+Check if the two values are identical, if they are both `Date` objects with the same time, using `Date.getTime()` or if they are both non-object values with an equivalent value (strict comparison).
+Check if only one value is `null` or `undefined` or if their prototypes differ.
+If none of the above conditions are met, use `Object.keys()` to check if both values have the same number of keys, then use `Array.prototype.every()` to check if every key in the first value exists in the second one and if they are equivalent by calling this method recursively.
+
+```js
+const equals = (a, b) => {
+ if (a === b) return true;
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
+ if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b;
+ if (a === null || a === undefined || b === null || b === undefined) return false;
+ if (a.prototype !== b.prototype) return false;
+ let keys = Object.keys(a);
+ if (keys.length !== Object.keys(b).length) return false;
+ return keys.every(k => equals(a[k], b[k]));
+};
+```
+
+
+Examples
+
+```js
+equals({ a: [2, { e: 3 }], b: [4], c: 'foo' }, { a: [2, { e: 3 }], b: [4], c: 'foo' }); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### findKey
+
+Returns the first key that satisfies the provided testing function. Otherwise `undefined` is returned.
+
+Use `Object.keys(obj)` to get all the properties of the object, `Array.prototype.find()` to test the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.
+
+```js
+const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));
+```
+
+
+Examples
+
+```js
+findKey(
+ {
+ barney: { age: 36, active: true },
+ fred: { age: 40, active: false },
+ pebbles: { age: 1, active: true }
+ },
+ o => o['active']
+); // 'barney'
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### findLastKey
+
+Returns the last key that satisfies the provided testing function.
+Otherwise `undefined` is returned.
+
+Use `Object.keys(obj)` to get all the properties of the object, `Array.prototype.reverse()` to reverse their order and `Array.prototype.find()` to test the provided function for each key-value pair.
+The callback receives three arguments - the value, the key and the object.
+
+```js
+const findLastKey = (obj, fn) =>
+ Object.keys(obj)
+ .reverse()
+ .find(key => fn(obj[key], key, obj));
+```
+
+
+Examples
+
+```js
+findLastKey(
+ {
+ barney: { age: 36, active: true },
+ fred: { age: 40, active: false },
+ pebbles: { age: 1, active: true }
+ },
+ o => o['active']
+); // 'pebbles'
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### flattenObject
+
+Flatten an object with the paths for keys.
+
+Use recursion.
+Use `Object.keys(obj)` combined with `Array.prototype.reduce()` to convert every leaf node to a flattened path node.
+If the value of a key is an object, the function calls itself with the appropriate `prefix` to create the path using `Object.assign()`.
+Otherwise, it adds the appropriate prefixed key-value pair to the accumulator object.
+You should always omit the second argument, `prefix`, unless you want every key to have a prefix.
+
+```js
+const flattenObject = (obj, prefix = '') =>
+ Object.keys(obj).reduce((acc, k) => {
+ const pre = prefix.length ? prefix + '.' : '';
+ if (typeof obj[k] === 'object') Object.assign(acc, flattenObject(obj[k], pre + k));
+ else acc[pre + k] = obj[k];
return acc;
}, {});
```
@@ -3863,19 +6830,155 @@ const invertKeyValues = obj =>
Examples
```js
-invertKeyValues({ name: 'John', age: 20 }); // { 20: 'age', John: 'name' }
+flattenObject({ a: { b: { c: 1 } }, d: 1 }); // { 'a.b.c': 1, d: 1 }
```
[⬆ Back to top](#table-of-contents)
+### forOwn
+
+Iterates over all own properties of an object, running a callback for each one.
+
+Use `Object.keys(obj)` to get all the properties of the object, `Array.prototype.forEach()` to run the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.
+
+```js
+const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));
+```
+
+
+Examples
+
+```js
+forOwn({ foo: 'bar', a: 1 }, v => console.log(v)); // 'bar', 1
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### forOwnRight
+
+Iterates over all own properties of an object in reverse, running a callback for each one.
+
+Use `Object.keys(obj)` to get all the properties of the object, `Array.prototype.reverse()` to reverse their order and `Array.prototype.forEach()` to run the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.
+
+```js
+const forOwnRight = (obj, fn) =>
+ Object.keys(obj)
+ .reverse()
+ .forEach(key => fn(obj[key], key, obj));
+```
+
+
+Examples
+
+```js
+forOwnRight({ foo: 'bar', a: 1 }, v => console.log(v)); // 1, 'bar'
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### functions
+
+Returns an array of function property names from own (and optionally inherited) enumerable properties of an object.
+
+Use `Object.keys(obj)` to iterate over the object's own properties.
+If `inherited` is `true`, use `Object.get.PrototypeOf(obj)` to also get the object's inherited properties.
+Use `Array.prototype.filter()` to keep only those properties that are functions.
+Omit the second argument, `inherited`, to not include inherited properties by default.
+
+```js
+const functions = (obj, inherited = false) =>
+ (inherited
+ ? [...Object.keys(obj), ...Object.keys(Object.getPrototypeOf(obj))]
+ : Object.keys(obj)
+ ).filter(key => typeof obj[key] === 'function');
+```
+
+
+Examples
+
+```js
+function Foo() {
+ this.a = () => 1;
+ this.b = () => 2;
+}
+Foo.prototype.c = () => 3;
+functions(new Foo()); // ['a', 'b']
+functions(new Foo(), true); // ['a', 'b', 'c']
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### get
+
+Retrieve a set of properties indicated by the given selectors from an object.
+
+Use `Array.prototype.map()` for each selector, `String.prototype.replace()` to replace square brackets with dots, `String.prototype.split('.')` to split each selector, `Array.prototype.filter()` to remove empty values and `Array.prototype.reduce()` to get the value indicated by it.
+
+```js
+const get = (from, ...selectors) =>
+ [...selectors].map(s =>
+ s
+ .replace(/\[([^\[\]]*)\]/g, '.$1.')
+ .split('.')
+ .filter(t => t !== '')
+ .reduce((prev, cur) => prev && prev[cur], from)
+ );
+```
+
+
+Examples
+
+```js
+const obj = { selector: { to: { val: 'val to select' } }, target: [1, 2, { a: 'test' }] };
+get(obj, 'selector.to.val', 'target[0]', 'target[2].a'); // ['val to select', 1, 'test']
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### invertKeyValues
+
+Inverts the key-value pairs of an object, without mutating it. The corresponding inverted value of each inverted key is an array of keys responsible for generating the inverted value. If a function is supplied, it is applied to each inverted key.
+
+Use `Object.keys()` and `Array.prototype.reduce()` to invert the key-value pairs of an object and apply the function provided (if any).
+Omit the second argument, `fn`, to get the inverted keys without applying a function to them.
+
+```js
+const invertKeyValues = (obj, fn) =>
+ Object.keys(obj).reduce((acc, key) => {
+ const val = fn ? fn(obj[key]) : obj[key];
+ acc[val] = acc[val] || [];
+ acc[val].push(key);
+ return acc;
+ }, {});
+```
+
+
+Examples
+
+```js
+invertKeyValues({ a: 1, b: 2, c: 1 }); // { 1: [ 'a', 'c' ], 2: [ 'b' ] }
+invertKeyValues({ a: 1, b: 2, c: 1 }, value => 'group' + value); // { group1: [ 'a', 'c' ], group2: [ 'b' ] }
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### lowercaseKeys
Creates a new object from the specified object, where all the keys are in lowercase.
-Use `Object.keys()` and `Array.reduce()` to create a new object from the specified object.
+Use `Object.keys()` and `Array.prototype.reduce()` to create a new object from the specified object.
Convert each key in the original object to lowercase, using `String.toLowerCase()`.
```js
@@ -3898,15 +7001,202 @@ const myObjLower = lowercaseKeys(myObj); // {name: 'Adam', surname: 'Smith'};
[⬆ Back to top](#table-of-contents)
+### mapKeys
+
+Creates an object with keys generated by running the provided function for each key and the same values as the provided object.
+
+Use `Object.keys(obj)` to iterate over the object's keys.
+Use `Array.prototype.reduce()` to create a new object with the same values and mapped keys using `fn`.
+
+```js
+const mapKeys = (obj, fn) =>
+ Object.keys(obj).reduce((acc, k) => {
+ acc[fn(obj[k], k, obj)] = obj[k];
+ return acc;
+ }, {});
+```
+
+
+Examples
+
+```js
+mapKeys({ a: 1, b: 2 }, (val, key) => key + val); // { a1: 1, b2: 2 }
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### mapValues
+
+Creates an object with the same keys as the provided object and values generated by running the provided function for each value.
+
+Use `Object.keys(obj)` to iterate over the object's keys.
+Use `Array.prototype.reduce()` to create a new object with the same keys and mapped values using `fn`.
+
+```js
+const mapValues = (obj, fn) =>
+ Object.keys(obj).reduce((acc, k) => {
+ acc[k] = fn(obj[k], k, obj);
+ return acc;
+ }, {});
+```
+
+
+Examples
+
+```js
+const users = {
+ fred: { user: 'fred', age: 40 },
+ pebbles: { user: 'pebbles', age: 1 }
+};
+mapValues(users, u => u.age); // { fred: 40, pebbles: 1 }
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### matches
+
+Compares two objects to determine if the first one contains equivalent property values to the second one.
+
+Use `Object.keys(source)` to get all the keys of the second object, then `Array.prototype.every()`, `Object.hasOwnProperty()` and strict comparison to determine if all keys exist in the first object and have the same values.
+
+```js
+const matches = (obj, source) =>
+ Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]);
+```
+
+
+Examples
+
+```js
+matches({ age: 25, hair: 'long', beard: true }, { hair: 'long', beard: true }); // true
+matches({ hair: 'long', beard: true }, { age: 25, hair: 'long', beard: true }); // false
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### matchesWith
+
+Compares two objects to determine if the first one contains equivalent property values to the second one, based on a provided function.
+
+Use `Object.keys(source)` to get all the keys of the second object, then `Array.prototype.every()`, `Object.hasOwnProperty()` and the provided function to determine if all keys exist in the first object and have equivalent values.
+If no function is provided, the values will be compared using the equality operator.
+
+```js
+const matchesWith = (obj, source, fn) =>
+ Object.keys(source).every(
+ key =>
+ obj.hasOwnProperty(key) && fn
+ ? fn(obj[key], source[key], key, obj, source)
+ : obj[key] == source[key]
+ );
+```
+
+
+Examples
+
+```js
+const isGreeting = val => /^h(?:i|ello)$/.test(val);
+matchesWith(
+ { greeting: 'hello' },
+ { greeting: 'hi' },
+ (oV, sV) => isGreeting(oV) && isGreeting(sV)
+); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### merge
+
+Creates a new object from the combination of two or more objects.
+
+Use `Array.prototype.reduce()` combined with `Object.keys(obj)` to iterate over all objects and keys.
+Use `hasOwnProperty()` and `Array.prototype.concat()` to append values for keys existing in multiple objects.
+
+```js
+const merge = (...objs) =>
+ [...objs].reduce(
+ (acc, obj) =>
+ Object.keys(obj).reduce((a, k) => {
+ acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k];
+ return acc;
+ }, {}),
+ {}
+ );
+```
+
+
+Examples
+
+```js
+const object = {
+ a: [{ x: 2 }, { y: 4 }],
+ b: 1
+};
+const other = {
+ a: { z: 3 },
+ b: [2, 3],
+ c: 'foo'
+};
+merge(object, other); // { a: [ { x: 2 }, { y: 4 }, { z: 3 } ], b: [ 1, 2, 3 ], c: 'foo' }
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### nest
+
+Given a flat array of objects linked to one another, it will nest them recursively.
+Useful for nesting comments, such as the ones on reddit.com.
+
+Use recursion.
+Use `Array.prototype.filter()` to filter the items where the `id` matches the `link`, then `Array.prototype.map()` to map each one to a new object that has a `children` property which recursively nests the items based on which ones are children of the current item.
+Omit the second argument, `id`, to default to `null` which indicates the object is not linked to another one (i.e. it is a top level object).
+Omit the third argument, `link`, to use `'parent_id'` as the default property which links the object to another one by its `id`.
+
+```js
+const nest = (items, id = null, link = 'parent_id') =>
+ items
+ .filter(item => item[link] === id)
+ .map(item => ({ ...item, children: nest(items, item.id) }));
+```
+
+
+Examples
+
+```js
+// One top level comment
+const comments = [
+ { id: 1, parent_id: null },
+ { id: 2, parent_id: 1 },
+ { id: 3, parent_id: 1 },
+ { id: 4, parent_id: 2 },
+ { id: 5, parent_id: 4 }
+];
+const nestedComments = nest(comments); // [{ id: 1, parent_id: null, children: [...] }]
+```
+
+
+
+
+ [⬆ Back to top](#table-of-contents)
### objectFromPairs
Creates an object from the given key-value pairs.
-Use `Array.reduce()` to create and combine key-value pairs.
+Use `Array.prototype.reduce()` to create and combine key-value pairs.
```js
-const objectFromPairs = arr => arr.reduce((a, v) => ((a[v[0]] = v[1]), a), {});
+const objectFromPairs = arr => arr.reduce((a, [key, val]) => ((a[key] = val), a), {});
```
@@ -3920,12 +7210,11 @@ objectFromPairs([['a', 1], ['b', 2]]); // {a: 1, b: 2}
[⬆ Back to top](#table-of-contents)
-
### objectToPairs
Creates an array of key-value pair arrays from an object.
-Use `Object.keys()` and `Array.map()` to iterate over the object's keys and produce an array with key-value pairs.
+Use `Object.keys()` and `Array.prototype.map()` to iterate over the object's keys and produce an array with key-value pairs.
```js
const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);
@@ -3935,20 +7224,69 @@ const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);
Examples
```js
-objectToPairs({ a: 1, b: 2 }); // [['a',1],['b',2]])
+objectToPairs({ a: 1, b: 2 }); // [ ['a', 1], ['b', 2] ]
```
[⬆ Back to top](#table-of-contents)
+### omit
+
+Omits the key-value pairs corresponding to the given keys from an object.
+
+Use `Object.keys(obj)`, `Array.prototype.filter()` and `Array.prototype.includes()` to remove the provided keys.
+Use `Array.prototype.reduce()` to convert the filtered keys back to an object with the corresponding key-value pairs.
+
+```js
+const omit = (obj, arr) =>
+ Object.keys(obj)
+ .filter(k => !arr.includes(k))
+ .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});
+```
+
+
+Examples
+
+```js
+omit({ a: 1, b: '2', c: 3 }, ['b']); // { 'a': 1, 'c': 3 }
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### omitBy
+
+Creates an object composed of the properties the given function returns falsey for. The function is invoked with two arguments: (value, key).
+
+Use `Object.keys(obj)` and `Array.prototype.filter()`to remove the keys for which `fn` returns a truthy value.
+Use `Array.prototype.reduce()` to convert the filtered keys back to an object with the corresponding key-value pairs.
+
+```js
+const omitBy = (obj, fn) =>
+ Object.keys(obj)
+ .filter(k => !fn(obj[k], k))
+ .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});
+```
+
+
+Examples
+
+```js
+omitBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number'); // { b: '2' }
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### orderBy
Returns a sorted array of objects ordered by properties and orders.
-Uses a custom implementation of sort, that reduces the props array argument with a default value of 0, it uses destructuring to swap the properties position depending on the order passed.
-If no orders array is passed it sort by 'asc' by default.
+Uses `Array.prototype.sort()`, `Array.prototype.reduce()` on the `props` array with a default value of `0`, use array destructuring to swap the properties position depending on the order passed.
+If no `orders` array is passed it sort by `'asc'` by default.
```js
const orderBy = (arr, props, orders) =>
@@ -3976,30 +7314,81 @@ orderBy(users, ['name', 'age']); // [{name: 'barney', age: 36}, {name: 'fred', a
[⬆ Back to top](#table-of-contents)
+### pick
-### select
+Picks the key-value pairs corresponding to the given keys from an object.
-Retrieve a property that indicated by the selector from an object.
-
-If the property does not exists returns `undefined`.
+Use `Array.prototype.reduce()` to convert the filtered/picked keys back to an object with the corresponding key-value pairs if the key exists in the object.
```js
-const select = (from, selector) =>
- selector.split('.').reduce((prev, cur) => prev && prev[cur], from);
+const pick = (obj, arr) =>
+ arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
```
Examples
```js
-const obj = { selector: { to: { val: 'val to select' } } };
-select(obj, 'selector.to.val'); // 'val to select'
+pick({ a: 1, b: '2', c: 3 }, ['a', 'c']); // { 'a': 1, 'c': 3 }
```
[⬆ Back to top](#table-of-contents)
+### pickBy
+
+Creates an object composed of the properties the given function returns truthy for. The function is invoked with two arguments: (value, key).
+
+Use `Object.keys(obj)` and `Array.prototype.filter()`to remove the keys for which `fn` returns a falsey value.
+Use `Array.prototype.reduce()` to convert the filtered keys back to an object with the corresponding key-value pairs.
+
+```js
+const pickBy = (obj, fn) =>
+ Object.keys(obj)
+ .filter(k => fn(obj[k], k))
+ .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});
+```
+
+
+Examples
+
+```js
+pickBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number'); // { 'a': 1, 'c': 3 }
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### renameKeys
+
+Replaces the names of multiple object keys with the values provided.
+
+Use `Object.keys()` in combination with `Array.prototype.reduce()` and the spread operator (`...`) to get the object's keys and rename them according to `keysMap`.
+
+```js
+const renameKeys = (keysMap, obj) =>
+ Object.keys(obj).reduce(
+ (acc, key) => ({
+ ...acc,
+ ...{ [keysMap[key] || key]: obj[key] }
+ }),
+ {}
+ );
+```
+
+
+Examples
+
+```js
+const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 };
+renameKeys({ name: 'firstName', job: 'passion' }, obj); // { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 }
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### shallowClone
@@ -4023,25 +7412,26 @@ const b = shallowClone(a); // a !== b
[⬆ Back to top](#table-of-contents)
-
### size
Get size of arrays, objects or strings.
-Get type of `value` (`array`, `object` or `string`).
-Use `length` property for arrays.
-Use `length` or `size` value if available or number of keys for objects.
-Use `size` of a [`Blob` object](https://developer.mozilla.org/en-US/docs/Web/API/Blob) created from `value` for strings.
+Get type of `val` (`array`, `object` or `string`).
+Use `length` property for arrays.
+Use `length` or `size` value if available or number of keys for objects.
+Use `size` of a [`Blob` object](https://developer.mozilla.org/en-US/docs/Web/API/Blob) created from `val` for strings.
Split strings into array of characters with `split('')` and return its length.
```js
-const size = value =>
- Array.isArray(value)
- ? value.length
- : value && typeof value === 'object'
- ? value.size || value.length || Object.keys(value).length
- : typeof value === 'string' ? new Blob([value]).size : 0;
+const size = val =>
+ Array.isArray(val)
+ ? val.length
+ : val && typeof val === 'object'
+ ? val.size || val.length || Object.keys(val).length
+ : typeof val === 'string'
+ ? new Blob([val]).size
+ : 0;
```
@@ -4057,12 +7447,39 @@ size({ one: 1, two: 2, three: 3 }); // 3
[⬆ Back to top](#table-of-contents)
+### transform
+
+Applies a function against an accumulator and each key in the object (from left to right).
+
+Use `Object.keys(obj)` to iterate over each key in the object, `Array.prototype.reduce()` to call the apply the specified function against the given accumulator.
+
+```js
+const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc);
+```
+
+
+Examples
+
+```js
+transform(
+ { a: 1, b: 2, c: 1 },
+ (r, v, k) => {
+ (r[v] || (r[v] = [])).push(k);
+ return r;
+ },
+ {}
+); // { '1': ['a', 'c'], '2': ['b'] }
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### truthCheckCollection
Checks if the predicate (second argument) is truthy on all elements of a collection (first argument).
-Use `Array.every()` to check if each passed object has the specified property and if it returns a truthy value.
+Use `Array.prototype.every()` to check if each passed object has the specified property and if it returns a truthy value.
```js
const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]);
@@ -4079,38 +7496,38 @@ truthCheckCollection([{ user: 'Tinky-Winky', sex: 'male' }, { user: 'Dipsy', sex
[⬆ Back to top](#table-of-contents)
----
- ## 📜 String
+### unflattenObject 
-### anagrams
+Unflatten an object with the paths for keys.
-⚠️ **WARNING**: This function's execution time increases exponentially with each character. Anything more than 8 to 10 characters will cause your browser to hang as it tries to solve all the different combinations.
-
-Generates all anagrams of a string (contains duplicates).
-
-Use recursion.
-For each letter in the given string, create all the partial anagrams for the rest of its letters.
-Use `Array.map()` to combine the letter with each partial anagram, then `Array.reduce()` to combine all anagrams in one array.
-Base cases are for string `length` equal to `2` or `1`.
+Use `Object.keys(obj)` combined with `Array.prototype.reduce()` to convert flattened path node to a leaf node.
+If the value of a key contains a dot delimiter (`.`), use `Array.prototype.split('.')`, string transformations and `JSON.parse()` to create an object, then `Object.assign()` to create the leaf node.
+Otherwise, add the appropriate key-value pair to the accumulator object.
```js
-const anagrams = str => {
- if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
- return str
- .split('')
- .reduce(
- (acc, letter, i) =>
- acc.concat(anagrams(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)),
- []
- );
-};
+const unflattenObject = obj =>
+ Object.keys(obj).reduce((acc, k) => {
+ if (k.indexOf('.') !== -1) {
+ const keys = k.split('.');
+ Object.assign(
+ acc,
+ JSON.parse(
+ '{' +
+ keys.map((v, i) => (i !== keys.length - 1 ? `"${v}":{` : `"${v}":`)).join('') +
+ obj[k] +
+ '}'.repeat(keys.length)
+ )
+ );
+ } else acc[k] = obj[k];
+ return acc;
+ }, {});
```
Examples
```js
-anagrams('abc'); // ['abc','acb','bac','bca','cab','cba']
+unflattenObject({ 'a.b.c': 1, d: 1 }); // { a: { b: { c: 1 } }, d: 1 }
```
@@ -4118,9 +7535,13 @@ anagrams('abc'); // ['abc','acb','bac','bca','cab','cba']
[⬆ Back to top](#table-of-contents)
+---
+
+## 📜 String
+
### byteSize
-Returns the length of string.
+Returns the length of a string in bytes.
Convert a given string to a [`Blob` Object](https://developer.mozilla.org/en-US/docs/Web/API/Blob) and find its `size`.
@@ -4140,12 +7561,11 @@ byteSize('Hello World'); // 11
[⬆ Back to top](#table-of-contents)
-
### capitalize
Capitalizes the first letter of a string.
-Use destructuring and `toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.join('')` to make it a string again.
+Use array destructuring and `String.prototype.toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.prototype.join('')` to make it a string again.
Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase.
```js
@@ -4165,12 +7585,11 @@ capitalize('fooBar', true); // 'Foobar'
[⬆ Back to top](#table-of-contents)
-
### capitalizeEveryWord
Capitalizes the first letter of every word in a string.
-Use `replace()` to match the first character of each word and `toUpperCase()` to capitalize it.
+Use `String.prototype.replace()` to match the first character of each word and `String.prototype.toUpperCase()` to capitalize it.
```js
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
@@ -4187,35 +7606,100 @@ capitalizeEveryWord('hello world!'); // 'Hello World!'
[⬆ Back to top](#table-of-contents)
+### CSVToArray
-### countVowels
+Converts a comma-separated values (CSV) string to a 2D array.
-Retuns `number` of vowels in provided string.
-
-Use a regular expression to count the number of vowels `(A, E, I, O, U)` in a `string`.
+Use `Array.prototype.slice()` and `Array.prototype.indexOf('\n')` to remove the first row (title row) if `omitFirstRow` is `true`.
+Use `String.prototype.split('\n')` to create a string for each row, then `String.prototype.split(delimiter)` to separate the values in each row.
+Omit the second argument, `delimiter`, to use a default delimiter of `,`.
+Omit the third argument, `omitFirstRow`, to include the first row (title row) of the CSV string.
```js
-const countVowels = str => (str.match(/[aeiou]/gi) || []).length;
+const CSVToArray = (data, delimiter = ',', omitFirstRow = false) =>
+ data
+ .slice(omitFirstRow ? data.indexOf('\n') + 1 : 0)
+ .split('\n')
+ .map(v => v.split(delimiter));
```
Examples
```js
-countVowels('foobar'); // 3
-countVowels('gym'); // 0
+CSVToArray('a,b\nc,d'); // [['a','b'],['c','d']];
+CSVToArray('a;b\nc;d', ';'); // [['a','b'],['c','d']];
+CSVToArray('col1,col2\na,b\nc,d', ',', true); // [['a','b'],['c','d']];
```
[⬆ Back to top](#table-of-contents)
+### CSVToJSON 
+
+Converts a comma-separated values (CSV) string to a 2D array of objects.
+The first row of the string is used as the title row.
+
+Use `Array.prototype.slice()` and `Array.prototype.indexOf('\n')` and `String.prototype.split(delimiter)` to separate the first row (title row) into values.
+Use `String.prototype.split('\n')` to create a string for each row, then `Array.prototype.map()` and `String.prototype.split(delimiter)` to separate the values in each row.
+Use `Array.prototype.reduce()` to create an object for each row's values, with the keys parsed from the title row.
+Omit the second argument, `delimiter`, to use a default delimiter of `,`.
+
+```js
+const CSVToJSON = (data, delimiter = ',') => {
+ const titles = data.slice(0, data.indexOf('\n')).split(delimiter);
+ return data
+ .slice(data.indexOf('\n') + 1)
+ .split('\n')
+ .map(v => {
+ const values = v.split(delimiter);
+ return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {});
+ });
+};
+```
+
+
+Examples
+
+```js
+CSVToJSON('col1,col2\na,b\nc,d'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];
+CSVToJSON('col1;col2\na;b\nc;d', ';'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### decapitalize
+
+Decapitalizes the first letter of a string.
+
+Use array destructuring and `String.toLowerCase()` to decapitalize first letter, `...rest` to get array of characters after first letter and then `Array.prototype.join('')` to make it a string again.
+Omit the `upperRest` parameter to keep the rest of the string intact, or set it to `true` to convert to uppercase.
+
+```js
+const decapitalize = ([first, ...rest], upperRest = false) =>
+ first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join(''));
+```
+
+
+Examples
+
+```js
+decapitalize('FooBar'); // 'fooBar'
+decapitalize('FooBar', true); // 'fOOBAR'
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### escapeHTML
Escapes a string for use in HTML.
-Use `String.replace()` with a regex that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object).
+Use `String.prototype.replace()` with a regexp that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object).
```js
const escapeHTML = str =>
@@ -4243,12 +7727,11 @@ escapeHTML('Me & you'); // '<a href="#">Me &
[⬆ Back to top](#table-of-contents)
-
### escapeRegExp
Escapes a string to use in a regular expression.
-Use `replace()` to escape special characters.
+Use `String.prototype.replace()` to escape special characters.
```js
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
@@ -4265,13 +7748,12 @@ escapeRegExp('(test)'); // \\(test\\)
[⬆ Back to top](#table-of-contents)
-
### fromCamelCase
Converts a string from camelcase.
-Use `replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
-Omit the second argument to use a default separator of `_`.
+Use `String.prototype.replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
+Omit the second argument to use a default `separator` of `_`.
```js
const fromCamelCase = (str, separator = '_') =>
@@ -4294,6 +7776,28 @@ fromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property'
[⬆ Back to top](#table-of-contents)
+### indentString
+
+Indents each line in the provided string.
+
+Use `String.replace` and a regular expression to add the character specified by `indent` `count` times at the start of each line.
+Omit the third parameter, `indent`, to use a default indentation character of `' '`.
+
+```js
+const indentString = (str, count, indent = ' ') => str.replace(/^/gm, indent.repeat(count));
+```
+
+
+Examples
+
+```js
+indentString('Lorem\nIpsum', 2); // ' Lorem\n Ipsum'
+indentString('Lorem\nIpsum', 2, '_'); // '__Lorem\n__Ipsum'
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### isAbsoluteURL
@@ -4318,19 +7822,120 @@ isAbsoluteURL('/foo/bar'); // false
[⬆ Back to top](#table-of-contents)
+### isAnagram
+
+Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).
+
+Use `String.toLowerCase()`, `String.prototype.replace()` with an appropriate regular expression to remove unnecessary characters, `String.prototype.split('')`, `Array.prototype.sort()` and `Array.prototype.join('')` on both strings to normalize them, then check if their normalized forms are equal.
+
+```js
+const isAnagram = (str1, str2) => {
+ const normalize = str =>
+ str
+ .toLowerCase()
+ .replace(/[^a-z0-9]/gi, '')
+ .split('')
+ .sort()
+ .join('');
+ return normalize(str1) === normalize(str2);
+};
+```
+
+
+Examples
+
+```js
+isAnagram('iceman', 'cinema'); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isLowerCase
+
+Checks if a string is lower case.
+
+Convert the given string to lower case, using `String.toLowerCase()` and compare it to the original.
+
+```js
+const isLowerCase = str => str === str.toLowerCase();
+```
+
+
+Examples
+
+```js
+isLowerCase('abc'); // true
+isLowerCase('a3@$'); // true
+isLowerCase('Ab4'); // false
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isUpperCase
+
+Checks if a string is upper case.
+
+Convert the given string to upper case, using `String.prototype.toUpperCase()` and compare it to the original.
+
+
+```js
+const isUpperCase = str => str === str.toUpperCase();
+```
+
+
+Examples
+
+```js
+isUpperCase('ABC'); // true
+isLowerCase('A3@$'); // true
+isLowerCase('aB4'); // false
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### mapString
+
+Creates a new string with the results of calling a provided function on every character in the calling string.
+
+Use `String.prototype.split('')` and `Array.prototype.map()` to call the provided function, `fn`, for each character in `str`.
+Use `Array.prototype.join('')` to recombine the array of characters into a string.
+The callback function, `fn`, takes three arguments (the current character, the index of the current character and the string `mapString` was called upon).
+
+```js
+const mapString = (str, fn) =>
+ str
+ .split('')
+ .map((c, i) => fn(c, i, str))
+ .join('');
+```
+
+
+Examples
+
+```js
+mapString('lorem ipsum', c => c.toUpperCase()); // 'LOREM IPSUM'
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### mask
Replaces all but the last `num` of characters with the specified mask character.
-Use `String.slice()` to grab the portion of the characters that need to be masked and use `String.replace()` with a regex to replace every character with the mask character.
-Concatenate the masked characters with the remaining unmasked portion of the string.
+Use `String.prototype.slice()` to grab the portion of the characters that will remain unmasked and use `String.padStart()` to fill the beginning of the string with the mask character up to the original length.
Omit the second argument, `num`, to keep a default of `4` characters unmasked. If `num` is negative, the unmasked characters will be at the start of the string.
Omit the third argument, `mask`, to use a default character of `'*'` for the mask.
```js
-const mask = (cc, num = 4, mask = '*') =>
- ('' + cc).slice(0, -num).replace(/./g, mask) + ('' + cc).slice(-num);
+const mask = (cc, num = 4, mask = '*') => `${cc}`.slice(-num).padStart(`${cc}`.length, mask);
```
@@ -4339,31 +7944,49 @@ const mask = (cc, num = 4, mask = '*') =>
```js
mask(1234567890); // '******7890'
mask(1234567890, 3); // '*******890'
-mask(1234567890, -4, '$'); // '1234$$$$$$'
+mask(1234567890, -4, '$'); // '$$$$567890'
```
[⬆ Back to top](#table-of-contents)
+### pad
+
+Pads a string on both sides with the specified character, if it's shorter than the specified length.
+
+Use `String.padStart()` and `String.padEnd()` to pad both sides of the given string.
+Omit the third argument, `char`, to use the whitespace character as the default padding character.
+
+```js
+const pad = (str, length, char = ' ') =>
+ str.padStart((str.length + length) / 2, char).padEnd(length, char);
+```
+
+
+Examples
+
+```js
+pad('cat', 8); // ' cat '
+pad(String(42), 6, '0'); // '004200'
+pad('foobar', 3); // 'foobar'
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### palindrome
Returns `true` if the given string is a palindrome, `false` otherwise.
-Convert string `toLowerCase()` and use `replace()` to remove non-alphanumeric characters from it.
-Then, `split('')` into individual characters, `reverse()`, `join('')` and compare to the original, unreversed string, after converting it `tolowerCase()`.
+Convert string `String.toLowerCase()` and use `String.prototype.replace()` to remove non-alphanumeric characters from it.
+Then, use the spread operator (`...`) to split string into individual characters, `Array.prototype.reverse()`, `String.prototype.join('')` and compare to the original, unreversed string, after converting it `String.tolowerCase()`.
```js
const palindrome = str => {
const s = str.toLowerCase().replace(/[\W_]/g, '');
- return (
- s ===
- s
- .split('')
- .reverse()
- .join('')
- );
+ return s === [...s].reverse().join('');
};
```
@@ -4378,7 +8001,6 @@ palindrome('taco cat'); // true
[⬆ Back to top](#table-of-contents)
-
### pluralize
Returns the singular or plural form of the word based on the input number. If the first argument is an `object`, it will use a closure by returning a function that can auto-pluralize words that don't simply end in `s` if the supplied dictionary contains the word.
@@ -4415,45 +8037,36 @@ autoPluralize(2, 'person'); // 'people'
[⬆ Back to top](#table-of-contents)
+### removeNonASCII
-### repeatString
+Removes non-printable ASCII characters.
-Repeats a string n times using `String.repeat()`
-
-If no string is provided the default is `""` and the default number of times is 2.
+Use a regular expression to remove non-printable ASCII characters.
```js
-const repeatString = (str = '', num = 2) => {
- return num >= 0 ? str.repeat(num) : str;
-};
+const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, '');
```
Examples
```js
-repeatString('abc', 3); // 'abcabcabc'
-repeatString('abc'); // 'abcabc'
+removeNonASCII('äÄçÇéÉêlorem-ipsumöÖÐþúÚ'); // 'lorem-ipsum'
```
[⬆ Back to top](#table-of-contents)
-
### reverseString
Reverses a string.
-Use `split('')` and `Array.reverse()` to reverse the order of the characters in the string.
-Combine characters to get a string using `join('')`.
+Use the spread operator (`...`) and `Array.prototype.reverse()` to reverse the order of the characters in the string.
+Combine characters to get a string using `String.prototype.join('')`.
```js
-const reverseString = str =>
- str
- .split('')
- .reverse()
- .join('');
+const reverseString = str => [...str].reverse().join('');
```
@@ -4467,19 +8080,14 @@ reverseString('foobar'); // 'raboof'
[⬆ Back to top](#table-of-contents)
-
### sortCharactersInString
Alphabetically sorts the characters in a string.
-Split the string using `split('')`, `Array.sort()` utilizing `localeCompare()`, recombine using `join('')`.
+Use the spread operator (`...`), `Array.prototype.sort()` and `String.localeCompare()` to sort the characters in `str`, recombine using `String.prototype.join('')`.
```js
-const sortCharactersInString = str =>
- str
- .split('')
- .sort((a, b) => a.localeCompare(b))
- .join('');
+const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join('');
```
@@ -4493,12 +8101,11 @@ sortCharactersInString('cabbage'); // 'aabbceg'
[⬆ Back to top](#table-of-contents)
-
### splitLines
Splits a multiline string into an array of lines.
-Use `String.split()` and a regular expression to match line breaks and create an array.
+Use `String.prototype.split()` and a regular expression to match line breaks and create an array.
```js
const splitLines = str => str.split(/\r?\n/);
@@ -4508,20 +8115,74 @@ const splitLines = str => str.split(/\r?\n/);
Examples
```js
-splitLines('This\nis a\nmultiline\nstring.\n'); // ['This', 'is a', 'multiline', 'string' , '']
+splitLines('This\nis a\nmultiline\nstring.\n'); // ['This', 'is a', 'multiline', 'string.' , '']
```
[⬆ Back to top](#table-of-contents)
+### stringPermutations 
+
+⚠️ **WARNING**: This function's execution time increases exponentially with each character. Anything more than 8 to 10 characters will cause your browser to hang as it tries to solve all the different combinations.
+
+Generates all permutations of a string (contains duplicates).
+
+Use recursion.
+For each letter in the given string, create all the partial permutations for the rest of its letters.
+Use `Array.prototype.map()` to combine the letter with each partial permutation, then `Array.prototype.reduce()` to combine all permutations in one array.
+Base cases are for string `length` equal to `2` or `1`.
+
+```js
+const stringPermutations = str => {
+ if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
+ return str
+ .split('')
+ .reduce(
+ (acc, letter, i) =>
+ acc.concat(stringPermutations(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)),
+ []
+ );
+};
+```
+
+
+Examples
+
+```js
+stringPermutations('abc'); // ['abc','acb','bac','bca','cab','cba']
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### stripHTMLTags
+
+Removes HTML/XML tags from string.
+
+Use a regular expression to remove HTML/XML tags from a string.
+
+```js
+const stripHTMLTags = str => str.replace(/<[^>]*>/g, '');
+```
+
+
+Examples
+
+```js
+stripHTMLTags('
loremipsum
'); // 'lorem ipsum'
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### toCamelCase
Converts a string to camelcase.
-Break the string into words and combine them capitalizing the first letter of each word.
-For more detailed explanation of this Regex, [visit this Site](https://regex101.com/r/bMCgAB/1).
+Break the string into words and combine them capitalizing the first letter of each word, using a regexp.
```js
const toCamelCase = str => {
@@ -4549,13 +8210,11 @@ toCamelCase('some-mixed_string with spaces_underscores-and-hyphens'); // 'someMi
[⬆ Back to top](#table-of-contents)
-
### toKebabCase
Converts a string to kebab case.
-Break the string into words and combine them using `-` as a separator.
-For more detailed explanation of this Regex, [visit this Site](https://regex101.com/r/bMCgAB/1).
+Break the string into words and combine them adding `-` as a separator, using a regexp.
```js
const toKebabCase = str =>
@@ -4581,13 +8240,11 @@ toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSo
[⬆ Back to top](#table-of-contents)
-
### toSnakeCase
Converts a string to snake case.
-Break the string into words and combine them using `_` as a separator.
-For more detailed explanation of this Regex, [visit this Site](https://regex101.com/r/bMCgAB/1).
+Break the string into words and combine them adding `_` as a separator, using a regexp.
```js
const toSnakeCase = str =>
@@ -4613,13 +8270,12 @@ toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSo
[⬆ Back to top](#table-of-contents)
-
### truncateString
Truncates a string up to a specified length.
Determine if the string's `length` is greater than `num`.
-Return the string truncated to the desired length, with `...` appended to the end or the original string.
+Return the string truncated to the desired length, with `'...'` appended to the end or the original string.
```js
const truncateString = (str, num) =>
@@ -4637,12 +8293,11 @@ truncateString('boomerang', 7); // 'boom...'
[⬆ Back to top](#table-of-contents)
-
### unescapeHTML
Unescapes escaped HTML characters.
-Use `String.replace()` with a regex that matches the characters that need to be unescaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object).
+Use `String.prototype.replace()` with a regex that matches the characters that need to be unescaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object).
```js
const unescapeHTML = str =>
@@ -4670,13 +8325,41 @@ unescapeHTML('<a href="#">Me & you</a>'); // '[⬆ Back to top](#table-of-contents)
+### URLJoin 
+
+Joins all given URL segments together, then normalizes the resulting URL.
+
+Use `String.prototype.join('/')` to combine URL segments, then a series of `String.prototype.replace()` calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with `'&'` and normalize first parameter delimiter).
+
+```js
+const URLJoin = (...args) =>
+ args
+ .join('/')
+ .replace(/[\/]+/g, '/')
+ .replace(/^(.+):\//, '$1://')
+ .replace(/^file:/, 'file:/')
+ .replace(/\/(\?|&|#[^!])/g, '$1')
+ .replace(/\?/g, '&')
+ .replace('&', '?');
+```
+
+
+Examples
+
+```js
+URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo'); // 'http://www.google.com/a/b/cd?foo=123&bar=foo'
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### words
Converts a given string into an array of words.
-Use `String.split()` with a supplied pattern (defaults to non-alpha as a regex) to convert to an array of strings. Use `Array.filter()` to remove any empty strings.
-Omit the second argument to use the default regex.
+Use `String.prototype.split()` with a supplied pattern (defaults to non-alpha as a regexp) to convert to an array of strings. Use `Array.prototype.filter()` to remove any empty strings.
+Omit the second argument to use the default regexp.
```js
const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
@@ -4694,8 +8377,478 @@ words('python, javaScript & coffee'); // ["python", "javaScript", "coffee"]
[⬆ Back to top](#table-of-contents)
+
---
- ## 🔧 Utility
+
+## 📃 Type
+
+### getType
+
+Returns the native type of a value.
+
+Returns lowercased constructor name of value, `"undefined"` or `"null"` if value is `undefined` or `null`.
+
+```js
+const getType = v =>
+ v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
+```
+
+
+Examples
+
+```js
+getType(new Set([1, 2, 3])); // 'set'
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### is
+
+Checks if the provided value is of the specified type.
+
+Ensure the value is not `undefined` or `null` using `Array.prototype.includes()`, and compare the `constructor` property on the value with `type` to check if the provided value is of the specified `type`.
+
+```js
+const is = (type, val) => ![, null].includes(val) && val.constructor === type;
+```
+
+
+Examples
+
+```js
+is(Array, [1]); // true
+is(ArrayBuffer, new ArrayBuffer()); // true
+is(Map, new Map()); // true
+is(RegExp, /./g); // true
+is(Set, new Set()); // true
+is(WeakMap, new WeakMap()); // true
+is(WeakSet, new WeakSet()); // true
+is(String, ''); // true
+is(String, new String('')); // true
+is(Number, 1); // true
+is(Number, new Number(1)); // true
+is(Boolean, true); // true
+is(Boolean, new Boolean(true)); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isArrayLike
+
+Checks if the provided argument is array-like (i.e. is iterable).
+
+Check if the provided argument is not `null` and that its `Symbol.iterator` property is a function.
+
+```js
+const isArrayLike = obj => obj != null && typeof obj[Symbol.iterator] === 'function';
+```
+
+
+Examples
+
+```js
+isArrayLike(document.querySelectorAll('.className')); // true
+isArrayLike('abc'); // true
+isArrayLike(null); // false
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isBoolean
+
+Checks if the given argument is a native boolean element.
+
+Use `typeof` to check if a value is classified as a boolean primitive.
+
+```js
+const isBoolean = val => typeof val === 'boolean';
+```
+
+
+Examples
+
+```js
+isBoolean(null); // false
+isBoolean(false); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isEmpty
+
+Returns true if the a value is an empty object, collection, map or set, has no enumerable properties or is any type that is not considered a collection.
+
+Check if the provided value is `null` or if its `length` is equal to `0`.
+
+```js
+const isEmpty = val => val == null || !(Object.keys(val) || val).length;
+```
+
+
+Examples
+
+```js
+isEmpty(new Map()); // true
+isEmpty(new Set()); // true
+isEmpty([]); // true
+isEmpty({}); // true
+isEmpty(''); // true
+isEmpty([1, 2]); // false
+isEmpty({ a: 1, b: 2 }); // false
+isEmpty('text'); // false
+isEmpty(123); // true - type is not considered a collection
+isEmpty(true); // true - type is not considered a collection
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isFunction
+
+Checks if the given argument is a function.
+
+Use `typeof` to check if a value is classified as a function primitive.
+
+```js
+const isFunction = val => typeof val === 'function';
+```
+
+
+Examples
+
+```js
+isFunction('x'); // false
+isFunction(x => x); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isNil
+
+Returns `true` if the specified value is `null` or `undefined`, `false` otherwise.
+
+Use the strict equality operator to check if the value and of `val` are equal to `null` or `undefined`.
+
+```js
+const isNil = val => val === undefined || val === null;
+```
+
+
+Examples
+
+```js
+isNil(null); // true
+isNil(undefined); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isNull
+
+Returns `true` if the specified value is `null`, `false` otherwise.
+
+Use the strict equality operator to check if the value and of `val` are equal to `null`.
+
+```js
+const isNull = val => val === null;
+```
+
+
+Examples
+
+```js
+isNull(null); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isNumber
+
+Checks if the given argument is a number.
+
+Use `typeof` to check if a value is classified as a number primitive.
+
+```js
+const isNumber = val => typeof val === 'number';
+```
+
+
+Examples
+
+```js
+isNumber('1'); // false
+isNumber(1); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isObject
+
+Returns a boolean determining if the passed value is an object or not.
+
+Uses the `Object` constructor to create an object wrapper for the given value.
+If the value is `null` or `undefined`, create and return an empty object. Οtherwise, return an object of a type that corresponds to the given value.
+
+```js
+const isObject = obj => obj === Object(obj);
+```
+
+
+Examples
+
+```js
+isObject([1, 2, 3, 4]); // true
+isObject([]); // true
+isObject(['Hello!']); // true
+isObject({ a: 1 }); // true
+isObject({}); // true
+isObject(true); // false
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isObjectLike
+
+Checks if a value is object-like.
+
+Check if the provided value is not `null` and its `typeof` is equal to `'object'`.
+
+```js
+const isObjectLike = val => val !== null && typeof val === 'object';
+```
+
+
+Examples
+
+```js
+isObjectLike({}); // true
+isObjectLike([1, 2, 3]); // true
+isObjectLike(x => x); // false
+isObjectLike(null); // false
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isPlainObject
+
+Checks if the provided value is an object created by the Object constructor.
+
+Check if the provided value is truthy, use `typeof` to check if it is an object and `Object.constructor` to make sure the constructor is equal to `Object`.
+
+```js
+const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object;
+```
+
+
+Examples
+
+```js
+isPlainObject({ a: 1 }); // true
+isPlainObject(new Map()); // false
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isPrimitive
+
+Returns a boolean determining if the passed value is primitive or not.
+
+Use `Array.prototype.includes()` on an array of type strings which are not primitive,
+supplying the type using `typeof`.
+Since `typeof null` evaluates to `'object'`, it needs to be directly compared.
+
+```js
+const isPrimitive = val => !['object', 'function'].includes(typeof val) || val === null;
+```
+
+
+Examples
+
+```js
+isPrimitive(null); // true
+isPrimitive(50); // true
+isPrimitive('Hello!'); // true
+isPrimitive(false); // true
+isPrimitive(Symbol()); // true
+isPrimitive([]); // false
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isPromiseLike
+
+Returns `true` if an object looks like a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), `false` otherwise.
+
+Check if the object is not `null`, its `typeof` matches either `object` or `function` and if it has a `.then` property, which is also a `function`.
+
+```js
+const isPromiseLike = obj =>
+ obj !== null &&
+ (typeof obj === 'object' || typeof obj === 'function') &&
+ typeof obj.then === 'function';
+```
+
+
+Examples
+
+```js
+isPromiseLike({
+ then: function() {
+ return '';
+ }
+}); // true
+isPromiseLike(null); // false
+isPromiseLike({}); // false
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isString
+
+Checks if the given argument is a string. Only works for string primitives.
+
+Use `typeof` to check if a value is classified as a string primitive.
+
+```js
+const isString = val => typeof val === 'string';
+```
+
+
+Examples
+
+```js
+isString('10'); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isSymbol
+
+Checks if the given argument is a symbol.
+
+Use `typeof` to check if a value is classified as a symbol primitive.
+
+```js
+const isSymbol = val => typeof val === 'symbol';
+```
+
+
+Examples
+
+```js
+isSymbol(Symbol('x')); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isUndefined
+
+Returns `true` if the specified value is `undefined`, `false` otherwise.
+
+Use the strict equality operator to check if the value and of `val` are equal to `undefined`.
+
+```js
+const isUndefined = val => val === undefined;
+```
+
+
+Examples
+
+```js
+isUndefined(undefined); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### isValidJSON
+
+Checks if the provided argument is a valid JSON.
+
+Use `JSON.parse()` and a `try... catch` block to check if the provided argument is a valid JSON.
+
+```js
+const isValidJSON = obj => {
+ try {
+ JSON.parse(obj);
+ return true;
+ } catch (e) {
+ return false;
+ }
+};
+```
+
+
+Examples
+
+```js
+isValidJSON('{"name":"Adam","age":20}'); // true
+isValidJSON('{"name":"Adam",age:"20"}'); // false
+isValidJSON(null); // true
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+
+---
+
+## 🔧 Utility
+
+### castArray
+
+Casts the provided value as an array if it's not one.
+
+Use `Array.prototype.isArray()` to determine if `val` is an array and return it as-is or encapsulated in an array accordingly.
+
+```js
+const castArray = val => (Array.isArray(val) ? val : [val]);
+```
+
+
+Examples
+
+```js
+castArray('foo'); // ['foo']
+castArray([1]); // [1]
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### cloneRegExp
@@ -4719,12 +8872,11 @@ const regExp2 = cloneRegExp(regExp); // /lorem ipsum/gi
[⬆ Back to top](#table-of-contents)
-
### coalesce
Returns the first non-null/undefined argument.
-Use `Array.find()` to return the first non `null`/`undefined` argument.
+Use `Array.prototype.find()` to return the first non `null`/`undefined` argument.
```js
const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_));
@@ -4741,12 +8893,11 @@ coalesce(null, undefined, '', NaN, 'Waldo'); // ""
[⬆ Back to top](#table-of-contents)
-
### coalesceFactory
Returns a customized coalesce function that returns the first argument that returns `true` from the provided argument validation function.
-Use `Array.find()` to return the first argument that returns `true` from the provided argument validation function.
+Use `Array.prototype.find()` to return the first argument that returns `true` from the provided argument validation function.
```js
const coalesceFactory = valid => (...args) => args.find(valid);
@@ -4764,13 +8915,13 @@ customCoalesce(undefined, null, NaN, '', 'Waldo'); // "Waldo"
[⬆ Back to top](#table-of-contents)
-
### extendHex
Extends a 3-digit color code to a 6-digit color code.
-Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form.
-`String.slice()` is used to remove `#` from string start since it's added once.
+Use `Array.prototype.map()`, `String.prototype.split()` and `Array.prototype.join()` to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form.
+`Array.prototype.slice()` is used to remove `#` from string start since it's added once.
+
```js
const extendHex = shortHex =>
'#' +
@@ -4793,42 +8944,19 @@ extendHex('05a'); // '#0055aa'
[⬆ Back to top](#table-of-contents)
-
-### getType
-
-Returns the native type of a value.
-
-Returns lowercased constructor name of value, "undefined" or "null" if value is undefined or null
-
-```js
-const getType = v =>
- v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
-```
-
-
-Examples
-
-```js
-getType(new Set([1, 2, 3])); // 'Set'
-```
-
-
-
- [⬆ Back to top](#table-of-contents)
-
-
### getURLParameters
Returns an object containing the parameters of the current URL.
-Use `match()` with an appropriate regular expression to get all key-value pairs, `Array.reduce()` to map and combine them into a single object.
+Use `String.match()` with an appropriate regular expression to get all key-value pairs, `Array.prototype.reduce()` to map and combine them into a single object.
Pass `location.search` as the argument to apply to the current `url`.
```js
const getURLParameters = url =>
- url
- .match(/([^?=&]+)(=([^&]*))/g)
- .reduce((a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a), {});
+ (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
+ (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
+ {}
+ );
```
@@ -4836,14 +8964,14 @@ const getURLParameters = url =>
```js
getURLParameters('http://url.com/page?name=Adam&surname=Smith'); // {name: 'Adam', surname: 'Smith'}
+getURLParameters('google.com'); // {}
```
[⬆ Back to top](#table-of-contents)
-
-### hexToRGB
+### hexToRGB 
Converts a color code to a `rgb()` or `rgba()` string if alpha value is provided.
@@ -4884,43 +9012,22 @@ hexToRGB('#fff'); // 'rgb(255, 255, 255)'
[⬆ Back to top](#table-of-contents)
+### httpGet
-### isArray
+Makes a `GET` request to the passed URL.
-Checks if the given argument is an array.
-
-Use `Array.isArray()` to check if a value is classified as an array.
+Use [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) web api to make a `get` request to the given `url`.
+Handle the `onload` event, by calling the given `callback` the `responseText`.
+Handle the `onerror` event, by running the provided `err` function.
+Omit the third argument, `err`, to log errors to the console's `error` stream by default.
```js
-const isArray = val => !!val && Array.isArray(val);
-```
-
-
-Examples
-
-```js
-isArray(null); // false
-isArray([1]); // true
-```
-
-
-
- [⬆ Back to top](#table-of-contents)
-
-
-### isArrayLike
-
-Checks if the provided argument is array-like (i.e. is iterable).
-
-Use the spread operator (`...`) to check if the provided argument is iterable inside a `try... catch` block and the comma operator (`,`) to return the appropriate value.
-
-```js
-const isArrayLike = val => {
- try {
- return [...val], true;
- } catch (e) {
- return false;
- }
+const httpGet = (url, callback, err = console.error) => {
+ const request = new XMLHttpRequest();
+ request.open('GET', url, true);
+ request.onload = () => callback(request.responseText);
+ request.onerror = () => err(request);
+ request.send();
};
```
@@ -4928,226 +9035,42 @@ const isArrayLike = val => {
Examples
```js
-isArrayLike(document.querySelectorAll('.className')); // true
-isArrayLike('abc'); // true
-isArrayLike(null); // false
+httpGet(
+ 'https://jsonplaceholder.typicode.com/posts/1',
+ console.log
+); /*
+Logs: {
+ "userId": 1,
+ "id": 1,
+ "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
+ "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
+}
+*/
```
[⬆ Back to top](#table-of-contents)
+### httpPost
-### isBoolean
+Makes a `POST` request to the passed URL.
-Checks if the given argument is a native boolean element.
-
-Use `typeof` to check if a value is classified as a boolean primitive.
+Use [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) web api to make a `post` request to the given `url`.
+Set the value of an `HTTP` request header with `setRequestHeader` method.
+Handle the `onload` event, by calling the given `callback` the `responseText`.
+Handle the `onerror` event, by running the provided `err` function.
+Omit the third argument, `data`, to send no data to the provided `url`.
+Omit the fourth argument, `err`, to log errors to the console's `error` stream by default.
```js
-const isBoolean = val => typeof val === 'boolean';
-```
-
-
-Examples
-
-```js
-isBoolean(null); // false
-isBoolean(false); // true
-```
-
-
-
- [⬆ Back to top](#table-of-contents)
-
-
-### isFunction
-
-Checks if the given argument is a function.
-
-Use `typeof` to check if a value is classified as a function primitive.
-
-```js
-const isFunction = val => typeof val === 'function';
-```
-
-
-Examples
-
-```js
-isFunction(null); // false
-isFunction('x'); // false
-isFunction(x => x); // true
-```
-
-
-
- [⬆ Back to top](#table-of-contents)
-
-
-### isNull
-
-Returns `true` if the specified value is `null`, `false` otherwise.
-
-Use the strict equality operator to check if the value and of `val` are equal to `null`.
-
-```js
-const isNull = val => val === null;
-```
-
-
-Examples
-
-```js
-isNull(null); // true
-```
-
-
-
- [⬆ Back to top](#table-of-contents)
-
-
-### isNumber
-
-Checks if the given argument is a number.
-
-Use `typeof` to check if a value is classified as a number primitive.
-
-```js
-const isNumber = val => typeof val === 'number';
-```
-
-
-Examples
-
-```js
-isNumber('1'); // false
-isNumber(1); // true
-```
-
-
-
- [⬆ Back to top](#table-of-contents)
-
-
-### isPrimitive
-
-Returns a boolean determining if the supplied value is primitive or not.
-
-Use `Array.includes()` on an array of type strings which are not primitive,
-supplying the type using `typeof`.
-Since `typeof null` evaluates to `'object'`, it needs to be directly compared.
-
-```js
-const isPrimitive = val => !['object', 'function'].includes(typeof val) || val === null;
-```
-
-
-Examples
-
-```js
-isPrimitive(null); // true
-isPrimitive(50); // true
-isPrimitive('Hello!'); // true
-isPrimitive(false); // true
-isPrimitive(Symbol()); // true
-isPrimitive([]); // false
-```
-
-
-
- [⬆ Back to top](#table-of-contents)
-
-
-### isPromiseLike
-
-Returns `true` if an object looks like a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), `false` otherwise.
-
-Check if the object is not `null`, its `typeof` matches either `object` or `function` and if it has a `.then` property, which is also a `function`.
-
-```js
-const isPromiseLike = obj =>
- obj !== null &&
- (typeof obj === 'object' || typeof obj === 'function') &&
- typeof obj.then === 'function';
-```
-
-
-Examples
-
-```js
-isPromiseLike({
- then: function() {
- return '';
- }
-}); // true
-isPromiseLike(null); // false
-isPromiseLike({}); // false
-```
-
-
-
- [⬆ Back to top](#table-of-contents)
-
-
-### isString
-
-Checks if the given argument is a string.
-
-Use `typeof` to check if a value is classified as a string primitive.
-
-```js
-const isString = val => typeof val === 'string';
-```
-
-
-Examples
-
-```js
-isString('10'); // true
-```
-
-
-
- [⬆ Back to top](#table-of-contents)
-
-
-### isSymbol
-
-Checks if the given argument is a symbol.
-
-Use `typeof` to check if a value is classified as a symbol primitive.
-
-```js
-const isSymbol = val => typeof val === 'symbol';
-```
-
-
-Examples
-
-```js
-isSymbol(Symbol('x')); // true
-```
-
-
-
- [⬆ Back to top](#table-of-contents)
-
-
-### isValidJSON
-
-Checks if the provided argument is a valid JSON.
-
-Use `JSON.parse()` and a `try... catch` block to check if the provided argument is a valid JSON.
-
-```js
-const isValidJSON = obj => {
- try {
- JSON.parse(obj);
- return true;
- } catch (e) {
- return false;
- }
+const httpPost = (url, data, callback, err = console.error) => {
+ const request = new XMLHttpRequest();
+ request.open('POST', url, true);
+ request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
+ request.onload = () => callback(request.responseText);
+ request.onerror = () => err(request);
+ request.send(data);
};
```
@@ -5155,17 +9078,159 @@ const isValidJSON = obj => {
Examples
```js
-isValidJSON('{"name":"Adam","age":20}'); // true
-isValidJSON('{"name":"Adam",age:"20"}'); // false
-isValidJSON(null); // true
+const newPost = {
+ userId: 1,
+ id: 1337,
+ title: 'Foo',
+ body: 'bar bar bar'
+};
+const data = JSON.stringify(newPost);
+httpPost(
+ 'https://jsonplaceholder.typicode.com/posts',
+ data,
+ console.log
+); /*
+Logs: {
+ "userId": 1,
+ "id": 1337,
+ "title": "Foo",
+ "body": "bar bar bar"
+}
+*/
+httpPost(
+ 'https://jsonplaceholder.typicode.com/posts',
+ null, //does not send a body
+ console.log
+); /*
+Logs: {
+ "id": 101
+}
+*/
```
[⬆ Back to top](#table-of-contents)
+### isBrowser
-### prettyBytes
+Determines if the current runtime environment is a browser so that front-end modules can run on the server (Node) without throwing errors.
+
+Use `Array.prototype.includes()` on the `typeof` values of both `window` and `document` (globals usually only available in a browser environment unless they were explicitly defined), which will return `true` if one of them is `undefined`.
+`typeof` allows globals to be checked for existence without throwing a `ReferenceError`.
+If both of them are not `undefined`, then the current environment is assumed to be a browser.
+
+```js
+const isBrowser = () => ![typeof window, typeof document].includes('undefined');
+```
+
+
+Examples
+
+```js
+isBrowser(); // true (browser)
+isBrowser(); // false (Node)
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### mostPerformant
+
+Returns the index of the function in an array of functions which executed the fastest.
+
+Use `Array.prototype.map()` to generate an array where each value is the total time taken to execute the function after `iterations` times. Use the difference in `performance.now()` values before and after to get the total time in milliseconds to a high degree of accuracy.
+Use `Math.min()` to find the minimum execution time, and return the index of that shortest time which corresponds to the index of the most performant function.
+Omit the second argument, `iterations`, to use a default of 10,000 iterations. The more iterations, the more reliable the result but the longer it will take.
+
+```js
+const mostPerformant = (fns, iterations = 10000) => {
+ const times = fns.map(fn => {
+ const before = performance.now();
+ for (let i = 0; i < iterations; i++) fn();
+ return performance.now() - before;
+ });
+ return times.indexOf(Math.min(...times));
+};
+```
+
+
+Examples
+
+```js
+mostPerformant([
+ () => {
+ // Loops through the entire array before returning `false`
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, '10'].every(el => typeof el === 'number');
+ },
+ () => {
+ // Only needs to reach index `1` before returning false
+ [1, '2', 3, 4, 5, 6, 7, 8, 9, 10].every(el => typeof el === 'number');
+ }
+]); // 1
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### nthArg
+
+Creates a function that gets the argument at index `n`. If `n` is negative, the nth argument from the end is returned.
+
+Use `Array.prototype.slice()` to get the desired argument at index `n`.
+
+```js
+const nthArg = n => (...args) => args.slice(n)[0];
+```
+
+
+Examples
+
+```js
+const third = nthArg(2);
+third(1, 2, 3); // 3
+third(1, 2); // undefined
+const last = nthArg(-1);
+last(1, 2, 3, 4, 5); // 5
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### parseCookie
+
+Parse an HTTP Cookie header string and return an object of all cookie name-value pairs.
+
+Use `String.prototype.split(';')` to separate key-value pairs from each other.
+Use `Array.prototype.map()` and `String.prototype.split('=')` to separate keys from values in each pair.
+Use `Array.prototype.reduce()` and `decodeURIComponent()` to create an object with all key-value pairs.
+
+```js
+const parseCookie = str =>
+ str
+ .split(';')
+ .map(v => v.split('='))
+ .reduce((acc, v) => {
+ acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());
+ return acc;
+ }, {});
+```
+
+
+Examples
+
+```js
+parseCookie('foo=bar; equation=E%3Dmc%5E2'); // { foo: 'bar', equation: 'E=mc^2' }
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
+
+### prettyBytes 
Converts a number in bytes to a human-readable string.
@@ -5189,16 +9254,15 @@ const prettyBytes = (num, precision = 3, addSpace = true) => {
Examples
```js
-prettyBytes(1000); // 1 KB
-prettyBytes(-27145424323.5821, 5); // -27.145 GB
-prettyBytes(123456789, 3, false); // 123MB
+prettyBytes(1000); // "1 KB"
+prettyBytes(-27145424323.5821, 5); // "-27.145 GB"
+prettyBytes(123456789, 3, false); // "123MB"
```
[⬆ Back to top](#table-of-contents)
-
### randomHexColorCode
Generates a random hexadecimal color code.
@@ -5207,8 +9271,8 @@ Use `Math.random` to generate a random 24-bit(6x4bits) hexadecimal number. Use b
```js
const randomHexColorCode = () => {
- let n = ((Math.random() * 0xfffff) | 0).toString(16);
- return '#' + (n.length !== 6 ? ((Math.random() * 0xf) | 0).toString(16) + n : n);
+ let n = (Math.random() * 0xfffff * 1000000).toString(16);
+ return '#' + n.slice(0, 6);
};
```
@@ -5223,12 +9287,11 @@ randomHexColorCode(); // "#e34155"
[⬆ Back to top](#table-of-contents)
-
### RGBToHex
Converts the values of RGB components to a color code.
-Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `toString(16)`, then `padStart(6,'0')` to get a 6-digit hexadecimal value.
+Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `toString(16)`, then `String.padStart(6,'0')` to get a 6-digit hexadecimal value.
```js
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
@@ -5245,36 +9308,27 @@ RGBToHex(255, 165, 1); // 'ffa501'
[⬆ Back to top](#table-of-contents)
+### serializeCookie
-### sbdm
+Serialize a cookie name-value pair into a Set-Cookie header string.
-This algorithm is a simple hash-algorithm that hashes it input string `s` into a whole number.
-
-Use `split('')` and `Array.reduce()` to create a hash of the input string, utilizing bit shifting.
+Use template literals and `encodeURIComponent()` to create the appropriate string.
```js
-const sdbm = str => {
- let arr = str.split('');
- return arr.reduce(
- (hashCode, currentVal) =>
- (hashCode = currentVal.charCodeAt(0) + (hashCode << 6) + (hashCode << 16) - hashCode),
- 0
- );
-};
+const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`;
```
Examples
```js
-console.log(sdbm('name')); // -3521204949
+serializeCookie('foo', 'bar'); // 'foo=bar'
```
[⬆ Back to top](#table-of-contents)
-
### timeTaken
Measures the time taken by a function to execute.
@@ -5301,6 +9355,31 @@ timeTaken(() => Math.pow(2, 10)); // 1024, (logged): timeTaken: 0.02099609375ms
[⬆ Back to top](#table-of-contents)
+### toCurrency
+
+Take a number and return specified currency formatting.
+
+Use `Intl.NumberFormat` to enable country / currency sensitive formatting.
+
+```js
+const toCurrency = (n, curr, LanguageFormat = undefined) =>
+ Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n);
+```
+
+
+Examples
+
+```js
+toCurrency(123456.789, 'EUR'); // €123,456.79 | currency: Euro | currencyLangFormat: Local
+toCurrency(123456.789, 'USD', 'en-us'); // $123,456.79 | currency: US Dollar | currencyLangFormat: English (United States)
+toCurrency(123456.789, 'USD', 'fa'); // ۱۲۳٬۴۵۶٫۷۹ $ | currency: US Dollar | currencyLangFormat: Farsi
+toCurrency(322342436423.2435, 'JPY'); // ¥322,342,436,423 | currency: Japanese Yen | currencyLangFormat: Local
+toCurrency(322342436423.2435, 'JPY', 'fi'); // 322 342 436 423 ¥ | currency: Japanese Yen | currencyLangFormat: Finnish
+```
+
+
+
+ [⬆ Back to top](#table-of-contents)
### toDecimalMark
@@ -5314,14 +9393,13 @@ const toDecimalMark = num => num.toLocaleString('en-US');
Examples
```js
-toDecimalMark(12305030388.9087); // "12,305,030,388.9087"
+toDecimalMark(12305030388.9087); // "12,305,030,388.909"
```
[⬆ Back to top](#table-of-contents)
-
### toOrdinalSuffix
Adds an ordinal suffix to a number.
@@ -5354,12 +9432,11 @@ toOrdinalSuffix('123'); // "123rd"
[⬆ Back to top](#table-of-contents)
-
### validateNumber
Returns `true` if the given value is a number, `false` otherwise.
-Use `!isNaN` in combination with `parseFloat()` to check if the argument is a number.
+Use `!isNaN()` in combination with `parseFloat()` to check if the argument is a number.
Use `isFinite()` to check if the number is finite.
Use `Number()` to check if the coercion holds.
@@ -5378,7 +9455,6 @@ validateNumber('10'); // true
[⬆ Back to top](#table-of-contents)
-
### yesNo
Returns `true` if the string is `y`/`yes` or `false` if the string is `n`/`no`.
@@ -5408,7 +9484,7 @@ yesNo('Foo', true); // true
## Collaborators
-| [](https://github.com/Chalarangelo) [Angelos Chalaris](https://github.com/Chalarangelo) | [](https://github.com/Pl4gue) [David Wu](https://github.com/Pl4gue) | [](https://github.com/fejes713) [Stefan Feješ](https://github.com/fejes713) | [](https://github.com/kingdavidmartins) [King David Martins](https://github.com/iamsoorena) | [](https://github.com/iamsoorena) [Soorena Soleimani](https://github.com/iamsoorena) |
+| [](https://github.com/Chalarangelo) [Angelos Chalaris](https://github.com/Chalarangelo) | [](https://github.com/flxwu) [Felix Wu](https://github.com/Pl4gue) | [](https://github.com/fejes713) [Stefan Feješ](https://github.com/fejes713) | [](https://github.com/kingdavidmartins) [King David Martins](https://github.com/iamsoorena) | [](https://github.com/iamsoorena) [Soorena Soleimani](https://github.com/iamsoorena) |
| --- | --- | --- | --- | --- |
| [](https://github.com/elderhsouza) [Elder Henrique Souza](https://github.com/elderhsouza) | [](https://github.com/skatcat31) [Robert Mennell](https://github.com/skatcat31) | [](https://github.com/atomiks) [atomiks](https://github.com/atomiks) |
diff --git a/advanced.svg b/advanced.svg
new file mode 100644
index 000000000..428312a3c
--- /dev/null
+++ b/advanced.svg
@@ -0,0 +1 @@
+
diff --git a/dist/_30s.es5.js b/dist/_30s.es5.js
index 34ebd5516..2ee4a9491 100644
--- a/dist/_30s.es5.js
+++ b/dist/_30s.es5.js
@@ -4,11 +4,6 @@
(global._30s = factory());
}(this, (function () { 'use strict';
-var JSONToDate = function JSONToDate(arr) {
- var dt = new Date(parseInt(arr.toString().substr(6)));
- return dt.getDate() + "/" + (dt.getMonth() + 1) + "/" + dt.getFullYear();
-};
-
var fs = typeof require !== "undefined" && require('fs');
var JSONToFile = function JSONToFile(obj, filename) {
return fs.writeFile(filename + ".json", JSON.stringify(obj, null, 2));
@@ -18,6 +13,14 @@ var RGBToHex = function RGBToHex(r, g, b) {
return ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
};
+var URLJoin = function URLJoin() {
+ for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+
+ return args.join('/').replace(/[\/]+/g, '/').replace(/^(.+):\//, '$1://').replace(/^file:/, 'file:/').replace(/\/(\?|&|#[^!])/g, '$1').replace(/\?/g, '&').replace('&', '?');
+};
+
var UUIDGeneratorBrowser = function UUIDGeneratorBrowser() {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, function (c) {
return (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16);
@@ -31,13 +34,19 @@ var UUIDGeneratorNode = function UUIDGeneratorNode() {
});
};
-var anagrams = function anagrams(str) {
- if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
- return str.split('').reduce(function (acc, letter, i) {
- return acc.concat(anagrams(str.slice(0, i) + str.slice(i + 1)).map(function (val) {
- return letter + val;
- }));
- }, []);
+var all = function all(arr) {
+ var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Boolean;
+ return arr.every(fn);
+};
+
+var any = function any(arr) {
+ var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Boolean;
+ return arr.some(fn);
+};
+
+var approximatelyEqual = function approximatelyEqual(v1, v2) {
+ var epsilon = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0.001;
+ return Math.abs(v1 - v2) < epsilon;
};
var arrayToHtmlList = function arrayToHtmlList(arr, listID) {
@@ -46,19 +55,116 @@ var arrayToHtmlList = function arrayToHtmlList(arr, listID) {
});
};
-var average = function average() {
- var _ref;
+function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
- var nums = (_ref = []).concat.apply(_ref, arguments);
- return nums.reduce(function (acc, val) {
+var ary = function ary(fn, n) {
+ return function () {
+ for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+
+ return fn.apply(undefined, _toConsumableArray(args.slice(0, n)));
+ };
+};
+
+var atob = function atob(str) {
+ return new Buffer(str, 'base64').toString('binary');
+};
+
+var attempt = function attempt(fn) {
+ for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ args[_key - 1] = arguments[_key];
+ }
+
+ try {
+ return fn(args);
+ } catch (e) {
+ return e instanceof Error ? e : new Error(e);
+ }
+};
+
+var average = function average() {
+ for (var _len = arguments.length, nums = Array(_len), _key = 0; _key < _len; _key++) {
+ nums[_key] = arguments[_key];
+ }
+
+ return [].concat(nums).reduce(function (acc, val) {
return acc + val;
}, 0) / nums.length;
};
+var averageBy = function averageBy(arr, fn) {
+ return arr.map(typeof fn === 'function' ? fn : function (val) {
+ return val[fn];
+ }).reduce(function (acc, val) {
+ return acc + val;
+ }, 0) / arr.length;
+};
+
+var bifurcate = function bifurcate(arr, filter) {
+ return arr.reduce(function (acc, val, i) {
+ return acc[filter[i] ? 0 : 1].push(val), acc;
+ }, [[], []]);
+};
+
+var bifurcateBy = function bifurcateBy(arr, fn) {
+ return arr.reduce(function (acc, val, i) {
+ return acc[fn(val, i) ? 0 : 1].push(val), acc;
+ }, [[], []]);
+};
+
+var bind = function bind(fn, context) {
+ for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
+ args[_key - 2] = arguments[_key];
+ }
+
+ return function () {
+ return fn.apply(context, args.concat.apply(args, arguments));
+ };
+};
+
+var bindAll = function bindAll(obj) {
+ for (var _len = arguments.length, fns = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ fns[_key - 1] = arguments[_key];
+ }
+
+ return fns.forEach(function (fn) {
+ return f = obj[fn], obj[fn] = function () {
+ return f.apply(obj);
+ };
+ });
+};
+
+var bindKey = function bindKey(context, fn) {
+ for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
+ args[_key - 2] = arguments[_key];
+ }
+
+ return function () {
+ return context[fn].apply(context, args.concat.apply(args, arguments));
+ };
+};
+
+var binomialCoefficient = function binomialCoefficient(n, k) {
+ if (Number.isNaN(n) || Number.isNaN(k)) return NaN;
+ if (k < 0 || k > n) return 0;
+ if (k === 0 || k === n) return 1;
+ if (k === 1 || k === n - 1) return n;
+ if (n - k < k) k = n - k;
+ var res = n;
+ for (var j = 2; j <= k; j++) {
+ res *= (n - j + 1) / j;
+ }return Math.round(res);
+};
+
var bottomVisible = function bottomVisible() {
return document.documentElement.clientHeight + window.scrollY >= (document.documentElement.scrollHeight || document.documentElement.clientHeight);
};
+var btoa = function btoa(str) {
+ return new Buffer(str, 'binary').toString('base64');
+};
+
var byteSize = function byteSize(str) {
return new Blob([str]).size;
};
@@ -90,6 +196,10 @@ var capitalizeEveryWord = function capitalizeEveryWord(str) {
});
};
+var castArray = function castArray(val) {
+ return Array.isArray(val) ? val : [val];
+};
+
var chainAsync = function chainAsync(fns) {
var curr = 0;
var next = function next() {
@@ -108,20 +218,6 @@ var clampNumber = function clampNumber(num, a, b) {
return Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));
};
-var cleanObj = function cleanObj(obj) {
- var keysToKeep = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
- var childIndicator = arguments[2];
-
- Object.keys(obj).forEach(function (key) {
- if (key === childIndicator) {
- cleanObj(obj[key], keysToKeep, childIndicator);
- } else if (!keysToKeep.includes(key)) {
- delete obj[key];
- }
- });
- return obj;
-};
-
var cloneRegExp = function cloneRegExp(regExp) {
return new RegExp(regExp.source, regExp.flags);
};
@@ -146,10 +242,6 @@ var coalesceFactory = function coalesceFactory(valid) {
};
};
-var collatz = function collatz(n) {
- return n % 2 == 0 ? n / 2 : 3 * n + 1;
-};
-
var collectInto = function collectInto(fn) {
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
@@ -160,6 +252,31 @@ var collectInto = function collectInto(fn) {
};
};
+var colorize = function colorize() {
+ for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+
+ return {
+ black: '\x1B[30m' + args.join(' '),
+ red: '\x1B[31m' + args.join(' '),
+ green: '\x1B[32m' + args.join(' '),
+ yellow: '\x1B[33m' + args.join(' '),
+ blue: '\x1B[34m' + args.join(' '),
+ magenta: '\x1B[35m' + args.join(' '),
+ cyan: '\x1B[36m' + args.join(' '),
+ white: '\x1B[37m' + args.join(' '),
+ bgBlack: '\x1B[40m' + args.join(' ') + '\x1B[0m',
+ bgRed: '\x1B[41m' + args.join(' ') + '\x1B[0m',
+ bgGreen: '\x1B[42m' + args.join(' ') + '\x1B[0m',
+ bgYellow: '\x1B[43m' + args.join(' ') + '\x1B[0m',
+ bgBlue: '\x1B[44m' + args.join(' ') + '\x1B[0m',
+ bgMagenta: '\x1B[45m' + args.join(' ') + '\x1B[0m',
+ bgCyan: '\x1B[46m' + args.join(' ') + '\x1B[0m',
+ bgWhite: '\x1B[47m' + args.join(' ') + '\x1B[0m'
+ };
+};
+
var compact = function compact(arr) {
return arr.filter(Boolean);
};
@@ -176,6 +293,32 @@ var compose = function compose() {
});
};
+var composeRight = function composeRight() {
+ for (var _len = arguments.length, fns = Array(_len), _key = 0; _key < _len; _key++) {
+ fns[_key] = arguments[_key];
+ }
+
+ return fns.reduce(function (f, g) {
+ return function () {
+ return g(f.apply(undefined, arguments));
+ };
+ });
+};
+
+function _toConsumableArray$1(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var converge = function converge(converger, fns) {
+ return function () {
+ for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+
+ return converger.apply(undefined, _toConsumableArray$1(fns.map(function (fn) {
+ return fn.apply(null, args);
+ })));
+ };
+};
+
var copyToClipboard = function copyToClipboard(str) {
var el = document.createElement('textarea');
el.value = str;
@@ -193,14 +336,46 @@ var copyToClipboard = function copyToClipboard(str) {
}
};
-var countOccurrences = function countOccurrences(arr, value) {
+var countBy = function countBy(arr, fn) {
+ return arr.map(typeof fn === 'function' ? fn : function (val) {
+ return val[fn];
+ }).reduce(function (acc, val, i) {
+ acc[val] = (acc[val] || 0) + 1;
+ return acc;
+ }, {});
+};
+
+var countOccurrences = function countOccurrences(arr, val) {
return arr.reduce(function (a, v) {
- return v === value ? a + 1 : a + 0;
+ return v === val ? a + 1 : a + 0;
}, 0);
};
-var countVowels = function countVowels(str) {
- return (str.match(/[aeiou]/gi) || []).length;
+var createElement = function createElement(str) {
+ var el = document.createElement('div');
+ el.innerHTML = str;
+ return el.firstElementChild;
+};
+
+var createEventHub = function createEventHub() {
+ return {
+ hub: Object.create(null),
+ emit: function emit(event, data) {
+ (this.hub[event] || []).forEach(function (handler) {
+ return handler(data);
+ });
+ },
+ on: function on(event, handler) {
+ if (!this.hub[event]) this.hub[event] = [];
+ this.hub[event].push(handler);
+ },
+ off: function off(event, handler) {
+ var i = (this.hub[event] || []).findIndex(function (h) {
+ return h === handler;
+ });
+ if (i > -1) this.hub[event].splice(i, 1);
+ }
+ };
};
var currentURL = function currentURL() {
@@ -216,16 +391,65 @@ var curry = function curry(fn) {
return arity <= args.length ? fn.apply(undefined, args) : curry.bind.apply(curry, [null, fn, arity].concat(args));
};
-function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+var debounce = function debounce(fn) {
+ var ms = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
+
+ var timeoutId = void 0;
+ return function () {
+ var _this = this;
+
+ for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+
+ clearTimeout(timeoutId);
+ timeoutId = setTimeout(function () {
+ return fn.apply(_this, args);
+ }, ms);
+ };
+};
+
+function _toArray$1(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }
+
+var decapitalize = function decapitalize(_ref) {
+ var _ref2 = _toArray$1(_ref),
+ first = _ref2[0],
+ rest = _ref2.slice(1);
+
+ var upperRest = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
+ return first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join(''));
+};
+
+var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
+
+var deepClone = function deepClone(obj) {
+ var clone = Object.assign({}, obj);
+ Object.keys(clone).forEach(function (key) {
+ return clone[key] = _typeof(obj[key]) === 'object' ? deepClone(obj[key]) : obj[key];
+ });
+ return clone;
+};
+
+function _toConsumableArray$2(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var deepFlatten = function deepFlatten(arr) {
var _ref;
- return (_ref = []).concat.apply(_ref, _toConsumableArray(arr.map(function (v) {
+ return (_ref = []).concat.apply(_ref, _toConsumableArray$2(arr.map(function (v) {
return Array.isArray(v) ? deepFlatten(v) : v;
})));
};
+function _toConsumableArray$3(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var defaults = function defaults(obj) {
+ for (var _len = arguments.length, defs = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ defs[_key - 1] = arguments[_key];
+ }
+
+ return Object.assign.apply(Object, [{}, obj].concat(_toConsumableArray$3(defs.reverse()), [obj]));
+};
+
var defer = function defer(fn) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
@@ -234,6 +458,18 @@ var defer = function defer(fn) {
return setTimeout.apply(undefined, [fn, 1].concat(args));
};
+var degreesToRads = function degreesToRads(deg) {
+ return deg * Math.PI / 180.0;
+};
+
+var delay = function delay(fn, wait) {
+ for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
+ args[_key - 2] = arguments[_key];
+ }
+
+ return setTimeout.apply(undefined, [fn, wait].concat(args));
+};
+
var detectDeviceType = function detectDeviceType() {
return (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop'
);
@@ -246,6 +482,15 @@ var difference = function difference(a, b) {
});
};
+var differenceBy = function differenceBy(a, b, fn) {
+ var s = new Set(b.map(function (v) {
+ return fn(v);
+ }));
+ return a.filter(function (x) {
+ return !s.has(fn(x));
+ });
+};
+
var differenceWith = function differenceWith(arr, val, comp) {
return arr.filter(function (a) {
return val.findIndex(function (b) {
@@ -254,10 +499,10 @@ var differenceWith = function differenceWith(arr, val, comp) {
});
};
-function _toConsumableArray$1(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+function _toConsumableArray$4(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var digitize = function digitize(n) {
- return [].concat(_toConsumableArray$1('' + n)).map(function (i) {
+ return [].concat(_toConsumableArray$4("" + n)).map(function (i) {
return parseInt(i);
});
};
@@ -266,16 +511,9 @@ var distance = function distance(x0, y0, x1, y1) {
return Math.hypot(x1 - x0, y1 - y0);
};
-function _toConsumableArray$2(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
-
-var distinctValuesOfArray = function distinctValuesOfArray(arr) {
- return [].concat(_toConsumableArray$2(new Set(arr)));
-};
-
-var dropElements = function dropElements(arr, func) {
- while (arr.length > 0 && !func(arr[0])) {
- arr = arr.slice(1);
- }return arr;
+var drop = function drop(arr) {
+ var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
+ return arr.slice(n);
};
var dropRight = function dropRight(arr) {
@@ -283,6 +521,18 @@ var dropRight = function dropRight(arr) {
return arr.slice(0, -n);
};
+var dropRightWhile = function dropRightWhile(arr, func) {
+ while (arr.length > 0 && !func(arr[arr.length - 1])) {
+ arr = arr.slice(0, -1);
+ }return arr;
+};
+
+var dropWhile = function dropWhile(arr, func) {
+ while (arr.length > 0 && !func(arr[0])) {
+ arr = arr.slice(1);
+ }return arr;
+};
+
var elementIsVisibleInViewport = function elementIsVisibleInViewport(el) {
var partiallyVisible = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
@@ -301,10 +551,10 @@ var elementIsVisibleInViewport = function elementIsVisibleInViewport(el) {
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
-function _toArray$1(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }
+function _toArray$2(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }
var elo = function elo(_ref) {
- var _ref2 = _toArray$1(_ref),
+ var _ref2 = _toArray$2(_ref),
ratings = _ref2.slice(0);
var kFactor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 32;
@@ -340,6 +590,21 @@ var elo = function elo(_ref) {
return ratings;
};
+var _typeof$1 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
+
+var equals = function equals(a, b) {
+ if (a === b) return true;
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
+ if (!a || !b || (typeof a === 'undefined' ? 'undefined' : _typeof$1(a)) != 'object' && (typeof b === 'undefined' ? 'undefined' : _typeof$1(b)) !== 'object') return a === b;
+ if (a === null || a === undefined || b === null || b === undefined) return false;
+ if (a.prototype !== b.prototype) return false;
+ var keys = Object.keys(a);
+ if (keys.length !== Object.keys(b).length) return false;
+ return keys.every(function (k) {
+ return equals(a[k], b[k]);
+ });
+};
+
var escapeHTML = function escapeHTML(str) {
return str.replace(/[&<>'"]/g, function (tag) {
return {
@@ -374,80 +639,88 @@ var factorial = function factorial(n) {
}() : n <= 1 ? 1 : n * factorial(n - 1);
};
-var factors = function factors(num) {
- var primes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
-
- var isPrime = function isPrime(num) {
- var boundary = Math.floor(Math.sqrt(num));
- for (var i = 2; i <= boundary; i++) {
- if (num % i === 0) return false;
- }return num >= 2;
- };
- var isNeg = num < 0;
- num = isNeg ? -num : num;
- var array = Array.from({ length: num - 1 }).map(function (val, i) {
- return num % (i + 2) === 0 ? i + 2 : false;
- }).filter(function (val) {
- return val;
- });
- if (isNeg) array = array.reduce(function (acc, val) {
- acc.push(val);
- acc.push(-val);
- return acc;
- }, []);
- return primes ? array.filter(isPrime) : array;
-};
-
var fibonacci = function fibonacci(n) {
return Array.from({ length: n }).reduce(function (acc, val, i) {
return acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i);
}, []);
};
-var fibonacciCountUntilNum = function fibonacciCountUntilNum(num) {
- return Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
-};
-
-var fibonacciUntilNum = function fibonacciUntilNum(num) {
- var n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
- return Array.from({ length: n }).reduce(function (acc, val, i) {
- return acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i);
- }, []);
-};
-
var filterNonUnique = function filterNonUnique(arr) {
return arr.filter(function (i) {
return arr.indexOf(i) === arr.lastIndexOf(i);
});
};
-function _toConsumableArray$3(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
-
-var flatten = function flatten(arr) {
- var _ref;
-
- return (_ref = []).concat.apply(_ref, _toConsumableArray$3(arr));
+var findKey = function findKey(obj, fn) {
+ return Object.keys(obj).find(function (key) {
+ return fn(obj[key], key, obj);
+ });
};
-var flattenDepth = function flattenDepth(arr) {
+var findLast = function findLast(arr, fn) {
+ return arr.filter(fn).slice(-1)[0];
+};
+
+var findLastIndex = function findLastIndex(arr, fn) {
+ return arr.map(function (val, i) {
+ return [i, val];
+ }).filter(function (val) {
+ return fn(val[1], val[0], arr);
+ }).slice(-1)[0][0];
+};
+
+var findLastKey = function findLastKey(obj, fn) {
+ return Object.keys(obj).reverse().find(function (key) {
+ return fn(obj[key], key, obj);
+ });
+};
+
+var flatten = function flatten(arr) {
var depth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
- return depth != 1 ? arr.reduce(function (a, v) {
- return a.concat(Array.isArray(v) ? flattenDepth(v, depth - 1) : v);
+ return depth !== 1 ? arr.reduce(function (a, v) {
+ return a.concat(Array.isArray(v) ? flatten(v, depth - 1) : v);
}, []) : arr.reduce(function (a, v) {
return a.concat(v);
}, []);
};
+var _typeof$2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
+
+var flattenObject = function flattenObject(obj) {
+ var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
+ return Object.keys(obj).reduce(function (acc, k) {
+ var pre = prefix.length ? prefix + '.' : '';
+ if (_typeof$2(obj[k]) === 'object') Object.assign(acc, flattenObject(obj[k], pre + k));else acc[pre + k] = obj[k];
+ return acc;
+ }, {});
+};
+
var flip = function flip(fn) {
- return function () {
- for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
+ return function (first) {
+ for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ rest[_key - 1] = arguments[_key];
}
- return fn.apply(undefined, [args.pop()].concat(args));
+ return fn.apply(undefined, rest.concat([first]));
};
};
+var forEachRight = function forEachRight(arr, callback) {
+ return arr.slice(0).reverse().forEach(callback);
+};
+
+var forOwn = function forOwn(obj, fn) {
+ return Object.keys(obj).forEach(function (key) {
+ return fn(obj[key], key, obj);
+ });
+};
+
+var forOwnRight = function forOwnRight(obj, fn) {
+ return Object.keys(obj).reverse().forEach(function (key) {
+ return fn(obj[key], key, obj);
+ });
+};
+
var formatDuration = function formatDuration(ms) {
if (ms < 0) ms = -ms;
var time = {
@@ -473,13 +746,24 @@ var functionName = function functionName(fn) {
return console.debug(fn.name), fn;
};
+function _toConsumableArray$5(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var functions = function functions(obj) {
+ var inherited = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
+ return (inherited ? [].concat(_toConsumableArray$5(Object.keys(obj)), _toConsumableArray$5(Object.keys(Object.getPrototypeOf(obj)))) : Object.keys(obj)).filter(function (key) {
+ return typeof obj[key] === 'function';
+ });
+};
+
var gcd = function gcd() {
- var _ref;
+ for (var _len = arguments.length, arr = Array(_len), _key = 0; _key < _len; _key++) {
+ arr[_key] = arguments[_key];
+ }
var _gcd = function _gcd(x, y) {
return !y ? x : gcd(y, x % y);
};
- return (_ref = []).concat.apply(_ref, arguments).reduce(function (a, b) {
+ return [].concat(arr).reduce(function (a, b) {
return _gcd(a, b);
});
};
@@ -492,10 +776,32 @@ var geometricProgression = function geometricProgression(end) {
});
};
+var get = function get(from) {
+ for (var _len = arguments.length, selectors = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ selectors[_key - 1] = arguments[_key];
+ }
+
+ return [].concat(selectors).map(function (s) {
+ return s.replace(/\[([^\[\]]*)\]/g, '.$1.').split('.').filter(function (t) {
+ return t !== '';
+ }).reduce(function (prev, cur) {
+ return prev && prev[cur];
+ }, from);
+ });
+};
+
+var getColonTimeFromDate = function getColonTimeFromDate(date) {
+ return date.toTimeString().slice(0, 8);
+};
+
var getDaysDiffBetweenDates = function getDaysDiffBetweenDates(dateInitial, dateFinal) {
return (dateFinal - dateInitial) / (1000 * 3600 * 24);
};
+var getMeridiemSuffixOfInteger = function getMeridiemSuffixOfInteger(num) {
+ return num === 0 || num === 24 ? 12 + 'am' : num === 12 ? 12 + 'pm' : num < 12 ? num % 12 + 'am' : num % 12 + 'pm';
+};
+
var getScrollPosition = function getScrollPosition() {
var el = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window;
return {
@@ -513,14 +819,14 @@ var getType = function getType(v) {
};
var getURLParameters = function getURLParameters(url) {
- return url.match(/([^?=&]+)(=([^&]*))/g).reduce(function (a, v) {
+ return (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(function (a, v) {
return a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1), a;
}, {});
};
-var groupBy = function groupBy(arr, func) {
- return arr.map(typeof func === 'function' ? func : function (val) {
- return val[func];
+var groupBy = function groupBy(arr, fn) {
+ return arr.map(typeof fn === 'function' ? fn : function (val) {
+ return val[fn];
}).reduce(function (acc, val, i) {
acc[val] = (acc[val] || []).concat(arr[i]);
return acc;
@@ -545,16 +851,35 @@ var hasFlags = function hasFlags() {
});
};
+var hashBrowser = function hashBrowser(val) {
+ return crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(val)).then(function (h) {
+ var hexes = [],
+ view = new DataView(h);
+ for (var i = 0; i < view.byteLength; i += 4) {
+ hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8));
+ }return hexes.join('');
+ });
+};
+
+var crypto$2 = typeof require !== "undefined" && require('crypto');
+var hashNode = function hashNode(val) {
+ return new Promise(function (resolve) {
+ return setTimeout(function () {
+ return resolve(crypto$2.createHash('sha256').update(val).digest('hex'));
+ }, 0);
+ });
+};
+
var head = function head(arr) {
return arr[0];
};
-function _toConsumableArray$4(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+function _toConsumableArray$6(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var hexToRGB = function hexToRGB(hex) {
var alpha = false,
h = hex.slice(hex.startsWith('#') ? 1 : 0);
- if (h.length === 3) h = [].concat(_toConsumableArray$4(h)).map(function (x) {
+ if (h.length === 3) h = [].concat(_toConsumableArray$6(h)).map(function (x) {
return x + x;
}).join('');else if (h.length === 8) alpha = true;
h = parseInt(h, 16);
@@ -571,15 +896,33 @@ var hide = function hide() {
});
};
-var howManyTimes = function howManyTimes(num, divisor) {
- if (divisor === 1 || divisor === -1) return Infinity;
- if (divisor === 0) return 0;
- var i = 0;
- while (Number.isInteger(num / divisor)) {
- i++;
- num = num / divisor;
- }
- return i;
+var httpGet = function httpGet(url, callback) {
+ var err = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : console.error;
+
+ var request = new XMLHttpRequest();
+ request.open('GET', url, true);
+ request.onload = function () {
+ return callback(request.responseText);
+ };
+ request.onerror = function () {
+ return err(request);
+ };
+ request.send();
+};
+
+var httpPost = function httpPost(url, data, callback) {
+ var err = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : console.error;
+
+ var request = new XMLHttpRequest();
+ request.open('POST', url, true);
+ request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
+ request.onload = function () {
+ return callback(request.responseText);
+ };
+ request.onerror = function () {
+ return err(request);
+ };
+ request.send(data);
};
var httpsRedirect = function httpsRedirect() {
@@ -593,14 +936,22 @@ var inRange = function inRange(n, start) {
return end == null ? n >= 0 && n < start : n >= start && n < end;
};
+var indexOfAll = function indexOfAll(arr, val) {
+ var indices = [];
+ arr.forEach(function (el, i) {
+ return el === val && indices.push(i);
+ });
+ return indices;
+};
+
var initial = function initial(arr) {
return arr.slice(0, -1);
};
var initialize2DArray = function initialize2DArray(w, h) {
var val = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
- return Array(h).fill().map(function () {
- return Array(w).fill(val);
+ return Array.from({ length: h }).map(function () {
+ return Array.from({ length: w }).fill(val);
});
};
@@ -612,9 +963,17 @@ var initializeArrayWithRange = function initializeArrayWithRange(end) {
});
};
+var initializeArrayWithRangeRight = function initializeArrayWithRangeRight(end) {
+ var start = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
+ var step = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
+ return Array.from({ length: Math.ceil((end + 1 - start) / step) }).map(function (v, i, arr) {
+ return (arr.length - i - 1) * step + start;
+ });
+};
+
var initializeArrayWithValues = function initializeArrayWithValues(n) {
- var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
- return Array(n).fill(value);
+ var val = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
+ return Array(n).fill(val);
};
var intersection = function intersection(a, b) {
@@ -624,35 +983,53 @@ var intersection = function intersection(a, b) {
});
};
-var invertKeyValues = function invertKeyValues(obj) {
+var intersectionBy = function intersectionBy(a, b, fn) {
+ var s = new Set(b.map(function (x) {
+ return fn(x);
+ }));
+ return a.filter(function (x) {
+ return s.has(fn(x));
+ });
+};
+
+var intersectionWith = function intersectionWith(a, b, comp) {
+ return a.filter(function (x) {
+ return b.findIndex(function (y) {
+ return comp(x, y);
+ }) !== -1;
+ });
+};
+
+var invertKeyValues = function invertKeyValues(obj, fn) {
return Object.keys(obj).reduce(function (acc, key) {
- acc[obj[key]] = key;
+ var val = fn ? fn(obj[key]) : obj[key];
+ acc[val] = acc[val] || [];
+ acc[val].push(key);
return acc;
}, {});
};
+var is = function is(type, val) {
+ return val instanceof type;
+};
+
var isAbsoluteURL = function isAbsoluteURL(str) {
return (/^[a-z][a-z0-9+.-]*:/.test(str)
);
};
-var isArmstrongNumber = function isArmstrongNumber(digits) {
- return function (arr) {
- return arr.reduce(function (a, d) {
- return a + Math.pow(parseInt(d), arr.length);
- }, 0) == digits;
- }((digits + '').split(''));
+var isAnagram = function isAnagram(str1, str2) {
+ var normalize = function normalize(str) {
+ return str.toLowerCase().replace(/[^a-z0-9]/gi, '').split('').sort().join('');
+ };
+ return normalize(str1) === normalize(str2);
};
-var isArray = function isArray(val) {
- return !!val && Array.isArray(val);
-};
-
-function _toConsumableArray$5(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+function _toConsumableArray$7(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var isArrayLike = function isArrayLike(val) {
try {
- return [].concat(_toConsumableArray$5(val)), true;
+ return [].concat(_toConsumableArray$7(val)), true;
} catch (e) {
return false;
}
@@ -666,6 +1043,10 @@ var isDivisible = function isDivisible(dividend, divisor) {
return dividend % divisor === 0;
};
+var isEmpty = function isEmpty(val) {
+ return val == null || !(Object.keys(val) || val).length;
+};
+
var isEven = function isEven(num) {
return num % 2 === 0;
};
@@ -674,6 +1055,14 @@ var isFunction = function isFunction(val) {
return typeof val === 'function';
};
+var isLowerCase = function isLowerCase(str) {
+ return str === str.toLowerCase();
+};
+
+var isNil = function isNil(val) {
+ return val === undefined || val === null;
+};
+
var isNull = function isNull(val) {
return val === null;
};
@@ -682,23 +1071,39 @@ var isNumber = function isNumber(val) {
return typeof val === 'number';
};
+var isObject = function isObject(obj) {
+ return obj === Object(obj);
+};
+
+var _typeof$3 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
+
+var isObjectLike = function isObjectLike(val) {
+ return val !== null && (typeof val === 'undefined' ? 'undefined' : _typeof$3(val)) === 'object';
+};
+
+var _typeof$4 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
+
+var isPlainObject = function isPlainObject(val) {
+ return !!val && (typeof val === 'undefined' ? 'undefined' : _typeof$4(val)) === 'object' && val.constructor === Object;
+};
+
var isPrime = function isPrime(num) {
var boundary = Math.floor(Math.sqrt(num));
for (var i = 2; i <= boundary; i++) {
- if (num % i == 0) return false;
+ if (num % i === 0) return false;
}return num >= 2;
};
-var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
+var _typeof$5 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var isPrimitive = function isPrimitive(val) {
- return !['object', 'function'].includes(typeof val === 'undefined' ? 'undefined' : _typeof(val)) || val === null;
+ return !['object', 'function'].includes(typeof val === 'undefined' ? 'undefined' : _typeof$5(val)) || val === null;
};
-var _typeof$1 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
+var _typeof$6 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var isPromiseLike = function isPromiseLike(obj) {
- return obj !== null && ((typeof obj === 'undefined' ? 'undefined' : _typeof$1(obj)) === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
+ return obj !== null && ((typeof obj === 'undefined' ? 'undefined' : _typeof$6(obj)) === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
};
var _slicedToArray$1 = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
@@ -740,16 +1145,24 @@ var isString = function isString(val) {
return typeof val === 'string';
};
-var _typeof$2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
+var _typeof$7 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var isSymbol = function isSymbol(val) {
- return (typeof val === 'undefined' ? 'undefined' : _typeof$2(val)) === 'symbol';
+ return (typeof val === 'undefined' ? 'undefined' : _typeof$7(val)) === 'symbol';
};
var isTravisCI = function isTravisCI() {
return 'TRAVIS' in process.env && 'CI' in process.env;
};
+var isUndefined = function isUndefined(val) {
+ return val === undefined;
+};
+
+var isUpperCase = function isUpperCase(str) {
+ return str === str.toUpperCase();
+};
+
var isValidJSON = function isValidJSON(obj) {
try {
JSON.parse(obj);
@@ -763,7 +1176,7 @@ var join = function join(arr) {
var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ',';
var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : separator;
return arr.reduce(function (acc, val, i) {
- return i == arr.length - 2 ? acc + val + end : i == arr.length - 1 ? acc + val : acc + val + separator;
+ return i === arr.length - 2 ? acc + val + end : i === arr.length - 1 ? acc + val : acc + val + separator;
}, '');
};
@@ -772,7 +1185,9 @@ var last = function last(arr) {
};
var lcm = function lcm() {
- var _ref;
+ for (var _len = arguments.length, arr = Array(_len), _key = 0; _key < _len; _key++) {
+ arr[_key] = arguments[_key];
+ }
var gcd = function gcd(x, y) {
return !y ? x : gcd(y, x % y);
@@ -780,11 +1195,21 @@ var lcm = function lcm() {
var _lcm = function _lcm(x, y) {
return x * y / gcd(x, y);
};
- return (_ref = []).concat.apply(_ref, arguments).reduce(function (a, b) {
+ return [].concat(arr).reduce(function (a, b) {
return _lcm(a, b);
});
};
+var longestItem = function longestItem() {
+ for (var _len = arguments.length, vals = Array(_len), _key = 0; _key < _len; _key++) {
+ vals[_key] = arguments[_key];
+ }
+
+ return [].concat(vals).sort(function (a, b) {
+ return b.length - a.length;
+ })[0];
+};
+
var lowercaseKeys = function lowercaseKeys(obj) {
return Object.keys(obj).reduce(function (acc, key) {
acc[key.toLowerCase()] = obj[key];
@@ -804,6 +1229,13 @@ var luhnCheck = function luhnCheck(num) {
return sum % 10 === 0;
};
+var mapKeys = function mapKeys(obj, fn) {
+ return Object.keys(obj).reduce(function (acc, k) {
+ acc[fn(obj[k], k, obj)] = obj[k];
+ return acc;
+ }, {});
+};
+
var mapObject = function mapObject(arr, fn) {
return function (a) {
return a = [arr, arr.map(fn)], a[0].reduce(function (acc, val, ind) {
@@ -812,26 +1244,53 @@ var mapObject = function mapObject(arr, fn) {
}();
};
+var mapValues = function mapValues(obj, fn) {
+ return Object.keys(obj).reduce(function (acc, k) {
+ acc[k] = fn(obj[k], k, obj);
+ return acc;
+ }, {});
+};
+
var mask = function mask(cc) {
var num = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 4;
var mask = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '*';
return ('' + cc).slice(0, -num).replace(/./g, mask) + ('' + cc).slice(-num);
};
-function _toConsumableArray$6(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+var matches = function matches(obj, source) {
+ return Object.keys(source).every(function (key) {
+ return obj.hasOwnProperty(key) && obj[key] === source[key];
+ });
+};
+
+var matchesWith = function matchesWith(obj, source, fn) {
+ return Object.keys(source).every(function (key) {
+ return obj.hasOwnProperty(key) && fn ? fn(obj[key], source[key], key, obj, source) : obj[key] == source[key];
+ });
+};
+
+function _toConsumableArray$8(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var maxBy = function maxBy(arr, fn) {
+ return Math.max.apply(Math, _toConsumableArray$8(arr.map(typeof fn === 'function' ? fn : function (val) {
+ return val[fn];
+ })));
+};
+
+function _toConsumableArray$9(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var maxN = function maxN(arr) {
var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
- return [].concat(_toConsumableArray$6(arr)).sort(function (a, b) {
+ return [].concat(_toConsumableArray$9(arr)).sort(function (a, b) {
return b - a;
}).slice(0, n);
};
-function _toConsumableArray$7(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+function _toConsumableArray$10(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var median = function median(arr) {
var mid = Math.floor(arr.length / 2),
- nums = [].concat(_toConsumableArray$7(arr)).sort(function (a, b) {
+ nums = [].concat(_toConsumableArray$10(arr)).sort(function (a, b) {
return a - b;
});
return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
@@ -846,21 +1305,71 @@ var memoize = function memoize(fn) {
return cached;
};
-function _toConsumableArray$8(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+var merge = function merge() {
+ for (var _len = arguments.length, objs = Array(_len), _key = 0; _key < _len; _key++) {
+ objs[_key] = arguments[_key];
+ }
+
+ return [].concat(objs).reduce(function (acc, obj) {
+ return Object.keys(obj).reduce(function (a, k) {
+ acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k];
+ return acc;
+ }, {});
+ }, {});
+};
+
+function _toConsumableArray$11(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var minBy = function minBy(arr, fn) {
+ return Math.min.apply(Math, _toConsumableArray$11(arr.map(typeof fn === 'function' ? fn : function (val) {
+ return val[fn];
+ })));
+};
+
+function _toConsumableArray$12(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var minN = function minN(arr) {
var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
- return [].concat(_toConsumableArray$8(arr)).sort(function (a, b) {
+ return [].concat(_toConsumableArray$12(arr)).sort(function (a, b) {
return a - b;
}).slice(0, n);
};
+function _toConsumableArray$13(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var mostPerformant = function mostPerformant(fns) {
+ var iterations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10000;
+
+ var times = fns.map(function (fn) {
+ var before = performance.now();
+ for (var i = 0; i < iterations; i++) {
+ fn();
+ }return performance.now() - before;
+ });
+ return times.indexOf(Math.min.apply(Math, _toConsumableArray$13(times)));
+};
+
var negate = function negate(func) {
return function () {
return !func.apply(undefined, arguments);
};
};
+var none = function none(arr) {
+ var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Boolean;
+ return !arr.some(fn);
+};
+
+var nthArg = function nthArg(n) {
+ return function () {
+ for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+
+ return args.slice(n)[0];
+ };
+};
+
var nthElement = function nthElement(arr) {
var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
return (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
@@ -878,6 +1387,54 @@ var objectToPairs = function objectToPairs(obj) {
});
};
+var observeMutations = function observeMutations(element, callback, options) {
+ var observer = new MutationObserver(function (mutations) {
+ return mutations.forEach(function (m) {
+ return callback(m);
+ });
+ });
+ observer.observe(element, Object.assign({
+ childList: true,
+ attributes: true,
+ attributeOldValue: true,
+ characterData: true,
+ characterDataOldValue: true,
+ subtree: true
+ }, options));
+ return observer;
+};
+
+var off = function off(el, evt, fn) {
+ var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
+ return el.removeEventListener(evt, fn, opts);
+};
+
+var omit = function omit(obj, arr) {
+ return Object.keys(obj).filter(function (k) {
+ return !arr.includes(k);
+ }).reduce(function (acc, key) {
+ return acc[key] = obj[key], acc;
+ }, {});
+};
+
+var omitBy = function omitBy(obj, fn) {
+ return Object.keys(obj).filter(function (k) {
+ return !fn(obj[k], k);
+ }).reduce(function (acc, key) {
+ return acc[key] = obj[key], acc;
+ }, {});
+};
+
+var on = function on(el, evt, fn) {
+ var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
+
+ var delegatorFn = function delegatorFn(e) {
+ return e.target.matches(opts.target) && fn.call(e.target, e);
+ };
+ el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false);
+ if (opts.target) return delegatorFn;
+};
+
var onUserInputChange = function onUserInputChange(callback) {
var type = 'mouse',
lastTime = 0;
@@ -908,10 +1465,10 @@ var once = function once(fn) {
var _slicedToArray$2 = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
-function _toConsumableArray$9(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+function _toConsumableArray$14(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var orderBy = function orderBy(arr, props, orders) {
- return [].concat(_toConsumableArray$9(arr)).sort(function (a, b) {
+ return [].concat(_toConsumableArray$14(arr)).sort(function (a, b) {
return props.reduce(function (acc, prop, i) {
if (acc === 0) {
var _ref = orders && orders[i] === 'desc' ? [b[prop], a[prop]] : [a[prop], b[prop]],
@@ -926,23 +1483,128 @@ var orderBy = function orderBy(arr, props, orders) {
});
};
+var over = function over() {
+ for (var _len = arguments.length, fns = Array(_len), _key = 0; _key < _len; _key++) {
+ fns[_key] = arguments[_key];
+ }
+
+ return function () {
+ for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
+ args[_key2] = arguments[_key2];
+ }
+
+ return fns.map(function (fn) {
+ return fn.apply(null, args);
+ });
+ };
+};
+
+function _toConsumableArray$15(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var overArgs = function overArgs(fn, transforms) {
+ return function () {
+ for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+
+ return fn.apply(undefined, _toConsumableArray$15(args.map(function (val, i) {
+ return transforms[i](val);
+ })));
+ };
+};
+
var palindrome = function palindrome(str) {
var s = str.toLowerCase().replace(/[\W_]/g, '');
return s === s.split('').reverse().join('');
};
+var parseCookie = function parseCookie(str) {
+ return str.split(';').map(function (v) {
+ return v.split('=');
+ }).reduce(function (acc, v) {
+ acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());
+ return acc;
+ }, {});
+};
+
+var partial = function partial(fn) {
+ for (var _len = arguments.length, partials = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ partials[_key - 1] = arguments[_key];
+ }
+
+ return function () {
+ for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
+ args[_key2] = arguments[_key2];
+ }
+
+ return fn.apply(undefined, partials.concat(args));
+ };
+};
+
+var partialRight = function partialRight(fn) {
+ for (var _len = arguments.length, partials = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ partials[_key - 1] = arguments[_key];
+ }
+
+ return function () {
+ for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
+ args[_key2] = arguments[_key2];
+ }
+
+ return fn.apply(undefined, args.concat(partials));
+ };
+};
+
+var partition = function partition(arr, fn) {
+ return arr.reduce(function (acc, val, i, arr) {
+ acc[fn(val, i, arr) ? 0 : 1].push(val);
+ return acc;
+ }, [[], []]);
+};
+
var percentile = function percentile(arr, val) {
return 100 * arr.reduce(function (acc, v) {
return acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0);
}, 0) / arr.length;
};
+function _toConsumableArray$16(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var permutations = function permutations(arr) {
+ if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
+ return arr.reduce(function (acc, item, i) {
+ return acc.concat(permutations([].concat(_toConsumableArray$16(arr.slice(0, i)), _toConsumableArray$16(arr.slice(i + 1)))).map(function (val) {
+ return [item].concat(_toConsumableArray$16(val));
+ }));
+ }, []);
+};
+
var pick = function pick(obj, arr) {
return arr.reduce(function (acc, curr) {
return curr in obj && (acc[curr] = obj[curr]), acc;
}, {});
};
+var pickBy = function pickBy(obj, fn) {
+ return Object.keys(obj).filter(function (k) {
+ return fn(obj[k], k);
+ }).reduce(function (acc, key) {
+ return acc[key] = obj[key], acc;
+ }, {});
+};
+
+var pipeAsyncFunctions = function pipeAsyncFunctions() {
+ for (var _len = arguments.length, fns = Array(_len), _key = 0; _key < _len; _key++) {
+ fns[_key] = arguments[_key];
+ }
+
+ return function (arg) {
+ return fns.reduce(function (p, f) {
+ return p.then(f);
+ }, Promise.resolve(arg));
+ };
+};
+
var pipeFunctions = function pipeFunctions() {
for (var _len = arguments.length, fns = Array(_len), _key = 0; _key < _len; _key++) {
fns[_key] = arguments[_key];
@@ -955,7 +1617,7 @@ var pipeFunctions = function pipeFunctions() {
});
};
-var _typeof$3 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
+var _typeof$8 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var pluralize = function pluralize(val, word) {
var plural = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : word + 's';
@@ -964,7 +1626,7 @@ var pluralize = function pluralize(val, word) {
var plural = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : word + 's';
return [1, -1].includes(Number(num)) ? word : plural;
};
- if ((typeof val === 'undefined' ? 'undefined' : _typeof$3(val)) === 'object') return function (num, word) {
+ if ((typeof val === 'undefined' ? 'undefined' : _typeof$8(val)) === 'object') return function (num, word) {
return _pluralize(num, word, val[word]);
};
return _pluralize(val, word, plural);
@@ -999,7 +1661,7 @@ var primes = function primes(num) {
});
numsTillSqroot.forEach(function (x) {
return arr = arr.filter(function (y) {
- return y % x !== 0 || y == x;
+ return y % x !== 0 || y === x;
});
});
return arr;
@@ -1063,25 +1725,40 @@ var pullAtValue = function pullAtValue(arr, pullArr) {
return removed;
};
-function _toConsumableArray$10(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+var pullBy = function pullBy(arr) {
+ for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ args[_key - 1] = arguments[_key];
+ }
-function _toArray$2(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }
+ var length = args.length;
+ var fn = length > 1 ? args[length - 1] : undefined;
+ fn = typeof fn == 'function' ? (args.pop(), fn) : undefined;
+ var argState = (Array.isArray(args[0]) ? args[0] : args).map(function (val) {
+ return fn(val);
+ });
+ var pulled = arr.filter(function (v, i) {
+ return !argState.includes(fn(v));
+ });
+ arr.length = 0;
+ pulled.forEach(function (v) {
+ return arr.push(v);
+ });
+};
-var quickSort = function quickSort(_ref, desc) {
- var _ref2 = _toArray$2(_ref),
- n = _ref2[0],
- nums = _ref2.slice(1);
-
- return isNaN(n) ? [] : [].concat(_toConsumableArray$10(quickSort(nums.filter(function (v) {
- return desc ? v > n : v <= n;
- }), desc)), [n], _toConsumableArray$10(quickSort(nums.filter(function (v) {
- return !desc ? v > n : v <= n;
- }), desc)));
+var radsToDegrees = function radsToDegrees(rad) {
+ return rad * 180.0 / Math.PI;
};
var randomHexColorCode = function randomHexColorCode() {
- var n = (Math.random() * 0xfffff | 0).toString(16);
- return '#' + (n.length !== 6 ? (Math.random() * 0xf | 0).toString(16) + n : n);
+ var n = (Math.random() * 0xfffff * 1000000).toString(16);
+ return '#' + n.slice(0, 6);
+};
+
+var randomIntArrayInRange = function randomIntArrayInRange(min, max) {
+ var n = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
+ return Array.from({ length: n }, function () {
+ return Math.floor(Math.random() * (max - min + 1)) + min;
+ });
};
var randomIntegerInRange = function randomIntegerInRange(min, max) {
@@ -1097,11 +1774,40 @@ var readFileLines = function readFileLines(filename) {
return fs$1.readFileSync(filename).toString('UTF8').split('\n');
};
+function _toConsumableArray$17(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var rearg = function rearg(fn, indexes) {
+ return function () {
+ for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+
+ return fn.apply(undefined, _toConsumableArray$17(args.reduce(function (acc, val, i) {
+ return acc[indexes.indexOf(i)] = val, acc;
+ }, Array.from({ length: indexes.length }))));
+ };
+};
+
var redirect = function redirect(url) {
var asLink = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
return asLink ? window.location.href = url : window.location.replace(url);
};
+var reduceSuccessive = function reduceSuccessive(arr, fn, acc) {
+ return arr.reduce(function (res, val, i, arr) {
+ return res.push(fn(res.slice(-1)[0], val, i, arr)), res;
+ }, [acc]);
+};
+
+var reduceWhich = function reduceWhich(arr) {
+ var comparator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (a, b) {
+ return a - b;
+ };
+ return arr.reduce(function (a, b) {
+ return comparator(a, b) >= 0 ? b : a;
+ });
+};
+
var reducedFilter = function reducedFilter(data, keys, fn) {
return data.filter(fn).map(function (el) {
return keys.reduce(function (acc, key) {
@@ -1118,15 +1824,14 @@ var remove = function remove(arr, func) {
}, []) : [];
};
-var repeatString = function repeatString() {
- var str = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
- var num = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
-
- return num >= 0 ? str.repeat(num) : str;
+var removeNonASCII = function removeNonASCII(str) {
+ return str.replace(/[^\x20-\x7E]/g, '');
};
+function _toConsumableArray$18(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
var reverseString = function reverseString(str) {
- return str.split('').reverse().join('');
+ return [].concat(_toConsumableArray$18(str)).reverse().join('');
};
var round = function round(n) {
@@ -1135,8 +1840,7 @@ var round = function round(n) {
};
var runAsync = function runAsync(fn) {
- var blob = 'var fn = ' + fn.toString() + '; postMessage(fn());';
- var worker = new Worker(URL.createObjectURL(new Blob([blob]), {
+ var worker = new Worker(URL.createObjectURL(new Blob(['postMessage((' + fn + ')());']), {
type: 'application/javascript; charset=utf-8'
}));
return new Promise(function (res, rej) {
@@ -1194,14 +1898,12 @@ var sdbm = function sdbm(str) {
}, 0);
};
-var select = function select(from, selector) {
- return selector.split('.').reduce(function (prev, cur) {
- return prev && prev[cur];
- }, from);
+var serializeCookie = function serializeCookie(name, val) {
+ return encodeURIComponent(name) + "=" + encodeURIComponent(val);
};
-var setStyle = function setStyle(el, ruleName, value) {
- return el.style[ruleName] = value;
+var setStyle = function setStyle(el, ruleName, val) {
+ return el.style[ruleName] = val;
};
var shallowClone = function shallowClone(obj) {
@@ -1240,10 +1942,10 @@ var similarity = function similarity(arr, values) {
});
};
-var _typeof$4 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
+var _typeof$9 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
-var size = function size(value) {
- return Array.isArray(value) ? value.length : value && (typeof value === 'undefined' ? 'undefined' : _typeof$4(value)) === 'object' ? value.size || value.length || Object.keys(value).length : typeof value === 'string' ? new Blob([value]).size : 0;
+var size = function size(val) {
+ return Array.isArray(val) ? val.length : val && (typeof val === 'undefined' ? 'undefined' : _typeof$9(val)) === 'object' ? val.size || val.length || Object.keys(val).length : typeof val === 'string' ? new Blob([val]).size : 0;
};
var sleep = function sleep(ms) {
@@ -1252,48 +1954,10 @@ var sleep = function sleep(ms) {
});
};
-var solveRPN = function solveRPN(rpn) {
- var OPERATORS = {
- '*': function _(a, b) {
- return a * b;
- },
- '+': function _(a, b) {
- return a + b;
- },
- '-': function _(a, b) {
- return a - b;
- },
- '/': function _(a, b) {
- return a / b;
- },
- '**': function _(a, b) {
- return Math.pow(a, b);
- }
- };
- var _ref = [[], rpn.replace(/\^/g, '**').split(/\s+/g).filter(function (el) {
- return !/\s+/.test(el) && el !== '';
- })],
- stack = _ref[0],
- solve = _ref[1];
-
- solve.forEach(function (symbol) {
- if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {
- stack.push(symbol);
- } else if (Object.keys(OPERATORS).includes(symbol)) {
- var _ref2 = [stack.pop(), stack.pop()],
- a = _ref2[0],
- b = _ref2[1];
-
- stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));
- } else {
- throw symbol + ' is not a recognized symbol';
- }
- });
- if (stack.length === 1) return stack.pop();else throw rpn + ' is not a proper RPN. Please check it and try again';
-};
+function _toConsumableArray$19(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var sortCharactersInString = function sortCharactersInString(str) {
- return str.split('').sort(function (a, b) {
+ return [].concat(_toConsumableArray$19(str)).sort(function (a, b) {
return a.localeCompare(b);
}).join('');
};
@@ -1306,24 +1970,59 @@ var sortedIndex = function sortedIndex(arr, n) {
return index === -1 ? arr.length : index;
};
-var speechSynthesis = function speechSynthesis(message) {
- var msg = new SpeechSynthesisUtterance(message);
- msg.voice = window.speechSynthesis.getVoices()[0];
- window.speechSynthesis.speak(msg);
+var sortedIndexBy = function sortedIndexBy(arr, n, fn) {
+ var isDescending = fn(arr[0]) > fn(arr[arr.length - 1]);
+ var val = fn(n);
+ var index = arr.findIndex(function (el) {
+ return isDescending ? val >= fn(el) : val <= fn(el);
+ });
+ return index === -1 ? arr.length : index;
+};
+
+var sortedLastIndex = function sortedLastIndex(arr, n) {
+ var isDescending = arr[0] > arr[arr.length - 1];
+ var index = arr.map(function (val, i) {
+ return [i, val];
+ }).reverse().findIndex(function (el) {
+ return isDescending ? n <= el[1] : n >= el[1];
+ });
+ return index === -1 ? 0 : arr.length - index - 1;
+};
+
+var sortedLastIndexBy = function sortedLastIndexBy(arr, n, fn) {
+ var isDescending = fn(arr[0]) > fn(arr[arr.length - 1]);
+ var val = fn(n);
+ var index = arr.map(function (val, i) {
+ return [i, fn(val)];
+ }).reverse().findIndex(function (el) {
+ return isDescending ? val <= el[1] : val >= el[1];
+ });
+ return index === -1 ? 0 : arr.length - index;
};
var splitLines = function splitLines(str) {
return str.split(/\r?\n/);
};
-function _toConsumableArray$11(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+function _toConsumableArray$20(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var spreadOver = function spreadOver(fn) {
return function (argsArr) {
- return fn.apply(undefined, _toConsumableArray$11(argsArr));
+ return fn.apply(undefined, _toConsumableArray$20(argsArr));
};
};
+var stableSort = function stableSort(arr, compare) {
+ return arr.map(function (item, index) {
+ return { item: item, index: index };
+ }).sort(function (a, b) {
+ return compare(a.item, b.item) || a.index - b.index;
+ }).map(function (_ref) {
+ var item = _ref.item;
+ return item;
+ });
+};
+
var standardDeviation = function standardDeviation(arr) {
var usePopulation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
@@ -1337,10 +2036,33 @@ var standardDeviation = function standardDeviation(arr) {
}, 0) / (arr.length - (usePopulation ? 0 : 1)));
};
-var sum = function sum() {
- var _ref;
+var stringPermutations = function stringPermutations(str) {
+ if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
+ return str.split('').reduce(function (acc, letter, i) {
+ return acc.concat(stringPermutations(str.slice(0, i) + str.slice(i + 1)).map(function (val) {
+ return letter + val;
+ }));
+ }, []);
+};
- return (_ref = []).concat.apply(_ref, arguments).reduce(function (acc, val) {
+var stripHTMLTags = function stripHTMLTags(str) {
+ return str.replace(/<[^>]*>/g, '');
+};
+
+var sum = function sum() {
+ for (var _len = arguments.length, arr = Array(_len), _key = 0; _key < _len; _key++) {
+ arr[_key] = arguments[_key];
+ }
+
+ return [].concat(arr).reduce(function (acc, val) {
+ return acc + val;
+ }, 0);
+};
+
+var sumBy = function sumBy(arr, fn) {
+ return arr.map(typeof fn === 'function' ? fn : function (val) {
+ return val[fn];
+ }).reduce(function (acc, val) {
return acc + val;
}, 0);
};
@@ -1355,18 +2077,48 @@ var sumPower = function sumPower(end) {
}, 0);
};
-function _toConsumableArray$12(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+function _toConsumableArray$21(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var symmetricDifference = function symmetricDifference(a, b) {
var sA = new Set(a),
sB = new Set(b);
- return [].concat(_toConsumableArray$12(a.filter(function (x) {
+ return [].concat(_toConsumableArray$21(a.filter(function (x) {
return !sB.has(x);
- })), _toConsumableArray$12(b.filter(function (x) {
+ })), _toConsumableArray$21(b.filter(function (x) {
return !sA.has(x);
})));
};
+function _toConsumableArray$22(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var symmetricDifferenceBy = function symmetricDifferenceBy(a, b, fn) {
+ var sA = new Set(a.map(function (v) {
+ return fn(v);
+ })),
+ sB = new Set(b.map(function (v) {
+ return fn(v);
+ }));
+ return [].concat(_toConsumableArray$22(a.filter(function (x) {
+ return !sB.has(fn(x));
+ })), _toConsumableArray$22(b.filter(function (x) {
+ return !sA.has(fn(x));
+ })));
+};
+
+function _toConsumableArray$23(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var symmetricDifferenceWith = function symmetricDifferenceWith(arr, val, comp) {
+ return [].concat(_toConsumableArray$23(arr.filter(function (a) {
+ return val.findIndex(function (b) {
+ return comp(a, b);
+ }) === -1;
+ })), _toConsumableArray$23(val.filter(function (a) {
+ return arr.findIndex(function (b) {
+ return comp(a, b);
+ }) === -1;
+ })));
+};
+
var tail = function tail(arr) {
return arr.length > 1 ? arr.slice(1) : arr;
};
@@ -1381,6 +2133,86 @@ var takeRight = function takeRight(arr) {
return arr.slice(arr.length - n, arr.length);
};
+var takeRightWhile = function takeRightWhile(arr, func) {
+ var _iteratorNormalCompletion = true;
+ var _didIteratorError = false;
+ var _iteratorError = undefined;
+
+ try {
+ for (var _iterator = arr.reverse().keys()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
+ var i = _step.value;
+
+ if (func(arr[i])) return arr.reverse().slice(arr.length - i, arr.length);
+ }
+ } catch (err) {
+ _didIteratorError = true;
+ _iteratorError = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion && _iterator.return) {
+ _iterator.return();
+ }
+ } finally {
+ if (_didIteratorError) {
+ throw _iteratorError;
+ }
+ }
+ }
+
+ return arr;
+};
+
+var takeWhile = function takeWhile(arr, func) {
+ var _iteratorNormalCompletion = true;
+ var _didIteratorError = false;
+ var _iteratorError = undefined;
+
+ try {
+ for (var _iterator = arr.keys()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
+ var i = _step.value;
+ if (func(arr[i])) return arr.slice(0, i);
+ }
+ } catch (err) {
+ _didIteratorError = true;
+ _iteratorError = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion && _iterator.return) {
+ _iterator.return();
+ }
+ } finally {
+ if (_didIteratorError) {
+ throw _iteratorError;
+ }
+ }
+ }
+
+ return arr;
+};
+
+var throttle = function throttle(fn, wait) {
+ var inThrottle = void 0,
+ lastFn = void 0,
+ lastTime = void 0;
+ return function () {
+ var context = this,
+ args = arguments;
+ if (!inThrottle) {
+ fn.apply(context, args);
+ lastTime = Date.now();
+ inThrottle = true;
+ } else {
+ clearTimeout(lastFn);
+ lastFn = setTimeout(function () {
+ if (Date.now() - lastTime >= wait) {
+ fn.apply(context, args);
+ lastTime = Date.now();
+ }
+ }, wait - (Date.now() - lastTime));
+ }
+ };
+};
+
var timeTaken = function timeTaken(callback) {
console.time('timeTaken');
var r = callback();
@@ -1388,6 +2220,13 @@ var timeTaken = function timeTaken(callback) {
return r;
};
+var times = function times(n, fn) {
+ var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
+
+ var i = 0;
+ while (fn.call(context, i) !== false && ++i < n) {}
+};
+
var toCamelCase = function toCamelCase(str) {
var s = str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).map(function (x) {
return x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase();
@@ -1395,14 +2234,13 @@ var toCamelCase = function toCamelCase(str) {
return s.slice(0, 1).toLowerCase() + s.slice(1);
};
-var toDecimalMark = function toDecimalMark(num) {
- return num.toLocaleString('en-US');
+var toCurrency = function toCurrency(n, curr) {
+ var LanguageFormat = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
+ return Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n);
};
-var toEnglishDate = function toEnglishDate(time) {
- try {
- return new Date(time).toISOString().split('T')[0].replace(/-/g, '/');
- } catch (e) {}
+var toDecimalMark = function toDecimalMark(num) {
+ return num.toLocaleString('en-US');
};
var toKebabCase = function toKebabCase(str) {
@@ -1420,6 +2258,10 @@ var toOrdinalSuffix = function toOrdinalSuffix(num) {
return oPattern.includes(digits[0]) && !tPattern.includes(digits[1]) ? int + ordinals[digits[0] - 1] : int + ordinals[3];
};
+var toSafeInteger = function toSafeInteger(num) {
+ return Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER));
+};
+
var toSnakeCase = function toSnakeCase(str) {
return str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).map(function (x) {
return x.toLowerCase();
@@ -1431,7 +2273,15 @@ var toggleClass = function toggleClass(el, className) {
};
var tomorrow = function tomorrow() {
- return new Date(new Date().getTime() + 86400000).toISOString().split('T')[0];
+ var t = new Date();
+ t.setDate(t.getDate() + 1);
+ return t.getFullYear() + '-' + String(t.getMonth() + 1).padStart(2, '0') + '-' + String(t.getDate()).padStart(2, '0');
+};
+
+var transform = function transform(obj, fn, acc) {
+ return Object.keys(obj).reduce(function (a, k) {
+ return fn(a, obj[k], k, obj);
+ }, acc);
};
var truncateString = function truncateString(str, num) {
@@ -1444,6 +2294,31 @@ var truthCheckCollection = function truthCheckCollection(collection, pre) {
});
};
+var unary = function unary(fn) {
+ return function (val) {
+ return fn(val);
+ };
+};
+
+var uncurry = function uncurry(fn) {
+ var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
+ return function () {
+ for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+
+ var next = function next(acc) {
+ return function (args) {
+ return args.reduce(function (x, y) {
+ return x(y);
+ }, acc);
+ };
+ };
+ if (n > args.length) throw new RangeError('Arguments too few!');
+ return next(fn)(args.slice(0, n));
+ };
+};
+
var unescapeHTML = function unescapeHTML(str) {
return str.replace(/&|<|>|'|"/g, function (tag) {
return {
@@ -1456,16 +2331,97 @@ var unescapeHTML = function unescapeHTML(str) {
});
};
-function _toConsumableArray$13(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+var unflattenObject = function unflattenObject(obj) {
+ return Object.keys(obj).reduce(function (acc, k) {
+ if (k.indexOf('.') !== -1) {
+ var keys = k.split('.');
+ Object.assign(acc, JSON.parse('{' + keys.map(function (v, i) {
+ return i !== keys.length - 1 ? '"' + v + '":{' : '"' + v + '":';
+ }).join('') + obj[k] + '}'.repeat(keys.length)));
+ } else acc[k] = obj[k];
+ return acc;
+ }, {});
+};
+
+var unfold = function unfold(fn, seed) {
+ var result = [],
+ val = [null, seed];
+ while (val = fn(val[1])) {
+ result.push(val[0]);
+ }return result;
+};
+
+function _toConsumableArray$24(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var union = function union(a, b) {
- return Array.from(new Set([].concat(_toConsumableArray$13(a), _toConsumableArray$13(b))));
+ return Array.from(new Set([].concat(_toConsumableArray$24(a), _toConsumableArray$24(b))));
+};
+
+function _toConsumableArray$25(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var unionBy = function unionBy(a, b, fn) {
+ var s = new Set(a.map(function (v) {
+ return fn(v);
+ }));
+ return Array.from(new Set([].concat(_toConsumableArray$25(a), _toConsumableArray$25(b.filter(function (x) {
+ return !s.has(fn(x));
+ })))));
+};
+
+function _toConsumableArray$26(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var unionWith = function unionWith(a, b, comp) {
+ return Array.from(new Set([].concat(_toConsumableArray$26(a), _toConsumableArray$26(b.filter(function (x) {
+ return a.findIndex(function (y) {
+ return comp(x, y);
+ }) === -1;
+ })))));
+};
+
+function _toConsumableArray$27(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var uniqueElements = function uniqueElements(arr) {
+ return [].concat(_toConsumableArray$27(new Set(arr)));
};
var untildify = function untildify(str) {
return str.replace(/^~($|\/|\\)/, (typeof require !== "undefined" && require('os').homedir()) + "$1");
};
+function _toConsumableArray$28(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var unzip = function unzip(arr) {
+ return arr.reduce(function (acc, val) {
+ return val.forEach(function (v, i) {
+ return acc[i].push(v);
+ }), acc;
+ }, Array.from({
+ length: Math.max.apply(Math, _toConsumableArray$28(arr.map(function (x) {
+ return x.length;
+ })))
+ }).map(function (x) {
+ return [];
+ }));
+};
+
+function _toConsumableArray$29(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var unzipWith = function unzipWith(arr, fn) {
+ return arr.reduce(function (acc, val) {
+ return val.forEach(function (v, i) {
+ return acc[i].push(v);
+ }), acc;
+ }, Array.from({
+ length: Math.max.apply(Math, _toConsumableArray$29(arr.map(function (x) {
+ return x.length;
+ })))
+ }).map(function (x) {
+ return [];
+ })).map(function (val) {
+ return fn.apply(undefined, _toConsumableArray$29(val));
+ });
+};
+
var validateNumber = function validateNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
};
@@ -1485,20 +2441,28 @@ var words = function words(str) {
return str.split(pattern).filter(Boolean);
};
+var xProd = function xProd(a, b) {
+ return a.reduce(function (acc, x) {
+ return acc.concat(b.map(function (y) {
+ return [x, y];
+ }));
+ }, []);
+};
+
var yesNo = function yesNo(val) {
var def = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
return (/^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def
);
};
-function _toConsumableArray$14(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+function _toConsumableArray$30(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var zip = function zip() {
for (var _len = arguments.length, arrays = Array(_len), _key = 0; _key < _len; _key++) {
arrays[_key] = arguments[_key];
}
- var maxLength = Math.max.apply(Math, _toConsumableArray$14(arrays.map(function (x) {
+ var maxLength = Math.max.apply(Math, _toConsumableArray$30(arrays.map(function (x) {
return x.length;
})));
return Array.from({ length: maxLength }).map(function (_, i) {
@@ -1514,7 +2478,30 @@ var zipObject = function zipObject(props, values) {
}, {});
};
-var imports = { JSONToDate: JSONToDate, JSONToFile: JSONToFile, RGBToHex: RGBToHex, UUIDGeneratorBrowser: UUIDGeneratorBrowser, UUIDGeneratorNode: UUIDGeneratorNode, anagrams: anagrams, arrayToHtmlList: arrayToHtmlList, average: average, bottomVisible: bottomVisible, byteSize: byteSize, call: call, capitalize: capitalize, capitalizeEveryWord: capitalizeEveryWord, chainAsync: chainAsync, chunk: chunk, clampNumber: clampNumber, cleanObj: cleanObj, cloneRegExp: cloneRegExp, coalesce: coalesce, coalesceFactory: coalesceFactory, collatz: collatz, collectInto: collectInto, compact: compact, compose: compose, copyToClipboard: copyToClipboard, countOccurrences: countOccurrences, countVowels: countVowels, currentURL: currentURL, curry: curry, deepFlatten: deepFlatten, defer: defer, detectDeviceType: detectDeviceType, difference: difference, differenceWith: differenceWith, digitize: digitize, distance: distance, distinctValuesOfArray: distinctValuesOfArray, dropElements: dropElements, dropRight: dropRight, elementIsVisibleInViewport: elementIsVisibleInViewport, elo: elo, escapeHTML: escapeHTML, escapeRegExp: escapeRegExp, everyNth: everyNth, extendHex: extendHex, factorial: factorial, factors: factors, fibonacci: fibonacci, fibonacciCountUntilNum: fibonacciCountUntilNum, fibonacciUntilNum: fibonacciUntilNum, filterNonUnique: filterNonUnique, flatten: flatten, flattenDepth: flattenDepth, flip: flip, formatDuration: formatDuration, fromCamelCase: fromCamelCase, functionName: functionName, gcd: gcd, geometricProgression: geometricProgression, getDaysDiffBetweenDates: getDaysDiffBetweenDates, getScrollPosition: getScrollPosition, getStyle: getStyle, getType: getType, getURLParameters: getURLParameters, groupBy: groupBy, hammingDistance: hammingDistance, hasClass: hasClass, hasFlags: hasFlags, head: head, hexToRGB: hexToRGB, hide: hide, howManyTimes: howManyTimes, httpsRedirect: httpsRedirect, inRange: inRange, initial: initial, initialize2DArray: initialize2DArray, initializeArrayWithRange: initializeArrayWithRange, initializeArrayWithValues: initializeArrayWithValues, intersection: intersection, invertKeyValues: invertKeyValues, isAbsoluteURL: isAbsoluteURL, isArmstrongNumber: isArmstrongNumber, isArray: isArray, isArrayLike: isArrayLike, isBoolean: isBoolean, isDivisible: isDivisible, isEven: isEven, isFunction: isFunction, isNull: isNull, isNumber: isNumber, isPrime: isPrime, isPrimitive: isPrimitive, isPromiseLike: isPromiseLike, isSorted: isSorted, isString: isString, isSymbol: isSymbol, isTravisCI: isTravisCI, isValidJSON: isValidJSON, join: join, last: last, lcm: lcm, lowercaseKeys: lowercaseKeys, luhnCheck: luhnCheck, mapObject: mapObject, mask: mask, maxN: maxN, median: median, memoize: memoize, minN: minN, negate: negate, nthElement: nthElement, objectFromPairs: objectFromPairs, objectToPairs: objectToPairs, onUserInputChange: onUserInputChange, once: once, orderBy: orderBy, palindrome: palindrome, percentile: percentile, pick: pick, pipeFunctions: pipeFunctions, pluralize: pluralize, powerset: powerset, prettyBytes: prettyBytes, primes: primes, promisify: promisify, pull: pull, pullAtIndex: pullAtIndex, pullAtValue: pullAtValue, quickSort: quickSort, randomHexColorCode: randomHexColorCode, randomIntegerInRange: randomIntegerInRange, randomNumberInRange: randomNumberInRange, readFileLines: readFileLines, redirect: redirect, reducedFilter: reducedFilter, remove: remove, repeatString: repeatString, reverseString: reverseString, round: round, runAsync: runAsync, runPromisesInSeries: runPromisesInSeries, sample: sample, sampleSize: sampleSize, scrollToTop: scrollToTop, sdbm: sdbm, select: select, setStyle: setStyle, shallowClone: shallowClone, show: show, shuffle: shuffle, similarity: similarity, size: size, sleep: sleep, solveRPN: solveRPN, sortCharactersInString: sortCharactersInString, sortedIndex: sortedIndex, speechSynthesis: speechSynthesis, splitLines: splitLines, spreadOver: spreadOver, standardDeviation: standardDeviation, sum: sum, sumPower: sumPower, symmetricDifference: symmetricDifference, tail: tail, take: take, takeRight: takeRight, timeTaken: timeTaken, toCamelCase: toCamelCase, toDecimalMark: toDecimalMark, toEnglishDate: toEnglishDate, toKebabCase: toKebabCase, toOrdinalSuffix: toOrdinalSuffix, toSnakeCase: toSnakeCase, toggleClass: toggleClass, tomorrow: tomorrow, truncateString: truncateString, truthCheckCollection: truthCheckCollection, unescapeHTML: unescapeHTML, union: union, untildify: untildify, validateNumber: validateNumber, without: without, words: words, yesNo: yesNo, zip: zip, zipObject: zipObject };
+function _toConsumableArray$31(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var zipWith = function zipWith() {
+ for (var _len = arguments.length, arrays = Array(_len), _key = 0; _key < _len; _key++) {
+ arrays[_key] = arguments[_key];
+ }
+
+ var length = arrays.length;
+ var fn = length > 1 ? arrays[length - 1] : undefined;
+ fn = typeof fn == 'function' ? (arrays.pop(), fn) : undefined;
+ var maxLength = Math.max.apply(Math, _toConsumableArray$31(arrays.map(function (x) {
+ return x.length;
+ })));
+ var result = Array.from({ length: maxLength }).map(function (_, i) {
+ return Array.from({ length: arrays.length }, function (_, k) {
+ return arrays[k][i];
+ });
+ });
+ return fn ? result.map(function (arr) {
+ return fn.apply(undefined, _toConsumableArray$31(arr));
+ }) : result;
+};
+
+var imports = { JSONToFile: JSONToFile, RGBToHex: RGBToHex, URLJoin: URLJoin, UUIDGeneratorBrowser: UUIDGeneratorBrowser, UUIDGeneratorNode: UUIDGeneratorNode, all: all, any: any, approximatelyEqual: approximatelyEqual, arrayToHtmlList: arrayToHtmlList, ary: ary, atob: atob, attempt: attempt, average: average, averageBy: averageBy, bifurcate: bifurcate, bifurcateBy: bifurcateBy, bind: bind, bindAll: bindAll, bindKey: bindKey, binomialCoefficient: binomialCoefficient, bottomVisible: bottomVisible, btoa: btoa, byteSize: byteSize, call: call, capitalize: capitalize, capitalizeEveryWord: capitalizeEveryWord, castArray: castArray, chainAsync: chainAsync, chunk: chunk, clampNumber: clampNumber, cloneRegExp: cloneRegExp, coalesce: coalesce, coalesceFactory: coalesceFactory, collectInto: collectInto, colorize: colorize, compact: compact, compose: compose, composeRight: composeRight, converge: converge, copyToClipboard: copyToClipboard, countBy: countBy, countOccurrences: countOccurrences, createElement: createElement, createEventHub: createEventHub, currentURL: currentURL, curry: curry, debounce: debounce, decapitalize: decapitalize, deepClone: deepClone, deepFlatten: deepFlatten, defaults: defaults, defer: defer, degreesToRads: degreesToRads, delay: delay, detectDeviceType: detectDeviceType, difference: difference, differenceBy: differenceBy, differenceWith: differenceWith, digitize: digitize, distance: distance, drop: drop, dropRight: dropRight, dropRightWhile: dropRightWhile, dropWhile: dropWhile, elementIsVisibleInViewport: elementIsVisibleInViewport, elo: elo, equals: equals, escapeHTML: escapeHTML, escapeRegExp: escapeRegExp, everyNth: everyNth, extendHex: extendHex, factorial: factorial, fibonacci: fibonacci, filterNonUnique: filterNonUnique, findKey: findKey, findLast: findLast, findLastIndex: findLastIndex, findLastKey: findLastKey, flatten: flatten, flattenObject: flattenObject, flip: flip, forEachRight: forEachRight, forOwn: forOwn, forOwnRight: forOwnRight, formatDuration: formatDuration, fromCamelCase: fromCamelCase, functionName: functionName, functions: functions, gcd: gcd, geometricProgression: geometricProgression, get: get, getColonTimeFromDate: getColonTimeFromDate, getDaysDiffBetweenDates: getDaysDiffBetweenDates, getMeridiemSuffixOfInteger: getMeridiemSuffixOfInteger, getScrollPosition: getScrollPosition, getStyle: getStyle, getType: getType, getURLParameters: getURLParameters, groupBy: groupBy, hammingDistance: hammingDistance, hasClass: hasClass, hasFlags: hasFlags, hashBrowser: hashBrowser, hashNode: hashNode, head: head, hexToRGB: hexToRGB, hide: hide, httpGet: httpGet, httpPost: httpPost, httpsRedirect: httpsRedirect, inRange: inRange, indexOfAll: indexOfAll, initial: initial, initialize2DArray: initialize2DArray, initializeArrayWithRange: initializeArrayWithRange, initializeArrayWithRangeRight: initializeArrayWithRangeRight, initializeArrayWithValues: initializeArrayWithValues, intersection: intersection, intersectionBy: intersectionBy, intersectionWith: intersectionWith, invertKeyValues: invertKeyValues, is: is, isAbsoluteURL: isAbsoluteURL, isAnagram: isAnagram, isArrayLike: isArrayLike, isBoolean: isBoolean, isDivisible: isDivisible, isEmpty: isEmpty, isEven: isEven, isFunction: isFunction, isLowerCase: isLowerCase, isNil: isNil, isNull: isNull, isNumber: isNumber, isObject: isObject, isObjectLike: isObjectLike, isPlainObject: isPlainObject, isPrime: isPrime, isPrimitive: isPrimitive, isPromiseLike: isPromiseLike, isSorted: isSorted, isString: isString, isSymbol: isSymbol, isTravisCI: isTravisCI, isUndefined: isUndefined, isUpperCase: isUpperCase, isValidJSON: isValidJSON, join: join, last: last, lcm: lcm, longestItem: longestItem, lowercaseKeys: lowercaseKeys, luhnCheck: luhnCheck, mapKeys: mapKeys, mapObject: mapObject, mapValues: mapValues, mask: mask, matches: matches, matchesWith: matchesWith, maxBy: maxBy, maxN: maxN, median: median, memoize: memoize, merge: merge, minBy: minBy, minN: minN, mostPerformant: mostPerformant, negate: negate, none: none, nthArg: nthArg, nthElement: nthElement, objectFromPairs: objectFromPairs, objectToPairs: objectToPairs, observeMutations: observeMutations, off: off, omit: omit, omitBy: omitBy, on: on, onUserInputChange: onUserInputChange, once: once, orderBy: orderBy, over: over, overArgs: overArgs, palindrome: palindrome, parseCookie: parseCookie, partial: partial, partialRight: partialRight, partition: partition, percentile: percentile, permutations: permutations, pick: pick, pickBy: pickBy, pipeAsyncFunctions: pipeAsyncFunctions, pipeFunctions: pipeFunctions, pluralize: pluralize, powerset: powerset, prettyBytes: prettyBytes, primes: primes, promisify: promisify, pull: pull, pullAtIndex: pullAtIndex, pullAtValue: pullAtValue, pullBy: pullBy, radsToDegrees: radsToDegrees, randomHexColorCode: randomHexColorCode, randomIntArrayInRange: randomIntArrayInRange, randomIntegerInRange: randomIntegerInRange, randomNumberInRange: randomNumberInRange, readFileLines: readFileLines, rearg: rearg, redirect: redirect, reduceSuccessive: reduceSuccessive, reduceWhich: reduceWhich, reducedFilter: reducedFilter, remove: remove, removeNonASCII: removeNonASCII, reverseString: reverseString, round: round, runAsync: runAsync, runPromisesInSeries: runPromisesInSeries, sample: sample, sampleSize: sampleSize, scrollToTop: scrollToTop, sdbm: sdbm, serializeCookie: serializeCookie, setStyle: setStyle, shallowClone: shallowClone, show: show, shuffle: shuffle, similarity: similarity, size: size, sleep: sleep, sortCharactersInString: sortCharactersInString, sortedIndex: sortedIndex, sortedIndexBy: sortedIndexBy, sortedLastIndex: sortedLastIndex, sortedLastIndexBy: sortedLastIndexBy, splitLines: splitLines, spreadOver: spreadOver, stableSort: stableSort, standardDeviation: standardDeviation, stringPermutations: stringPermutations, stripHTMLTags: stripHTMLTags, sum: sum, sumBy: sumBy, sumPower: sumPower, symmetricDifference: symmetricDifference, symmetricDifferenceBy: symmetricDifferenceBy, symmetricDifferenceWith: symmetricDifferenceWith, tail: tail, take: take, takeRight: takeRight, takeRightWhile: takeRightWhile, takeWhile: takeWhile, throttle: throttle, timeTaken: timeTaken, times: times, toCamelCase: toCamelCase, toCurrency: toCurrency, toDecimalMark: toDecimalMark, toKebabCase: toKebabCase, toOrdinalSuffix: toOrdinalSuffix, toSafeInteger: toSafeInteger, toSnakeCase: toSnakeCase, toggleClass: toggleClass, tomorrow: tomorrow, transform: transform, truncateString: truncateString, truthCheckCollection: truthCheckCollection, unary: unary, uncurry: uncurry, unescapeHTML: unescapeHTML, unflattenObject: unflattenObject, unfold: unfold, union: union, unionBy: unionBy, unionWith: unionWith, uniqueElements: uniqueElements, untildify: untildify, unzip: unzip, unzipWith: unzipWith, validateNumber: validateNumber, without: without, words: words, xProd: xProd, yesNo: yesNo, zip: zip, zipObject: zipObject, zipWith: zipWith };
return imports;
diff --git a/dist/_30s.es5.min.js b/dist/_30s.es5.min.js
index fcad427b8..1e206da34 100644
--- a/dist/_30s.es5.min.js
+++ b/dist/_30s.es5.min.js
@@ -1 +1 @@
-(function(a,b){'object'==typeof exports&&'undefined'!=typeof module?module.exports=b():'function'==typeof define&&define.amd?define(b):a._30s=b()})(this,function(){'use strict';function a(a){return Array.isArray(a)?a:Array.from(a)}function b(a){if(Array.isArray(a)){for(var b=0,c=Array(a.length);b>a/4).toString(16)})},UUIDGeneratorNode:function(){return'10000000-1000-4000-8000-100000000000'.replace(/[018]/g,function(a){return(a^C.randomBytes(1)[0]&15>>a/4).toString(16)})},anagrams:function a(b){return 2>=b.length?2===b.length?[b,b[1]+b[0]]:[b]:b.split('').reduce(function(c,d,e){return c.concat(a(b.slice(0,e)+b.slice(e+1)).map(function(a){return d+a}))},[])},arrayToHtmlList:function(a,b){return a.map(function(a){return document.querySelector('#'+b).innerHTML+='