Created
October 25, 2013 17:40
-
-
Save bebraw/7158737 to your computer and use it in GitHub Desktop.
Simple, generic Vector thinger for JS. Just basic ops.
This file contains hidden or 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
| var Vec = decorate({ | |
| add: function(a, b) {return a + b;}, | |
| sub: function(a, b) {return a - b;}, | |
| div: function(a, b) {return a / b;}, | |
| mul: function(a, b) {return a * b;} | |
| }, function(op) { | |
| return function() { | |
| var pos = arguments[0].slice(); | |
| var i, len, arg; | |
| for(i = 1, len = arguments.length; i < len; i++) { | |
| arg = arguments[i]; | |
| pos = update(pos, isNumber(arg)? [arg, arg]: arg); | |
| } | |
| return pos; | |
| }; | |
| function update(pos, arg) { | |
| return pos.map(function(v, i) { | |
| return op(v, arg[i]); | |
| }); | |
| } | |
| }); | |
| function decorate(o, fn) { | |
| var ret = {}; | |
| for(var k in o) if(o.hasOwnProperty(k)) ret[k] = fn(o[k]); | |
| return ret; | |
| } | |
| function isNumber(n) { | |
| return !isNaN(parseFloat(n)) && isFinite(n); | |
| } | |
| // demo | |
| var a = Vec.add([1, 2], [1, 2]); | |
| var b = Vec.mul([1, 2], [1, 2]); | |
| var c = Vec.mul([1, 2], 0.5); | |
| var d = Vec.sub([1, 2], [2, 1]); | |
| console.log(a, b, c, d); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment