in packages/utilities/fast-colors/src/color-palette.ts [268:318]
export function rescale(
input: ColorRGBA64[],
targetSize: number,
preserveInputColors: boolean
): ColorRGBA64[] {
if (input.length <= 1 || targetSize <= 1) {
throw new Error("The input array and targetSize must both be greater than 1");
}
if (preserveInputColors && targetSize <= input.length) {
throw new Error(
"If preserveInputColors is true then targetSize must be greater than the length of the input array"
);
}
const stops: ColorScaleStop[] = new Array(input.length);
if (preserveInputColors) {
for (let i: number = 0; i < input.length; i++) {
const p: number = i / (input.length - 1);
let bestFitValue: number = 2;
let bestFitIndex: number = 0;
for (let j: number = 0; j < targetSize; j++) {
const fitValue: number = Math.abs(j / (targetSize - 1) - p);
if (fitValue < bestFitValue) {
bestFitValue = fitValue;
bestFitIndex = j;
}
if (fitValue === 0) {
break;
}
}
stops[i] = {
color: input[i],
position: bestFitIndex / (targetSize - 1),
};
}
} else {
for (let i: number = 0; i < stops.length; i++) {
stops[i] = { color: input[i], position: i / (input.length - 1) };
}
}
const scale: ColorScale = new ColorScale(stops);
const retVal: ColorRGBA64[] = new Array(targetSize);
for (let i: number = 0; i < targetSize; i++) {
retVal[i] = scale.getColor(i / (targetSize - 1));
}
return retVal;
}