typedash
Version:
modern, type-safe collection of utility functions
29 lines (28 loc) • 1.31 kB
JavaScript
//#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
export { unique as t };
//# sourceMappingURL=unique-BY4IH2wk.js.map