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(unique): let toKey return any kind of value #10

Merged
merged 3 commits into from
Jun 25, 2024
Merged
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
20 changes: 20 additions & 0 deletions src/array/tests/unique.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,24 @@ describe('unique function', () => {
expect(c.id).toBe('c')
expect(c.word).toBe('yolo')
})
test('correctly handles non string, number or symbol values', () => {
const list: any[] = [
null,
null,
true,
true,
'true',
false,
{ id: 'a', word: 'hello' },
{ id: 'a', word: 'hello' }
]
const result = _.unique(list, val => (val && val.id) ?? val)
expect(result).toEqual([
null,
true,
'true',
false,
{ id: 'a', word: 'hello' }
])
})
})
21 changes: 13 additions & 8 deletions src/array/unique.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,20 @@
* Accepts an optional identity function to convert each item in the
* list to a comparable identity value
*/
export const unique = <T, K extends string | number | symbol>(
export const unique = <T, K = T>(
array: readonly T[],
toKey?: (item: T) => K
): T[] => {
const valueMap = array.reduce((acc, item) => {
const key = toKey ? toKey(item) : (item as any as string | number | symbol)
if (acc[key]) return acc
acc[key] = item
return acc
}, {} as Record<string | number | symbol, T>)
return Object.values(valueMap)
if (toKey) {
const keys = new Set<K>()
return array.reduce((acc, item) => {
const key = toKey(item)
if (!keys.has(key)) {
keys.add(key)
acc.push(item)
}
return acc
}, [] as T[])
}
return [...new Set(array)]
}