UNPKG

super-utils-plus

Version:

A superior alternative to Lodash with improved performance, TypeScript support, and developer experience

85 lines (84 loc) 2.16 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.uniq = uniq; exports.uniqDeep = uniqDeep; exports.uniqBy = uniqBy; const is_1 = require("../utils/is"); /** * Creates a duplicate-free version of an array, using SameValueZero for equality comparisons. * * @param array - The array to inspect * @returns The new duplicate-free array * * @example * ```ts * uniq([2, 1, 2]); * // => [2, 1] * ``` */ function uniq(array) { if (!array || !array.length) { return []; } return [...new Set(array)]; } /** * Creates a duplicate-free version of an array using deep equality comparisons. * * @param array - The array to inspect * @returns The new duplicate-free array * * @example * ```ts * uniqDeep([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }]); * // => [{ 'x': 1 }, { 'x': 2 }] * ``` */ function uniqDeep(array) { if (!array || !array.length) { return []; } const result = []; for (const item of array) { // Only add if not already in result using deep equality if (!result.some(resultItem => (0, is_1.isEqual)(resultItem, item))) { result.push(item); } } return result; } /** * Creates a duplicate-free version of an array using a custom iteratee function. * * @param array - The array to inspect * @param iteratee - The function invoked per element or property name * @returns The new duplicate-free array * * @example * ```ts * uniqBy([2.1, 1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] * ``` */ function uniqBy(array, iteratee) { if (!array || !array.length) { return []; } const iterateeFn = typeof iteratee === 'function' ? iteratee : (obj) => obj[iteratee]; const result = []; const seen = new Set(); for (const item of array) { const transformed = iterateeFn(item); // Check if we've seen this transformed value before if (!seen.has(transformed)) { seen.add(transformed); result.push(item); } } return result; }