import { ensureArray } from './guards.ts' /** * Creates sort callback which can be used for `array.sort` input. * A custom key function can be supplied to customize the sort order. * Key can return any nested data structure, supports number, booleans, arrays. * * @example * ``` * // Sort by object key * arr.sort(sortByCb(v => v.myKey)) * // Sort by number in reversed order * arr.sort(sortByCb(v => v.numberKey * -1)) * // Sort by object key, then by boolean value in revered order * arr.sort(sortByCb(v => [v.myKey, !v.boolValue]) * ``` * @group Array * @param key a function to execute to decide the order * @returns `array.sort` compatible callback */ export function sortByCb( key: (item: T) => unknown = (v) => v, ): (a: T, b: T) => number { return (a, b) => { const doCompare = (keyA: unknown, keyB: unknown): number => { if (typeof keyA === 'number' && typeof keyB === 'number') { return keyA < keyB ? -1 : keyA > keyB ? 1 : 0 } if (typeof keyA === 'boolean' && typeof keyB === 'boolean') { return keyA < keyB ? -1 : keyA > keyB ? 1 : 0 } if (keyA instanceof Date && keyB instanceof Date) { return doCompare(keyA.getTime(), keyB.getTime()) } if (Array.isArray(keyA) && Array.isArray(keyB)) { const res = keyA .map((v, i) => doCompare(v, keyB[i])) .filter((v) => v !== 0) return res[0] ?? 1 } const stringA = String(keyA) const stringB = String(keyB) return stringA < stringB ? -1 : stringA > stringB ? 1 : 0 } return doCompare(key(a), key(b)) } } /** * Stable sort using provided callback without modifications. * A custom key function can be supplied to customize the sort order. * Key can return any nested data structure, supports number, booleans, arrays, objects. * * @example * ``` * // Sort by object key * sortBy(arr, v => v.myKey)) * // Sort by number in reversed order * sortBy(arr, v => v.numberKey * -1)) * // Sort by object key, then by boolean value in revered order * sortBy(arr, v => [v.myKey, !v.boolValue]) * ``` * @group Array * @param arr any array * @param key a function to execute to decide the order * @returns sorted array copy */ export function sortBy(arr: T[], key?: (item: T) => unknown): T[] export function sortBy( arr: readonly T[], key?: (item: T) => unknown, ): readonly T[] export function sortBy( arr: ReadonlyArray, key: (item: T) => unknown = (v) => v, ): T[] { return arr .map((v, i) => [v, i] as const) .sort(sortByCb(([v, i]) => [key(v), i])) .map((v) => v[0]) } /** * Return an object that produces a array of numbers from start (inclusive) to stop (exclusive) by step. * * @example * ``` * >>> generateRange(4) * [0, 1, 2, 3] * >>> generateRange(3,6) * [3, 4, 5] * >>> generateRange(0,10,2) * [0, 2, 4, 6, 8] * >>> generateRange(10,0,-1) * [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] * >>> generateRange(8,2,-2) * [8, 6, 4] * ``` * @group Array * @param stop an integer number specifying at which position to stop (not included) * @returns generated array by range */ export function generateRange(stop: number): number[] /** * Return an object that produces a array of numbers from start (inclusive) to stop (exclusive) by step. * * @example * ``` * >>> generateRange(4) * [0, 1, 2, 3] * >>> generateRange(3,6) * [3, 4, 5] * >>> generateRange(0,10,2) * [0, 2, 4, 6, 8] * >>> generateRange(10,0,-1) * [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] * >>> generateRange(8,2,-2) * [8, 6, 4] * ``` * @group Array * @param start an integer number specifying at which position to start * @param stop an integer number specifying at which position to stop (not included) * @param step an integer number specifying the incrementation * @returns generated array by range */ export function generateRange( start: number, stop: number, step?: number, ): number[] export function generateRange( start: number, stop?: number, step?: number, ): number[] { if (stop === undefined) { stop = start start = 0 } if (step === undefined) { step = 1 } if (step === 0) { throw new RangeError('generateRange step must not be 0') } if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) { return [] } const result = [] for (let i = start; step > 0 ? i < stop : i > stop; i += step) { result.push(i) } return result } type FlatArray = { done: Arr recur: Arr extends ReadonlyArray ? FlatArray< InnerArr, [ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ][Depth] > : Arr }[Depth extends -1 ? 'done' : 'recur'] /** * Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth. * * Use [Array.flat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) if possible or polyfill globally: * * ``` * Array.prototype.flat = function(depth) { * return flatten(this, depth) * } * ``` * * @example * ``` * flatten([1, 2, [3, 4]]) * // [1, 2, 3, 4] * * flatten([1, 2, [3, 4, [5, 6]]]) * // [1, 2, 3, 4, [5, 6]] * * flatten([1, 2, [3, 4, [5, 6]]], 2) * // [1, 2, 3, 4, 5, 6] * ``` * @group Array * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat * @param depth The maximum recursion depth */ export function flatten( array: A, depth?: D, ): FlatArray[] export function flatten( array: A, depth?: D, ): readonly FlatArray[] export function flatten( array: A, depth?: D, ): FlatArray[] { const d = depth ?? 1 if (d > 0) { return array.reduce( (acc, val) => acc.concat(Array.isArray(val) ? flatten(val, d - 1) : val), [], ) as FlatArray[] } return array.slice() as FlatArray[] } /** * Splits an array into groups the length of size. If array can't be split evenly, the final chunk will be the remaining elements. * * @example * ``` * chunk([1, 2, 3, 4, 5], 2) * // [[1, 2], [3, 4], [5]] * ``` * @param size Chunk maximum size * @group Array */ export function chunk(array: T[], size: number): T[][] export function chunk( array: readonly T[], size: number, ): readonly (readonly T[])[] export function chunk(array: ReadonlyArray, size: number): T[][] { if (size < 1 || !Number.isInteger(size)) { throw new RangeError('chunk size must be a positive integer') } return array.reduce((acc, _, i) => { if (i % size === 0) { acc.push(array.slice(i, i + size)) } return acc }, [] as T[][]) } /** * Groups an array's items into `[key, values]` entries, keyed by the * callback's return value. * * Internally backed by a `Map` keyed on the raw callback value, so: * * - Object/array keys use identity (two equal-but-different object instances * are distinct groups). For value equality, return a primitive key. * - Functions, symbols, and circular references work (no `JSON.stringify`). * - Entries are returned in first-seen order. * * @example * ``` * groupBy([6.1, 4.2, 6.3], Math.floor) * // [ [6, [6.1, 6.3]], [4, [4.2]] ] * ``` * @group Array */ export function groupBy( array: T[], keyCallback: (value: T) => G, ): [G, T[]][] export function groupBy( array: readonly T[], keyCallback: (value: T) => G, ): readonly [G, readonly T[]][] export function groupBy( array: ReadonlyArray, keyCallback: (value: T) => G, ): [G, T[]][] { const groups = new Map() for (const item of array) { const key = keyCallback(item) const existing = groups.get(key) if (existing) { existing.push(item) } else { groups.set(key, [item]) } } return [...groups] } /** * Creates indexed object by provided callback. * * If array is returned, creates a separate index for each array element. * * @example * ``` * indexBy(['one', 'two', 'three'], v => v.length) * // { '5': ['three'], '3': ['one', 'two'] } * * indexBy(['one', 'two', 'three'], v => [v.length, v.length + 1]) * // { '5': ['three'], '6': ['three'], '3': ['one', 'two'], '4': ['one', 'two'] } * ``` * @group Array */ export function indexBy( array: T[], keyCallback: (value: T) => string | number | ReadonlyArray, ): Record export function indexBy( array: readonly T[], keyCallback: (value: T) => string | number | ReadonlyArray, ): Record export function indexBy( array: ReadonlyArray, keyCallback: (value: T) => string | number | ReadonlyArray, ): Record { return array.reduce( (acc, cur) => ensureArray(keyCallback(cur)).reduce((acc2, key) => { const existing = acc2[key] if (existing) { existing.push(cur) } else { acc2[key] = [cur] } return acc2 }, acc), {} as Record, ) } /** * Removes duplicate values from the array. * * @example * ``` * deduplicate([1, 1, 2, 3, 3]) * // [1, 2, 3] * ``` * @group Array */ export function deduplicate(array: T[]): T[] export function deduplicate(array: readonly T[]): readonly T[] export function deduplicate(array: ReadonlyArray): T[] { return deduplicateBy(array as T[], (v) => v) } /** * Removes duplicate values from the array by given callback. * * @example * ``` * deduplicateBy([ { a: 1 }, { a: 1 } ], v => v.a) * // [ { a: 1 } ] * ``` * @group Array */ export function deduplicateBy(array: T[], key: (value: T) => unknown): T[] export function deduplicateBy( array: readonly T[], key: (value: T) => unknown, ): readonly T[] export function deduplicateBy( array: ReadonlyArray, key: (value: T) => unknown, ): T[] { const prims = { boolean: {} as Record, number: {} as Record, string: {} as Record, } type Prim = keyof typeof prims const objs: unknown[] = [] return array.filter((rawItem) => { const item = key(rawItem) as string | number | symbol const type = typeof item if (type in prims) { if (item in prims[type as Prim]) return false prims[type as Prim][item] = true return true } if (objs.indexOf(item) !== -1) return false objs.push(item) return true }) } /** * Creates an array of array values not included in the other given arrays. * * @example * ``` * difference([2, 1], [2, 3]) * // [1] * * difference([2, 1], ['2', '3'], (a, b) => a === parseInt(b)) * // [1] * ``` * @group Array */ export function difference( array: T[], values: ReadonlyArray, key?: (value: T | T2) => unknown, ): T[] export function difference( array: readonly T[], values: ReadonlyArray, key?: (value: T | T2) => unknown, ): readonly T[] export function difference( array: ReadonlyArray, values: ReadonlyArray, key: (value: T | T2) => unknown = (v) => v, ): T[] { return array.filter((v) => !values.some((v2) => key(v) === key(v2))) } /** * Creates an array of unique values that are included in all given arrays. * * @example * ``` * intersection([[2, 1], [2, 3]]) * // [2] * ``` * @group Array */ export function intersection(values: T[][], key?: (value: T) => unknown): T[] export function intersection( values: ReadonlyArray>, key?: (value: T) => unknown, ): readonly T[] export function intersection( values: ReadonlyArray>, key: (value: T) => unknown = (v) => v, ): T[] { const [first, ...rest] = values return first ? first.filter((v) => rest.every((v2) => v2.some((v3) => key(v) === key(v3))), ) : [] } /** * Creates an array of unique values that are included in all given arrays. * * @example * ``` * intersection([[2, 1], [2, 3]]) * // [2] * ``` * @group Array */ export function union(values: T[][], key?: (value: T) => unknown): T[] export function union( values: ReadonlyArray>, key?: (value: T) => unknown, ): readonly T[] export function union( values: ReadonlyArray>, key: (value: T) => unknown = (v) => v, ): T[] { return deduplicateBy( values.reduce((prev, cur) => { prev.push(...cur) return prev }, []), key, ) } /** * Checks if any value from provided values array is included in the provided array using provided `comparator` function (or by default comparing using `===`). * * @example * ``` * includesAny([1, 2, 3], [3, 4, 5]) * // true * ``` * @group Array */ export function includesAny( array: ReadonlyArray, values: ReadonlyArray, key: (value: T | T2) => unknown = (v) => v, ): boolean { return values.some((v) => array.some((v2) => key(v2) === key(v))) } /** * Checks if all values from provided values array are included in the provided array using provided `comparator` function (or by default comparing using `===`). * * @example * ``` * includesAll([1, 2, 3], [1, 2]) * // true * ``` * @group Array */ export function includesAll( array: ReadonlyArray, values: ReadonlyArray, key: (value: T | T2) => unknown = (v) => v, ): boolean { return values.every((v) => array.some((v2) => key(v2) === key(v))) } /** * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * * @example * ``` * const obj = [{name: 'abc'}] * const index = findIndex(obj, v => v.name = 'abc') * // 0 * ``` * @param compare find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @group Array */ export function findIndex( array: ReadonlyArray, compare: (value: T) => boolean, ): number { for (let index = 0; index < array.length; index++) { if (compare(array[index] as T)) { return index } } return -1 } /** * Returns a new array with `null` and `undefined` values removed. * * The element type is narrowed via `NonNullable`. Other falsy values * (`0`, `''`, `false`, `NaN`) are preserved — use `array.filter(Boolean)` * or a custom predicate if you want full falsy removal. * * @example * ``` * compact([1, null, 2, undefined, 3]) * // [1, 2, 3] * ``` * @group Array */ export function compact(array: ReadonlyArray): NonNullable[] { return array.filter((v): v is NonNullable => v != null) } /** * Counts the number of items grouped by the callback's return value. * * Internally backed by a `Map` keyed on the raw callback value — same * identity semantics as [[groupBy]]. * * @example * ``` * countBy(['apple', 'banana', 'avocado'], v => v[0]) * // [ ['a', 2], ['b', 1] ] * ``` * @group Array */ export function countBy( array: ReadonlyArray, keyCallback: (value: T) => G, ): [G, number][] { const counts = new Map() for (const item of array) { const key = keyCallback(item) counts.set(key, (counts.get(key) ?? 0) + 1) } return [...counts] }