Skip to content

Commit

Permalink
Add correct handling of non string, number or symbol values to unique
Browse files Browse the repository at this point in the history
  • Loading branch information
jordydhoker committed Aug 30, 2023
1 parent 03dd315 commit 512b76e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
12 changes: 6 additions & 6 deletions src/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,17 +289,17 @@ export const cluster = <T>(list: readonly T[], size: number = 2): T[][] => {
* 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>(
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
const key = toKey ? toKey(item) : item
if (acc.get(key)) return acc
acc.set(key, item)
return acc
}, {} as Record<string | number | symbol, T>)
return Object.values(valueMap)
}, new Map())
return Array.from(valueMap.values());
}

/**
Expand Down
21 changes: 21 additions & 0 deletions src/tests/array.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,27 @@ describe('array module', () => {
assert.equal(c.id, 'c')
assert.equal(c.word, 'yolo')
})
test('correctly handles non string, number or symbol values', () => {
const list = [
null,
null,
true,
true,
"true",
false,
{ id: 'a', word: 'hello' },
{ id: 'a', word: 'hello' },
]
const result = _.unique(list)
assert.deepEqual(result, [
null,
true,
"true",
false,
{ id: 'a', word: 'hello' },
{ id: 'a', word: 'hello' },
])
})
})

describe('range function', () => {
Expand Down

0 comments on commit 512b76e

Please sign in to comment.