UNPKG

ts-data-forge

Version:

[![npm version](https://img.shields.io/npm/v/ts-data-forge.svg)](https://www.npmjs.com/package/ts-data-forge) [![npm downloads](https://img.shields.io/npm/dm/ts-data-forge.svg)](https://www.npmjs.com/package/ts-data-forge) [![License](https://img.shields.

123 lines (120 loc) 2.7 kB
import { range as range$1 } from '../../iterator/range.mjs'; /** * Creates an array of zeros with the specified length. * * @example * * ```ts * const emptyZeros = Arr.zeros(0); * * const threeZeros = Arr.zeros(3); * * assert.deepStrictEqual(emptyZeros, []); * * assert.deepStrictEqual(threeZeros, [0, 0, 0]); * ``` */ const zeros = (len) => // eslint-disable-next-line total-functions/no-unsafe-type-assertion Array.from({ length: len }).fill(0); /** * Creates a sequence of consecutive integers from 0 to `len-1`. * * @example * * ```ts * const emptySeq = Arr.seq(0); * * const firstFive = Arr.seq(5); * * assert.deepStrictEqual(emptySeq, []); * * assert.deepStrictEqual(firstFive, [0, 1, 2, 3, 4]); * ``` */ const seq = (len) => // eslint-disable-next-line total-functions/no-unsafe-type-assertion Array.from({ length: len }, (_, i) => i); /** * Creates a new array of the specified length, filled with the initial value. * * @example * * ```ts * const threeOnes = Arr.create(3, 1); * * const emptyStrings = Arr.create(0, 'Ada'); * * assert.deepStrictEqual(threeOnes, [1, 1, 1]); * * assert.deepStrictEqual(emptyStrings, []); * ``` */ const create = (len, init) => // eslint-disable-next-line total-functions/no-unsafe-type-assertion Array.from({ length: Math.max(0, len) }, () => init); /** * Alias for `create`. * * @see {@link create} */ const newArray = create; /** * Generates an array from a generator function. * * @example * * ```ts * const numbers = Arr.generate(function* () { * yield 1; * * yield 2; * * yield 3; * }); * * assert.deepStrictEqual(numbers, [1, 2, 3]); * ``` */ const generate = (generatorFn) => Array.from(generatorFn()); /** * Generates an array from an async generator function. * * @example * * ```ts * const values = await Arr.generateAsync(async function* () { * yield 'Ada'; * * await Promise.resolve(); * * yield 'Lovelace'; * }); * * assert.deepStrictEqual(values, ['Ada', 'Lovelace']); * ``` */ const generateAsync = (generatorFn) => Array.fromAsync(generatorFn()); /** * Creates a shallow copy of an array. * * @example * * ```ts * const original = [{ id: 1 }, { id: 2 }] as const; * * const cloned = Arr.copy(original); * * assert.deepStrictEqual(cloned, original); * * assert.notStrictEqual(cloned, original); * ``` */ const copy = (array) => // eslint-disable-next-line total-functions/no-unsafe-type-assertion array.slice(); function range(start, end, step = 1) { return Array.from(range$1(start, end, step)); } export { copy, create, generate, generateAsync, newArray, range, seq, zeros }; //# sourceMappingURL=array-utils-creation.mjs.map