Skip to content

Instantly share code, notes, and snippets.

@cmstead
Last active February 24, 2016 04:57
Show Gist options
  • Select an option

  • Save cmstead/504184633bf0d5b402ff to your computer and use it in GitHub Desktop.

Select an option

Save cmstead/504184633bf0d5b402ff to your computer and use it in GitHub Desktop.
Vector type for Javascript -- built for discussion on types and functions in Javascript
(function () {
'use strict';
function Vector() {
Vector.attachPoints(this, arguments);
}
// Inherted behaviors
Vector.prototype = {
getValues: function (result, index) {
var point = this[index];
var pointExists = typeof point !== 'undefined';
return pointExists ? this.getValues(Vector.pushPoint(result, point), index + 1) : result;
},
// Overrides Object.prototype.toString
toString: function () {
return '<' + this.valueOf().join(',') + '>';
},
// Overrides Object.prototype.valueOf
valueOf: function () {
return this.getValues([], 0);
}
};
// Static functions
Vector.build = function buildVector(point1, point2) {
var vector = new Vector();
return Vector.attachPoints(vector, arguments);
};
Vector.attachPoints = function attachPoints(vector, args) {
var points = Array.prototype.slice.call(args);
points.reduce(Vector.attachPoint, vector);
return vector;
};
Vector.attachPoint = function attachPoint(vector, point, index) {
vector[index] = point;
vector.length = index + 1;
return vector;
};
Vector.pushPoint = function pushPoint(result, point) {
result.push(point);
return result;
}
return Vector;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment