/** * ### 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(array: Array, identity?: (x: T) => unknown): Array { if (!identity) { return primitiveUnique(array) } return objectUnique(array, identity) } function primitiveUnique(array: Array): Array { return Array.from(new Set(array)) } function objectUnique(array: Array, identity: (x: T) => unknown): Array { const identities = array.map((x) => identity(x)) return array.filter((_, i) => identities.indexOf(identities[i]) === i) }