asyncFilter()
This commit is contained in:
parent
5b9ef555ae
commit
cf600c8876
3 changed files with 82 additions and 0 deletions
24
utils/helpers.js
Normal file
24
utils/helpers.js
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
/**
|
||||||
|
* @format
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @template T
|
||||||
|
* @typedef {(value: T) => Promise<boolean>} AsyncFilterCallback
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @template T
|
||||||
|
* @param {T[]} arr
|
||||||
|
* @param {AsyncFilterCallback<T>} cb
|
||||||
|
* @returns {Promise<T[]>}
|
||||||
|
*/
|
||||||
|
const asyncFilter = async (arr, cb) => {
|
||||||
|
const results = await Promise.all(arr.map(item => cb(item)))
|
||||||
|
|
||||||
|
return arr.filter((_, i) => results[i])
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
asyncFilter
|
||||||
|
}
|
||||||
49
utils/helpers.spec.js
Normal file
49
utils/helpers.spec.js
Normal file
|
|
@ -0,0 +1,49 @@
|
||||||
|
/**
|
||||||
|
* @format
|
||||||
|
*/
|
||||||
|
|
||||||
|
const { asyncFilter } = require('./helpers')
|
||||||
|
|
||||||
|
const numbers = [1, 2, 3, 4]
|
||||||
|
const odds = [1, 3]
|
||||||
|
const evens = [2, 4]
|
||||||
|
|
||||||
|
describe('asyncFilter()', () => {
|
||||||
|
it('returns an empty array when given one', async () => {
|
||||||
|
expect.hasAssertions()
|
||||||
|
const result = await asyncFilter([], () => true)
|
||||||
|
|
||||||
|
expect(result).toStrictEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects', async () => {
|
||||||
|
expect.hasAssertions()
|
||||||
|
|
||||||
|
const result = await asyncFilter(numbers, () => false)
|
||||||
|
|
||||||
|
expect(result).toStrictEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects via calling with the correct value', async () => {
|
||||||
|
expect.hasAssertions()
|
||||||
|
|
||||||
|
const result = await asyncFilter(numbers, v => v % 2 !== 0)
|
||||||
|
|
||||||
|
expect(result).toStrictEqual(odds)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('filters via calling with the correct value', async () => {
|
||||||
|
expect.hasAssertions()
|
||||||
|
|
||||||
|
const result = await asyncFilter(numbers, v => v % 2 === 0)
|
||||||
|
|
||||||
|
expect(result).toStrictEqual(evens)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('handles promises', async () => {
|
||||||
|
expect.hasAssertions()
|
||||||
|
|
||||||
|
const result = await asyncFilter(numbers, v => Promise.resolve(v % 2 === 0))
|
||||||
|
expect(result).toStrictEqual(evens)
|
||||||
|
})
|
||||||
|
})
|
||||||
9
utils/index.js
Normal file
9
utils/index.js
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
/**
|
||||||
|
* @format
|
||||||
|
*/
|
||||||
|
|
||||||
|
const { asyncFilter } = require('./helpers')
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
asyncFilter
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue