雄辩的 Javascript 练习 6.3 - 序列接口

Eloquent Javascript Exercise 6.3 - Sequence Interface

本文关键字:接口 Javascript 练习      更新时间:2023-09-26

我刚从Web开发训练营毕业,目前正在研究Eloquent Javascript。在这次演习之前,事情进展得相当顺利。有人可以为我分解吗?我不确定为什么每个序列的起始位置都设置为"-1"。

问题来了:设计一个对值集合进行抽象迭代的接口。提供此接口的对象表示一个序列,并且该接口必须以某种方式使使用此类对象的代码能够遍历序列,查看它所组成的元素值,并有某种方法来找出何时到达序列的末尾。

指定接口后,尝试编写一个函数 logFive,该函数采用序列对象并调用控制台.log在其前五个元素上 - 如果序列的元素少于五个,则更少。

然后实现一个对象类型 ArraySeq,该对象类型包装数组并允许使用您设计的接口对数组进行迭代。实现另一个对象类型 RangeSeq,它遍历一系列整数(从参数到其构造函数

)。

和解决方案:

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

该位置最初设置为 -1 以允许您编写如下代码:

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

在具有从 0 开始的数组(如 JavaScript)的语言中,0指向第一项,因此您需要一些其他值,以防数组为空,而-1恰好是一个方便的值。

那是因为RangeSeq.prototype.next将使用不能产生0this.pos += 1;