Skip to content

Instantly share code, notes, and snippets.

@meodai
Last active June 14, 2023 11:50
Show Gist options
  • Save meodai/8b1476a4aad0f603408d4a973d1efb58 to your computer and use it in GitHub Desktop.
Save meodai/8b1476a4aad0f603408d4a973d1efb58 to your computer and use it in GitHub Desktop.
vectorScale
// function that scales an array of vectors to a given length and interpolates between the the vectors
// to create a smooth path
// input: array of vectors
// output: array of vectors
export type Vector = number[];
export function vectorScale(vectors: Vector[], length: number): Vector[] {
const result: Vector[] = [];
if (vectors.length === 0) {
return result;
}
const numVectors = vectors.length;
const segmentLength = length / (numVectors - 1);
for (let i = 0; i < numVectors - 1; i++) {
const currentVector = vectors[i];
const nextVector = vectors[i + 1];
const segmentVector: Vector = [];
for (let j = 0; j < currentVector.length; j++) {
const currentComponent = currentVector[j];
const nextComponent = nextVector[j];
const interpolatedComponent =
currentComponent +
((nextComponent - currentComponent) * segmentLength) / vectorLength(
currentVector,
nextVector
);
segmentVector.push(interpolatedComponent);
}
result.push(segmentVector);
}
result.push(vectors[numVectors - 1]);
return result;
}
// Helper function to calculate the length of a vector
function vectorLength(v1: Vector, v2: Vector): number {
let sum = 0;
for (let i = 0; i < v1.length; i++) {
const diff = v2[i] - v1[i];
sum += diff * diff;
}
return Math.sqrt(sum);
}
console.log(vectorScale([[1, 2], [3, 4], [5, 6]], 10));
console.log(vectorScale([[0, 1], [1, 0], [0, 2]], 5));
console.log(vectorScale([[0, 1], [1, 0], [0, 2]], 7));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment