Skip to content

Commit d26151d

Browse files
committed
Refactor array utility
1 parent fa4d984 commit d26151d

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

server/src/util/array.ts

+14-7
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,24 @@ export function uniq<A>(a: A[]): A[] {
1515

1616
/**
1717
* Removed all duplicates from the list based on the hash function.
18+
* First element matching the hash function wins.
1819
*/
19-
export function uniqueBasedOnHash<A>(list: A[], elementToHash: (a: A) => string): A[] {
20-
const hashSet = new Set()
20+
export function uniqueBasedOnHash<A extends Record<string, any>>(
21+
list: A[],
22+
elementToHash: (a: A) => string,
23+
__result: A[] = [],
24+
): A[] {
25+
const result: typeof list = []
26+
const hashSet = new Set<string>()
2127

22-
return list.reduce((accumulator, currentValue) => {
23-
const hash = elementToHash(currentValue)
28+
list.forEach(element => {
29+
const hash = elementToHash(element)
2430
if (hashSet.has(hash)) {
25-
return accumulator
31+
return
2632
}
2733
hashSet.add(hash)
34+
result.push(element)
35+
})
2836

29-
return [...accumulator, currentValue]
30-
}, [])
37+
return result
3138
}

0 commit comments

Comments
 (0)