UNPKG

@tempots/std

Version:

Std library for TypeScript. Natural complement to the Tempo libraries.

398 lines (397 loc) 15 kB
import { Compare, Maybe, Nothing } from './domain'; /** * Returns the first element of an array, or `undefined` if the array is empty. * * @param arr - The input array. * @returns The first element of the array, or `undefined` if the array is empty. * @typeParam A - The type of elements in the array. * @public */ export declare const arrayHead: <A>(arr: A[]) => Maybe<A>; /** * Returns a new array containing all elements of the input array except for the first element. * * @param arr - The input array. * @returns A new array containing all elements of the input array except for the first element. * @public */ export declare const arrayTail: <A>(arr: A[]) => A[]; /** * Checks if two arrays are equal based on a custom equality function. * * @typeParam T - The type of elements in the arrays. * @param a - The first array. * @param b - The second array. * @param equals - The custom equality function to compare elements. * @returns Returns `true` if the arrays are equal, `false` otherwise. * @public */ export declare const areArraysEqual: <T>(a: T[], b: T[], equals: (a: T, b: T) => boolean) => boolean; /** * Checks if an array is empty. * * @param arr - The array to check. * @returns `true` if the array is empty, `false` otherwise. * @public */ export declare const isArrayEmpty: <T>(arr: T[]) => arr is []; /** * Checks if an array has values. * * @param arr - The array to check. * @returns `true` if the array has values, `false` otherwise. * @public */ export declare const arrayHasValues: <T>(arr: T[]) => arr is [T, ...T[]]; /** * Applies a mapping function to each element of an array and returns a new array * containing the mapped values, excluding any `null` or `undefined` values. * * @typeParam A - The type of the elements in the input array. * @typeParam B - The type of the elements in the output array. * @param arr - The input array. * @param f - The mapping function to apply to each element. * @returns The new array containing the mapped values. * @public */ export declare const filterMapArray: <A, B>(arr: A[], f: (a: A, index: number) => Maybe<B>) => B[]; /** * Filters out null and undefined values from an array. * * @typeParam T - The type of elements in the array. * @param arr - The array to filter. * @returns The filtered array. * @public */ export declare const filterNullsFromArray: <T>(arr: Array<T | Nothing>) => T[]; /** * Compares two arrays based on their lengths and element values. * * @typeParam A - The type of elements in the arrays. * @param a - The first array to compare. * @param b - The second array to compare. * @param comparef - The compare function to use for comparing the elements of the arrays. * @param shorterFirst - Specifies whether shorter arrays should be considered smaller. Defaults to true. * @returns A compare function that can be used to compare arrays. * @public */ export declare const compareArrays: <A>(a: A[], b: A[], comparef: Compare<A>, shorterFirst?: boolean) => number; /** * Generates an array of values by applying a function to each index. * * This function provides a more semantic alternative to `Array.from({ length }, (_, i) => f(i))` * with better readability and intent expression. It's particularly useful for creating * arrays with computed values based on their position. * * @example * ```typescript * // Create an array of squares * const squares = buildArray(5, i => i * i) * // Result: [0, 1, 4, 9, 16] * * // Create an array of objects with IDs * const items = buildArray(3, i => ({ id: i, name: `Item ${i}` })) * // Result: [{ id: 0, name: 'Item 0' }, { id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }] * ``` * * @param length - The length of the resulting array. * @param f - The function to apply to each index. It takes the index as a parameter and returns the corresponding value. * @returns An array of values generated by applying the function to each index. * @public */ export declare const buildArray: <A>(length: number, f: (index: number) => A) => A[]; /** * Generates an array of consecutive numbers in a specified range. * * This function provides a more intuitive API than `Array.from({ length }, (_, i) => startAt + i)` * for creating numeric sequences. It's commonly needed for iterations, indexing, and mathematical operations. * * @example * ```typescript * // Create a range from 0 to 4 * const zeroToFour = range(5) * // Result: [0, 1, 2, 3, 4] * * // Create a range from 10 to 14 * const tenToFourteen = range(5, 10) * // Result: [10, 11, 12, 13, 14] * * // Use for creating test data * const testIds = range(100, 1000) * // Result: [1000, 1001, 1002, ..., 1099] * ``` * * @param length - The length of the array to generate. * @param startAt - The starting value of the range. Default is 0. * @returns An array of numbers in the specified range. * @public */ export declare const range: (length: number, startAt?: number) => number[]; /** * Creates a new array with the specified length and fills it with the provided value. * * This function provides a more semantic alternative to `Array(length).fill(value)` or * `new Array(length).fill(value)` with better type inference and clearer intent. * It's particularly useful when you need arrays of non-primitive values or when * working with functional programming patterns. * * @example * ```typescript * // Create an array of default objects * const defaultUsers = fillArray(3, { name: '', active: false }) * // Result: [{ name: '', active: false }, { name: '', active: false }, { name: '', active: false }] * * // Create an array of empty arrays * const matrix = fillArray(3, [] as number[]) * // Result: [[], [], []] * * // Create an array of functions * const handlers = fillArray(5, () => console.log('handler')) * // Result: [function, function, function, function, function] * ``` * * @typeParam A - The type of the elements in the array. * @param length - The length of the new array. * @param value - The value to fill the array with. * @returns A new array filled with the specified value. * @public */ export declare const fillArray: <A>(length: number, value: A) => A[]; /** * Removes duplicate objects from an array based on a key extraction function. * * This function removes duplicates from arrays of objects by extracting a primitive * key from each object and using that key to determine uniqueness. When duplicates * are found, the first occurrence is kept. * * @example * ```typescript * // Remove users with duplicate IDs * const users = [ * { id: 1, name: 'Alice' }, * { id: 2, name: 'Bob' }, * { id: 1, name: 'Alice Clone' }, * { id: 3, name: 'Charlie' } * ] * const uniqueUsers = uniqueByPrimitive(users, user => user.id) * // Result: [ * // { id: 1, name: 'Alice' }, * // { id: 2, name: 'Bob' }, * // { id: 3, name: 'Charlie' } * // ] * ``` * * @example * ```typescript * // Remove products with duplicate names * const products = [ * { name: 'Laptop', price: 1000 }, * { name: 'Mouse', price: 25 }, * { name: 'Laptop', price: 1200 }, * { name: 'Keyboard', price: 75 } * ] * const uniqueProducts = uniqueByPrimitive(products, p => p.name) * // Result: [ * // { name: 'Laptop', price: 1000 }, * // { name: 'Mouse', price: 25 }, * // { name: 'Keyboard', price: 75 } * // ] * ``` * * @example * ```typescript * // Use with complex key extraction * const events = [ * { date: '2023-01-01', type: 'click' }, * { date: '2023-01-01', type: 'hover' }, * { date: '2023-01-01', type: 'click' }, * { date: '2023-01-02', type: 'click' } * ] * const uniqueEvents = uniqueByPrimitive(events, e => `${e.date}-${e.type}`) * // Result: [ * // { date: '2023-01-01', type: 'click' }, * // { date: '2023-01-01', type: 'hover' }, * // { date: '2023-01-02', type: 'click' } * // ] * ``` * * @typeParam T - The type of elements in the input array * @param values - The input array containing objects to deduplicate * @param predicate - Function that extracts a primitive key from each element for comparison * @returns A new array with duplicate elements removed based on the extracted key * @public */ export declare const uniqueByPrimitive: <T>(values: T[], predicate: (a: T) => string | number | symbol) => T[]; /** * Removes the first occurrence of an item from an array. * * @typeParam A - The type of the array elements. * @param arr - The array from which to remove the item. * @param item - The item to remove from the array. * @returns `true` if the item was found and removed, `false` otherwise. * @public */ export declare const removeOneFromArray: <A>(arr: A[], item: A) => boolean; /** * Removes all occurrences of an item from an array. * * @typeParam A - The type of the array elements. * @param arr - The array from which to remove the item. * @param item - The item to remove from the array. * @returns `true` if at least one occurrence was found and removed, `false` otherwise. * @public */ export declare const removeAllFromArray: <A>(arr: A[], item: A) => boolean; /** * Removes the first occurrence in an array that satisfy the given predicate. * * @typeParam A - The type of elements in the array. * @param arr - The array from which elements will be removed. * @param predicate - The predicate function used to determine which elements to remove. * @returns `true` if at least one element was removed, `false` otherwise. * @public */ export declare const removeOneFromArrayByPredicate: <A>(arr: A[], predicate: (a: A) => boolean) => boolean; /** * Removes all occurrences in an array that satisfy the given predicate. * * @typeParam A - The type of elements in the array. * @param arr - The array from which elements will be removed. * @param predicate - The predicate function used to determine which elements to remove. * @returns `true` if at least one element was removed, `false` otherwise. * @public */ export declare const removeAllFromArrayByPredicate: <A>(arr: A[], predicate: (a: A) => boolean) => boolean; /** * Represents the different operations that can be performed on an array. * * @public */ export type ArrayDiffOperations<T> = { removals: Array<{ at: number; qt: number; }>; swaps: Array<{ from: number; to: number; }>; inserts: Array<{ at: number; values: T[]; }>; }; /** * Calculates the difference operations between two arrays based on a key function. * * @typeParam T - The type of elements in the arrays. * @typeParam K - The type of the key used to compare elements. * @param from - The source array. * @param to - The target array. * @param getKey - The key function used to compare elements. * @returns The difference operations between the two arrays. * @public */ export declare const arrayDiffOperations: <T, K>(from: T[], to: T[], getKey: (v: T) => K) => ArrayDiffOperations<T>; /** * Applies a series of operations to an array and returns the modified array. * * @typeParam T - The type of elements in the array. * @param operations - The operations to apply. * @param start - The initial array. * @returns The modified array after applying the operations. * @public */ export declare const applyArrayDiffOperations: <T>(operations: ArrayDiffOperations<T>, start: T[]) => T[]; /** * Joins an array of values into a string using a conjunction and separator. * * @param arr - The array of values to join. * @param conjunction - The conjunction to use between the second-to-last and last value. Default is ' and '. * @param separator - The separator to use between each value. Default is ', '. * @returns The joined string. * @public */ export declare const joinArrayWithConjunction: <A>(arr: A[], conjunction?: string, separator?: string) => string; /** * Assigns ranks to the elements in the array based on the provided compare function. * The ranks are assigned in ascending order, with the lowest value receiving a rank of 0. * If there are duplicate values, the rank of the duplicates can be incremented or not based on the `incrementDuplicates` parameter. * * @typeParam T - The type of elements in the array. * @param array - The array to rank. * @param compare - The compare function used to determine the order of elements. * @param incrementDuplicates - Whether to increment the rank of duplicate values. * @returns An array of ranks corresponding to the elements in the input array. * @public */ export declare const rankArray: <T>(array: T[], compare: (a: T, b: T) => number, incrementDuplicates?: boolean) => number[]; /** * Splits an array into chunks of the specified size. * * This function divides an array into smaller arrays of a fixed size. * The last chunk may contain fewer elements if the array length is not * evenly divisible by the chunk size. * * @example * ```typescript * const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] * const chunks = chunk(numbers, 3) * // Result: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] * * const uneven = chunk([1, 2, 3, 4, 5], 2) * // Result: [[1, 2], [3, 4], [5]] * ``` * * @param array - The array to chunk * @param size - The size of each chunk (must be positive) * @returns An array of chunks * @public */ export declare const chunk: <T>(array: readonly T[], size: number) => T[][]; /** * Partitions an array into two arrays based on a predicate. * * This function splits an array into two parts: elements that satisfy * the predicate and elements that don't. The order of elements is preserved. * * @example * ```typescript * const numbers = [1, 2, 3, 4, 5, 6] * const [evens, odds] = partition(numbers, n => n % 2 === 0) * // evens: [2, 4, 6] * // odds: [1, 3, 5] * ``` * * @param array - The array to partition * @param predicate - Function that tests each element * @returns A tuple containing [matching elements, non-matching elements] * @public */ export declare const partition: <T>(array: readonly T[], predicate: (item: T) => boolean) => [T[], T[]]; /** * Groups array elements by a key function. * * This function creates an object where keys are the result of the key function * and values are arrays of elements that produced that key. * * @example * ```typescript * const users = [ * { name: 'Alice', department: 'Engineering' }, * { name: 'Bob', department: 'Engineering' }, * { name: 'Carol', department: 'Marketing' } * ] * const byDepartment = groupBy(users, user => user.department) * // Result: { * // Engineering: [{ name: 'Alice', ... }, { name: 'Bob', ... }], * // Marketing: [{ name: 'Carol', ... }] * // } * ``` * * @param array - The array to group * @param keyFn - Function that extracts the grouping key from each element * @returns An object with grouped elements * @public */ export declare const groupBy: <T, K extends string | number | symbol>(array: readonly T[], keyFn: (item: T) => K) => Record<K, T[]>;