2016年9月10日土曜日

開発環境

Eloquent JavaScript(Marijn Haverbeke 著、No Starch Press)のPart 1(Language)、Chapter 6(The Secret Life of Objects)、Exercises(Sequence Interface)を取り組んでみる。

Exercises(Sequence Interface)

コード(Emacs)

'use strict';
var ArraySeq,
    RangeSeq,
    ary0 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    ary1 = [1,2],
    ary_seq0,
    ary_seq1,
    range_seq0,
    range_seq1,
    elem;

ArraySeq = function (array) {
    this.array = array;
    this.cur = 0;
};
ArraySeq.prototype = Object.create(Array.prototype);
ArraySeq.prototype.logFive = function () {
    var i,
        max = Math.min(this.array.length, 5);

    for (i = 0; i < max; i += 1) {
        console.log(this.array[i]);
    }
};
ArraySeq.prototype.next = function () {
    var elem = this.array[this.cur];

    this.cur += 1;
    return elem;
};
ary_seq0 = new ArraySeq(ary0);
ary_seq1 = new ArraySeq(ary1);

ary_seq0.logFive();
console.log();
ary_seq1.logFive();
console.log();

RangeSeq = function (from, to) {
    var ary = [],
        i;

    for (i = from; i < to; i += 1) {
        ary.push(i);
    }
    ArraySeq.call(this, ary);
};
RangeSeq.prototype = Object.create(ArraySeq.prototype);
range_seq0 = new RangeSeq(1, 10);
range_seq1 = new RangeSeq(10, 1);

range_seq0.logFive();
console.log();
range_seq1.logFive();
console.log();

for (elem = range_seq0.next(); elem !== undefined;
     elem = range_seq0.next()) {
    console.log(elem);
}
console.log();
for (elem = range_seq1.next(); elem !== undefined;
     elem = range_seq1.next()) {
    console.log(elem);
}
console.log();

入出力結果(Terminal, Node.js)

$ node sample3.js
1
2
3
4
5

1
2

1
2
3
4
5


1
2
3
4
5
6
7
8
9


$

0 コメント:

コメントを投稿

Comments on Google+: