UNPKG

typedash

Version:

modern, type-safe collection of utility functions

35 lines (33 loc) 1.4 kB
//#region src/functions/unique/unique.ts /** * Returns an array containing only the unique elements of the input iterable. * @note The order of the elements in the input matters, the first occurrence of an element (per the `comparator`) is the one that will be kept. * @param iterable The input iterable to extract unique elements from. * @param comparator An optional function that takes two elements and returns a boolean indicating whether they are equal. Defaults to the `Object.is` function. * @returns An array containing only the unique elements of the input iterable. * @example * unique([1, 2, 3, 2, 1, 4, 5, 4, 3]); // [1, 2, 3, 4, 5] * unique(['a', 'b', 'c', 'b', 'a']); // ['a', 'b', 'c'] * unique([ * { id: 1, name: 'Alice' }, * { id: 2, name: 'Bob' }, * { id: 1, name: 'Alice', age: 42 }, * ], * (a, b) => a.id === b.id * ) // [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }] */ function unique(iterable, comparator = defaultComparator) { if (comparator === defaultComparator) return [...new Set(iterable)]; const result = []; for (const value of iterable ?? []) if (!result.some((other) => comparator(value, other))) result.push(value); return result; } const defaultComparator = Object.is; //#endregion Object.defineProperty(exports, 'unique', { enumerable: true, get: function () { return unique; } }); //# sourceMappingURL=unique-DwG6IZ4p.cjs.map