Skip to content

Commit

Permalink
feat(unique): let toKey return any kind of value (#10)
Browse files Browse the repository at this point in the history
* fix(unique): support any value

…instead of only values that can be identified through a key or can be used as keys themselves.

* test: add a test

Thanks to @jordydhoker for contributing this test: sodiray/radash#343

* fix(unique): skip `reduce` call if `toKey` is not defined

Co-authored-by: jordydhoker <[email protected]>
  • Loading branch information
aleclarson and jordydhoker authored Jun 25, 2024
1 parent 57c354c commit 3fd8446
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 8 deletions.
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)]
}

0 comments on commit 3fd8446

Please sign in to comment.