Skip to content

Instantly share code, notes, and snippets.

@sujinleeme
Created September 3, 2017 03:39
Show Gist options
  • Save sujinleeme/cec64e868711f521839ce6f41865e7b0 to your computer and use it in GitHub Desktop.
Save sujinleeme/cec64e868711f521839ce6f41865e7b0 to your computer and use it in GitHub Desktop.
JavaScript 2D Vector Class
/*
Simple 2D JavaScript Vector Class
Sujin Lee
*/
class Vector {
constructor(v, w) {
this.v = v
this.w = w
this.decimalPlaces = 2
this.sign = {
add : '+',
subtract: '-',
multiply: '*',
division:'/'
}
}
exec(sign) {
this.convertSinCos()
return this.v.map((e, i) => this.round(eval(e + sign + this.w[i])));
}
//add vectors
add() {
return this.exec(this.sign.add)
}
//subtract vectors
sub() {
return this.exec(this.sign.substract)
}
//scale the vector with multiplication
mult() {
return this.exec(this.sign.multiply)
}
// scale the vector with division
div() {
return this.exec(this.sign.division)
}
// calculate the magnitude of a vector
mag() {
}
// normalize the vector to a unit length of 1
normalize() {
}
// limit the magnitude of a vector()
limit() {
}
// the 2D heading of a vector expressed as an angle
heading2D() {
}
// the Euclidean distance between two vectors (considered as points)
dist() {
}
// find the angle between two vectors
angleBetween() {
}
// the dot product of two vectors
dot() {
}
// the cross product of two vectors (only relevant in three dimensions)
cross(){
}
unit() {
const v1 = this.v[0]
const v2 = this.v[1]
const base = 1/Math.sqrt(Math.pow(v1, 2)+Math.pow(v2, 2))
return [base*v1, base*v2]
}
convertSinCos() {
const vectors = [this.v, this.w]
for (let vector of vectors) {
const isDeg = typeof(vector[1])=== 'string' && vector[1].includes("deg")
if (isDeg) {
const magnitude = vector[0]
const dirAngle = vector[1].match(/\d+/g) * (Math.PI / 180);
vector[0] = magnitude * Math.cos(dirAngle)
vector[1] = magnitude * Math.sin(dirAngle)
}
}
this.v = vectors[0]
this.w = vectors[1]
return this
}
round(number) {
const precision = this.decimalPlaces
let pair = (number + 'e').split('e')
let value = Math.round(pair[0] + 'e' + (+pair[1] + precision))
pair = (value + 'e').split('e')
return +(pair[0] + 'e' + (+pair[1] - precision))
}
}
const Test1 = new Vector([8, '290deg'], [6, '60deg'])
console.log(Test1.add()) //[ 5.74, -2.32 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment