Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | 8x 8x 8x 6x 4x 6x 6x 35x 35x 11x 24x 24x | import { purry } from './purry';
import { _reduceLazy, LazyResult } from './_reduceLazy';
/**
* Returns a new array containing only one copy of each element in the original list transformed by a function.
* Elements are compared by reference using Set.
* @param array - List of items
* @signature
* P.uniqBy(fn, array)
* @signature
* P.pipe(array, P.uniqBy(fn))
* @example
* P.uniq(obj => obj.n, [{n: 1}, {n: 2}, {n: 2}, {n: 5}, {n: 1}, {n: 6}, {n: 7}]) // => [{n: 1}, {n: 2}, {n: 5}, {n: 6}, {n: 7}]
* P.pipe(
* [{n: 1}, {n: 2}, {n: 2}, {n: 5}, {n: 1}, {n: 6}, {n: 7}], // only 4 iterations
* P.uniq(obj => obj.n),
* P.take(3)
* ) // => [{n: 1}, {n: 2}, {n: 5}]
* @category Array, Pipe
*/
export function uniqBy<T, K>(
array: readonly T[],
transformer: (item: T) => K
): T[];
export function uniqBy<T, K>(
transformer: (item: T) => K
): (array: readonly T[]) => T[];
export function uniqBy() {
return purry(_uniqBy, arguments, lazyUniqBy);
}
function _uniqBy<T, K>(array: T[], transformer: (item: T) => K) {
return _reduceLazy(array, lazyUniqBy(transformer));
}
function lazyUniqBy(transformer: (item: any) => any) {
const set = new Set<any>();
return (value: any): LazyResult<any> => {
const appliedItem = transformer(value);
if (set.has(appliedItem)) {
return {
done: false,
hasNext: false,
};
}
set.add(appliedItem);
return {
done: false,
hasNext: true,
next: value,
};
};
}
|