The chainable forEach().
- JavaScript 100%
| .gitignore | Remove build setup | |
| foreachain.browser.js | Rename files | |
| foreachain.common.js | Rename files | |
| foreachain.d.ts | Add type definitions | |
| foreachain.module.js | Rename files | |
| LICENSE | Update year in LICENSE | |
| package.json | 2.0.2 | |
| README.md | Update licence link in README | |
foreachain
The chainable
forEach().
[2,3,5].forEachain(v => {console.log(v)})
.map(v => v * 3)
.forEach(v => {console.log(v)});
Why?
I don't really know. I just imagined that there can be a task like this:
- Output array data, element by element
- Modify array
- Output data again
And this can't be done in JavaScript in one long chained function call.
...well, OK, it can be done like this:
[2,3,5].map(v => {console.log(v);return v})
.map(v => v * 3)
.forEach(v => {console.log(v)});
But I find the first map call unreadable and confusing. So, this is my solution.
How?
-
npm i foreachainor
<script src="https://cdn.jsdelivr.net/npm/foreachain/foreachain.browser.min.js"></script>or (for modern browsers)
<script type="module"> import foreachain from 'https://cdn.jsdelivr.net/npm/foreachain/foreachain.module.min.js'; </script> -
// if you're not in browser import foreachain from 'foreachain'; /* DO NOT overwrite the original forEach. * This is unethical. * * ...and will break your code. */ [].constructor.prototype.forEachain = foreachain; -
[2,3,5].forEachain(v => {console.log(v)}) .map(v => v * 3) .forEach(v => {console.log(v)});
Is this necessary to have as a separate package?
If you think that the answer should be "No", you can copy the source code over to your codebase.
List of times I found use for a chainable forEach
I'm still looking...
Licence
MIT © 2020-2021 Nikita Karamov