1.0.3 • Published 6 years ago
array-reducer v1.0.3
array-reducer
Never carry anymore about async reduce an array. Install with:
npm i array-reducerStart requiring and then make the magic happen
const reducer = require('array-reducer')You might need 3 arguments:
reducer(array, fn, acc)arraymight be an array of whatever you wantfnis your reducer function. Here you can go async or sync, doesn't matteraccis the default accumulator value for your reducer functionfn
Samples
You might use reducers the way you want withouth carying if the reducer function shall fetch something from the database, make an external api call or a simple sum.
async/await
Make things meaningful, avoid promise/callback hell!
const reducer = require('array-reducer')
const arr = [1, 2, 3, 4]
const sum = async (n, m) => n + m
const result = await reducer(arr, sum, 0)
console.log(result) // 10promise
Connect in a promise chain
const reducer = require('array-reducer')
const arr = [1, 2, 3, 4]
const sum = (n, m) => new Promise(resolve => resolve(n + m))
reducer(arr, sum, 3).then((result) => {
console.log(result) // 13
})standard/sync
Go simple
const reducer = require('array-reducer')
const arr = [1, 2, 3, 4]
const sum = (n, m) => n + m
const result = reducer(arr, sum, 5)
console.log(result) // 15Go beyond! Go fancy!
It's not only about numbers or aggregations, we can go further.
const reducer = require('array-reducer')
const arr = [['drink', 'beer'], ['eat', 'hotdog']]
const toObject = (obj, [prop, value]) => ({
...obj,
[prop]: value,
})
const result = reducer(arr, toObject, {})
console.log(result) // { drink: 'beer', eat: 'hotdog' }