async/await-ready
array methods for Node.js
Installation · Docs · Usage
Follow @marcuspoehls and @superchargejs for updates!
This package is ESM-only.
The @supercharge/collections
package provides a convenient, fully-async wrapper to work with arrays.
npm i @supercharge/collections
Find all the details and available methods in the extensive Supercharge docs.
The package exports a function accepting an array as a parameter. From there, you can chain all collection methods.
Collections are asynchronous by default. You can use async
callback functions in all methods and need to await
the result.
In contrast to JavaScript’s array methods, collections have a lot more methods available making your code a lot simpler. Here are basic examples using a collection:
import User from '../models/user'
import Collect from '@supercharge/collections'
const users = await User.findAll()
const notSubscribedUsers = await Collect(users).filter(user => {
return user.notSubscribedToNewsletter
})
// notSubscribedUsers = [ <list of not-yet-subscribed users> ]
// you can also chain further methods to the collection
const users = await User.findAll()
const subscribedUsers = await Collect(users)
.filter(user => {
return user.notSubscribedToNewsletter
})
.map(async user => { // <-- providing an async callback creates an async collection that you need to `await`
await user.subscribeToNewsletter()
return user
})
// subscribedUsers = [ <list of newly-subscribed users> ]
Here’s another example outlining how to determine whether the array “has” an item:
// “has” in JS Arrays
const hasNotSubscribedUsers = !![].concat(users).find(user => {
return user.notSubscribedToNewsletter
})
// “has” in Collections
const hasNotSubscribedUsers = Collect(users).has(async user => {
return await User.isSubcribedToNewsletter(user)
})
All available methods are outlined in the docs.
Do you miss a collection function? We very much appreciate your contribution! Please send in a pull request 😊
- Create a fork
- Create your feature branch:
git checkout -b my-feature
- Commit your changes:
git commit -am 'Add some feature'
- Push to the branch:
git push origin my-new-feature
- Submit a pull request 🚀
MIT © Supercharge
superchargejs.com · GitHub @supercharge · Twitter @superchargejs