-
Notifications
You must be signed in to change notification settings - Fork 2
/
unique.ts
36 lines (32 loc) · 1.14 KB
/
unique.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* ### unique(array, identity?)
*
* Create a duplicate-free version of an array, in which only the first occurrence of each element is kept.
* The order of result values is determined by the order they occur in the array.
* Can be passed an optional `identity` function to select the identifying part of objects.
*
* ```js
* flocky.unique([1, 1, 2, 4, 2, 1, 6])
* // -> [1, 2, 4, 6]
*
* flocky.unique(['foo', 'bar', 'foo', 'foobar'])
* // -> ['foo', 'bar', 'foobar']
*
* const input = [{ id: 1, a: 1 }, { id: 1, a: 2 }, { id: 2, a: 3 }, { id: 1, a: 4 }]
* flocky.unique(input, (element) => element.id)
* // -> [{ id: 1, a: 1 }, { id: 2, a: 3 }]
* ```
*/
export function unique<T>(array: Array<T>, identity?: (x: T) => unknown): Array<T> {
if (!identity) {
return primitiveUnique(array)
}
return objectUnique(array, identity)
}
function primitiveUnique<T>(array: Array<T>): Array<T> {
return Array.from(new Set(array))
}
function objectUnique<T>(array: Array<T>, identity: (x: T) => unknown): Array<T> {
const identities = array.map((x) => identity(x))
return array.filter((_, i) => identities.indexOf(identities[i]) === i)
}