daily-toolset
Version:
A lightweight, versatile collection of TypeScript utility functions for everyday development needs. Simplify and streamline your Node.js, React, and Next.js projects with a powerful suite of well-organized helpers for strings, arrays, dates, objects, and
83 lines (80 loc) • 2.63 kB
TypeScript
/**
* Returns a new array with all duplicate elements removed.
*
* The function takes an array as an argument and returns a new array that contains
* only unique elements from the input array. The order of elements is preserved.
*
* @example
* uniqueArray([1, 2, 3, 2, 1]) // [1, 2, 3]
*
* @param {T[]} arr - The input array containing elements to be de-duplicated.
* @returns {T[]} A new array containing only unique elements from the input array.
* @throws {Error} Throws an error if the input is not an array.
*/
export declare function uniqueArray<T>(arr: T[]): T[];
type UniqueArrayByKeyParams<T> = {
array: T[] | null | undefined;
key: keyof T;
};
/**
* Returns a new array with all duplicate elements removed, based on the specified key.
*
* The function takes an array of objects and a key as arguments. It returns a new array that contains
* only one instance of each object, based on the specified key. If the key is not found in the object,
* the object is skipped.
*
* @example
* const array = [
* { id: 1, name: 'John' },
* { id: 2, name: 'Jane' },
* { id: 1, name: 'John' },
* ];
* const result = uniqueArrayByKey(array, 'id');
* console.log(result);
* // Output: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]
*/
export declare function uniqueArrayByKey<T>({ array, key, }: UniqueArrayByKeyParams<T>): T[];
type ArrayChunkParams<T> = {
array: T[];
size: number;
};
/**
* Chunks an array into smaller arrays of the specified size.
*
* @example
* chunk({ arr: [1, 2, 3, 4, 5], size: 2 }) // [[1, 2], [3, 4], [5]]
*/
export declare function chunk<T>({ array, size }: ArrayChunkParams<T>): T[][];
/**
* Flattens an array of arrays into a single array.
*
* @example
* flatten([[1, 2], [3, 4]]) // [1, 2, 3, 4]
*/
export declare function flatten<T>(arr: any[]): T[];
/**
* Shuffles an array in place.
*
* This function takes an array as an argument and returns the same array, but
* with its elements in a random order. The original array is modified.
*
* @example
* shuffleArray([1, 2, 3])
* // Output: [2, 3, 1] or [3, 1, 2] or [1, 3, 2], etc.
*/
export declare function shuffleArray<T>(array: T[]): T[];
/**
* Groups an array of objects by the specified key.
*
* @example
* const input = [
* { id: 1, category: 'a' },
* { id: 2, category: 'a' },
* { id: 3, category: 'b' },
* ];
*
* const result = groupBy(input, 'category');
* // result will be { a: [{ id: 1 }, { id: 2 }], b: [{ id: 3 }] }
*/
export declare function groupBy<T extends Record<string, any>, K extends keyof T>(array: T[], key: K): Record<T[K], T[]>;
export {};