Skip to content

Commit

Permalink
fix: map function added breakFunc
Browse files Browse the repository at this point in the history
  • Loading branch information
moowoonsunghoon committed Nov 14, 2024
1 parent 1ffc439 commit fa541b7
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
10 changes: 10 additions & 0 deletions docs/async/map.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,14 @@ const api = {
const users = await _.map(userIds, async userId => {
return await api.users.find(userId)
}) // [true, true, false, false]

const users = await _.map(
userIds,
async userId => {
return await api.users.find(userId)
},
user => {
return user === 3
},
) // [true, true]
```
7 changes: 6 additions & 1 deletion src/async/map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,19 @@
export async function map<T, K>(
array: readonly T[],
asyncMapFunc: (item: T, index: number) => Promise<K>,
breakFunc?: (result: Awaited<K>, item: T, index: number) => boolean,
): Promise<K[]> {
if (!array) {
return []
}
const result = []
let index = 0
for (const value of array) {
const newValue = await asyncMapFunc(value, index++)
const newValue = await asyncMapFunc(value, index)

if (breakFunc && breakFunc(newValue, value, index)) break

index++
result.push(newValue)
}
return result
Expand Down
10 changes: 10 additions & 0 deletions tests/async/map.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,14 @@ describe('map', () => {
const result = await _.map(array, mapper)
expect(result).toEqual(['a0', 'b1', 'c2', 'd3'])
})

test('returns result with break', async () => {
const array = ['a', 'b', 'c', 'd']
const mapper = async (l: string, index: number) => `${l}${index}`
const breakFunc = (result: string, item: string, index: number) =>{
return item === 'c' && result === `${item}${index}`
}
const result = await _.map(array, mapper, breakFunc)
expect(result).toEqual(['a0', 'b1'])
})
})

0 comments on commit fa541b7

Please sign in to comment.