Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add breakFunc argument to use break in the “map” function #312

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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'])
})
})
Loading