Skip to content

Commit

Permalink
better attr names for scaleSpread array fn
Browse files Browse the repository at this point in the history
  • Loading branch information
meodai committed May 2, 2024
1 parent a88ac93 commit da924d5
Showing 1 changed file with 21 additions and 10 deletions.
31 changes: 21 additions & 10 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,33 +259,44 @@ export const lerp: FillFunction<number> = (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 = <T>(
initial: T[],
valuesToFill: T[],
targetSize: number,
fillFunction: FillFunction<T> = lerp as unknown as FillFunction<T>
): 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[];
Expand Down

0 comments on commit da924d5

Please sign in to comment.