Created
October 9, 2014 18:25
-
-
Save Shiggiddie/20194bc8a9151e1dbdca to your computer and use it in GitHub Desktop.
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
// A Vector Type | |
function Vector(x, y){ | |
this.x = x; | |
this.y = y; | |
}; | |
Vector.prototype.plus = function(other_vector) { | |
return new Vector(this.x + other_vector.x, this.y + other_vector.y); | |
}; | |
Vector.prototype.minus = function(other_vector) { | |
return new Vector(this.x - other_vector.x, this.y - other_vector.y); | |
}; | |
Object.defineProperty(Vector.prototype, "length", { get:function() { | |
return Math.sqrt(this.x * this.x + this.y * this.y); } | |
}); | |
console.log(new Vector(1,2)); | |
console.log(new Vector(1, 2).plus(new Vector(2, 3))); | |
// → Vector{x: 3, y: 5} | |
console.log(new Vector(1, 2).minus(new Vector(2, 3))); | |
// → Vector{x: -1, y: -1} | |
console.log(new Vector(3, 4).length); | |
// → 5 | |
// Another Cell | |
function StretchCell(inner, width, height) { | |
this.inner = inner; | |
this.width = width; | |
this.height = height; | |
} | |
StretchCell.prototype.minWidth = function() { | |
return Math.max(this.inner.minWidth(), this.width); | |
} | |
StretchCell.prototype.minHeight = function() { | |
return Math.max(this.inner.minHeight(), this.height); | |
} | |
StretchCell.prototype.draw = function(width, height) { | |
return this.inner.draw(width, height); | |
} | |
var sc = new StretchCell(new TextCell("abc"), 1, 2); | |
console.log(sc.minWidth()); | |
// → 3 | |
console.log(sc.minHeight()); | |
// → 2 | |
console.log(sc.draw(3, 2)); | |
// → ["abc", " "] | |
// Sequence Interface | |
function ArraySeq(array) { | |
this.array = array; | |
this.pos = -1; | |
} | |
Object.defineProperty(ArraySeq.prototype, "continue", { get:function() { | |
if (this.pos < this.array.length) { | |
this.pos++; | |
return true; | |
} | |
return false; | |
}}); | |
Object.defineProperty(ArraySeq.prototype, "next", { get:function() { | |
return this.array[this.pos]; | |
}}); | |
function RangeSeq(from, to) { | |
this.from = from-1; | |
this.to = to; | |
} | |
Object.defineProperty(RangeSeq.prototype, "continue", { get:function() { | |
if (this.from < this.to) { | |
this.from++; | |
return true; | |
} | |
return false; | |
}}); | |
Object.defineProperty(RangeSeq.prototype, "next", { get:function() { | |
return this.from; | |
}}); | |
function logFive(seq) { | |
for (var i = 0; i < 5 && seq.continue; i++) { | |
console.log(seq.next); | |
} | |
} | |
logFive(new ArraySeq([1, 2])); | |
// → 1 | |
// → 2 | |
logFive(new RangeSeq(100, 1000)); | |
// → 100 | |
// → 101 | |
// → 102 | |
// → 103 | |
// → 104 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment