RealMagoj RealMagoj - 4 months ago 40
Javascript Question

Eloquent Javascript Exercise 6.3 - Sequence Interface

I'm a recent graduate of a web dev bootcamp and currently working my way through Eloquent Javascript. Things were movin pretty smoothly prior to this exercise. Can somebody break this down for me? I'm not sure why the starting position is set to "-1" for each sequence.

Here's the question:
Design an interface that abstracts iteration over a collection of values. An object that provides this interface represents a sequence, and the interface must somehow make it possible for code that uses such an object to iterate over the sequence, looking at the element values it is made up of and having some way to find out when the end of the sequence is reached.

When you have specified your interface, try to write a function logFive that takes a sequence object and calls console.log on its first five elements—or fewer, if the sequence has fewer than five elements.

Then implement an object type ArraySeq that wraps an array and allows iteration over the array using the interface you designed. Implement another object type RangeSeq that iterates over a range of integers (taking from and to arguments to its constructor) instead.

and the solution:

function logFive(sequence) {
for (var i = 0; i < 5; i += 1) {
if (!sequence.next()) {
break;
}
console.log(sequence.current());
}
}
function ArraySeq(array) {
this.pos = -1;
this.array = array;
}
ArraySeq.prototype.next = function() {
if (this.pos >= this.array.length - 1) {
return false;
}
this.pos += 1;
return true;
}
ArraySeq.prototype.current = function() {
return this.array[this.pos];
}
function RangeSeq(from, to) {
this.pos = from - 1;
this.to = to;
}
RangeSeq.prototype.next = function() {
if (this.pos >= this.to) {
return false;
}
this.pos += 1;
return true;
}
RangeSeq.prototype.current = function() {
return this.pos;
}

logFive(new ArraySeq([1, 2]));
// → 1
// → 2
logFive(new RangeSeq(100, 1000));
// → 100
// → 101
// → 102
// → 103
// → 104

Answer

The position is initially set to -1 to allow you to write code like this:

while (iter.next())
   console.log(iter.current());

In languages that have 0-based arrays like JavaScript, 0 points to the first item so you need some other value in case the array is empty, and -1 happens to be a convenient one.