Last active
July 5, 2018 07:58
-
-
Save jamesseanwright/ac7a230a38d67494ab3145b7fc5137f5 to your computer and use it in GitHub Desktop.
Manipulating Vectors of Numbers in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const getVectorSize = vector => Math.sqrt( | |
vector.map(n => Math.pow(n, 2)) | |
.reduce((total, n) => total + n, 0) | |
); | |
const addVectors = (a, b) => a.map((number, i) => number + b[i]); | |
const multiplyVectors = (a, b) => a.map((number, i) => number * b[i]); | |
const multiplyVector = (vector, operand) => ( | |
vector.map(number => number * operand) | |
); | |
const getDotProduct = (a, b) => a.reduce((result, number, i) => ( | |
result + (number * b[i]) | |
), 0); | |
const getScalarProjection = (a, b) => ( | |
getDotProduct(a, b) / getVectorSize(a) | |
); | |
const getVectorProjection = (aVector, bVector) => ( | |
aVector.map( | |
a => getScalarProjection(aVector, bVector) * (a / getVectorSize(aVector)) | |
) | |
); | |
// assumes basis vectors are orthogonal | |
const getFromBasis = (vector, ...basisVectors) => ( | |
basisVectors.map(basisVector => ( | |
getDotProduct(vector, basisVector) / (getVectorSize(basisVector) ** 2) | |
)) | |
); | |
const getCos = (a, b) => ( | |
getDotProduct(a, b) / (getVectorSize(a) * getVectorSize(b)) | |
); | |
// [1.2, -1.6, 0] | |
console.log(getVectorProjection([3, -4, 0], [10, 5, -6])); | |
// 0 | |
console.log(getCos([2, 1], [-2, 4])); | |
// [1, 0, 1, 1] | |
console.log( | |
getFromBasis( | |
[1, 1, 2, 3], | |
[1, 0, 0, 0], | |
[0, 2, -1, 0], | |
[0, 1, 0, 0], | |
[0, 0, 0, 3] | |
) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment