Skip to content

Commit

Permalink
feat(select): let condition be undefined (#9)
Browse files Browse the repository at this point in the history
* feat(select): let `condition` be undefined

* test: select without a condition callback

Co-authored-by: Adam C Hamlin <[email protected]>
  • Loading branch information
aleclarson and adamhamlin committed Jun 25, 2024
1 parent 3fd8446 commit dc74ace
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/array/select.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@
export const select = <T, K>(
array: readonly T[],
mapper: (item: T, index: number) => K,
condition: (item: T, index: number) => boolean
condition?: (item: T, index: number) => boolean
) => {
if (!array) return []
let mapped: K
return array.reduce((acc, item, index) => {
if (!condition(item, index)) return acc
acc.push(mapper(item, index))
if (condition) condition(item, index) && acc.push(mapper(item, index))
else (mapped = mapper(item, index)) != null && acc.push(mapped)
return acc
}, [] as K[])
}
5 changes: 5 additions & 0 deletions src/array/tests/select.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,9 @@ describe('select function', () => {
)
expect(result).toEqual(['c2', 'd3'])
})
test('works without a condition callback', () => {
const list = [{ a: 1 }, { b: 2 }, { a: 3 }, { a: null }, { a: undefined }]
const result = _.select(list, obj => obj.a)
expect(result).toEqual([1, 3])
})
})

0 comments on commit dc74ace

Please sign in to comment.