Created
April 18, 2016 11:11
-
-
Save amodig/255c58f9b920b600beac84cdbf95f059 to your computer and use it in GitHub Desktop.
JS sequence interface with inheritance example
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
function ArraySeq(array) { | |
this.array = array; | |
} | |
ArraySeq.prototype.current = function() { | |
return this.array[0]; | |
} | |
ArraySeq.prototype.remaining = function() { | |
if (this.array[1]) { | |
return new ArraySeq(this.array.slice([1])); | |
} | |
else return false; | |
} | |
function RangeSeq(begin, end) { | |
var array = []; | |
for (var i = begin; i <= end; i++) { | |
array.push(i); | |
} | |
ArraySeq.call(this, array); | |
} | |
RangeSeq.prototype = Object.create(ArraySeq.prototype); | |
function logFive(sequence) { | |
var i = 0; | |
var tempSeq = sequence; | |
while (tempSeq && i < 5) { | |
console.log(tempSeq.current()); | |
tempSeq = tempSeq.remaining(); | |
i++; | |
} | |
} | |
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