Skip to content

Instantly share code, notes, and snippets.

@amodig
Created April 18, 2016 11:11
Show Gist options
  • Save amodig/255c58f9b920b600beac84cdbf95f059 to your computer and use it in GitHub Desktop.
Save amodig/255c58f9b920b600beac84cdbf95f059 to your computer and use it in GitHub Desktop.
JS sequence interface with inheritance example
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