Skip to content

Instantly share code, notes, and snippets.

@jeanbza
Created November 7, 2014 05:05
Show Gist options
  • Save jeanbza/bb9528da330909c5867d to your computer and use it in GitHub Desktop.
Save jeanbza/bb9528da330909c5867d to your computer and use it in GitHub Desktop.
Vector javascript kata
// http://www.codewars.com/kata/vector-class/train/javascript
var Vector = function(a) {
return {
get: function(key) {
return a[key];
},
getAll: function() {
return a;
},
checkSize: function(b) {
if (a.length != b.getAll().length) {
throw 'Size mismatch: '+a+' '+b.getAll();
}
},
negate: function() {
var c = [];
a.forEach(function(val) {
c.push(-val);
});
return new Vector(c);
},
add: function(b) {
this.checkSize(b);
var c = [];
a.forEach(function(val, key) {
c.push(val+b.get(key));
});
return c;
},
subtract: function(b) {
return this.add(b.negate());
},
dot: function(b) {
this.checkSize(b);
var c = 0;
a.forEach(function(val, key) {
c += val*b.get(key);
});
return c;
},
norm: function() {
var c = 0;
a.forEach(function(val) {
c += Math.pow(val, 2);
});
return Math.sqrt(c);
},
toString: function() {
return '('+a.join(',')+')';
},
equals: function(b) {
return res = a.every(function(val, key) {
return val == b.get(key);
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment