From da924d5c54fd8442d498734094125a67cf1aa229 Mon Sep 17 00:00:00 2001 From: David Aerne Date: Thu, 2 May 2024 23:49:06 +0200 Subject: [PATCH] better attr names for scaleSpread array fn --- src/index.ts | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/src/index.ts b/src/index.ts index 75ee8e5..e999cd5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -259,33 +259,44 @@ export const lerp: FillFunction = (amt, from, to) => /** * Scales and spreads an array to the target size using interpolation. * - * @param {Array} initial - The initial array of values. + * This function takes an initial array of values, a target size, and an + * interpolation function (defaults to `lerp`). It returns a scaled and spread + * version of the initial array to the target size using the specified + * interpolation function. + * The initial entries are spread as evenly as possible across the target size + * and the gaps are filled with interpolated values using the specified. + * + * @param {Array} valuesToFill - The initial array of values. * @param {number} targetSize - The desired size of the resulting array. * @param {function} fillFunction - The interpolation function (default is lerp). * @returns {Array} The scaled and spread array. * @throws {Error} If the initial array is empty or target size is invalid. */ export const scaleSpreadArray = ( - initial: T[], + valuesToFill: T[], targetSize: number, fillFunction: FillFunction = lerp as unknown as FillFunction ): T[] => { - if (initial.length === 0) { - throw new Error("Initial array must not be empty."); + // Check that the valuesToFill array is not empty and that the target size is valid + if (!valuesToFill || valuesToFill.length < 2) { + throw new Error("valuesToFill array must have at least two values."); } - if (targetSize < initial.length) { + if (targetSize < valuesToFill.length) { throw new Error( - "Target size must be greater than or equal to the initial array length." + "Target size must be greater than or equal to the valuesToFill array length." ); } - - const valuesToAdd = targetSize - initial.length; - const chunkArray = initial.map((value) => [value]); + // Create a copy of the valuesToFill array and add null values to it if necessary + const valuesToAdd = targetSize - valuesToFill.length; + const chunkArray = valuesToFill.map((value) => [value]); for (let i = 0; i < valuesToAdd; i++) { - (chunkArray[i % (initial.length - 1)] as T[]).push(null as unknown as T); + (chunkArray[i % (valuesToFill.length - 1)] as T[]).push( + null as unknown as T + ); } + // Fill each chunk with interpolated values using the specified interpolation function for (let i = 0; i < chunkArray.length - 1; i++) { const currentChunk = chunkArray[i] as T[]; const nextChunk = chunkArray[i + 1] as T[];