Last active
September 22, 2017 08:46
-
-
Save sujinleeme/60fb97553d634b0ea1350c228aa319d8 to your computer and use it in GitHub Desktop.
Simple 2D Vector Operation Class
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
/** | |
Simple 2D Vector Operation calculator Class using Javascript | |
Blog Post : https://www.sujinlee.me/blog/vector-basics/ | |
*/ | |
class Vector { | |
constructor(v, w) { | |
this.u = v | |
this.w = w | |
this.decimalPlaces = 2 | |
this.sign = { | |
add: '+', | |
subtract: '-' | |
} | |
} | |
// scale vectors | |
scale(num) { | |
return this.u.map((e, i) => e * num) | |
} | |
// add vectors | |
add() { | |
return this.exec(this.sign.add) | |
} | |
// subtract vectors | |
sub() { | |
return this.exec(this.sign.subtract) | |
} | |
// scale the vector with multiplication | |
mult() { | |
return this.exec(this.sign.multiply) | |
} | |
// calculate sign | |
exec(sign) { | |
return this.u.map((e, i) => eval( | |
e + sign + '(' + this.w[i] + ')' | |
)) | |
} | |
// magnitude of a vector | |
magnitude(v) { | |
return Math.sqrt(Math.pow(v[0], 2) + Math.pow(v[1], 2)) | |
} | |
// vector magnitude from initial & terminal points | |
segmentMagnitude() { | |
return this.round(this.magnitude(this.sub())) | |
} | |
// round N decimal numbers | |
round(num) { | |
const precision = this.decimalPlaces | |
return +(Math.round(num + "e+" + precision) + "e-" + precision); | |
} | |
} | |
// test | |
const VectorInstance = new Vector([1, 1], [5, 3]) | |
const magVector1 = VectorInstance.segmentMagnitude() | |
console.log(magVector1) // 4.47 | |
VectorInstance.decimalPlaces = 5 | |
const magVector2 = VectorInstance.segmentMagnitude() | |
console.log(magVector2) // 4.47214 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment