Skip to content

Commit

Permalink
fix(unique): skip reduce call if toKey is not defined
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Jun 24, 2024
1 parent 50ee1b9 commit 9857a6b
Showing 1 changed file with 12 additions and 9 deletions.
21 changes: 12 additions & 9 deletions src/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,15 +295,18 @@ export const unique = <T, K = T>(
array: readonly T[],
toKey?: (item: T) => K
): T[] => {
const known = new Set<T | K>()
return array.reduce((acc, item) => {
const key = toKey ? toKey(item) : item
if (!known.has(key)) {
known.add(key)
acc.push(item)
}
return acc
}, [] as T[])
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)]
}

/**
Expand Down

0 comments on commit 9857a6b

Please sign in to comment.