JSで複数個ずつ配列から取り出す。

かなり小さなtipsで悩んでしまった昨今。こんな小さなことで日々悩んでいるのだけど、自戒を込めて。

もっと綺麗に書けるかな...。うーん。

n個のコレクションをm個ずつ取り出す。あー。while使ってsliceのindexを加算してくほうが素直で綺麗か。

code

var __iterator = function (collection, howMany) {
    var count = 0;
    var __next = function() {
        var index = howMany * count;
        var result = collection.slice(index, index + howMany);
        count += 1;
        return result;
    };
    var __hasNext = function() {
        var index = howMany * count;
        return collection.slice(index, index + howMany).length > 0;
    };
    return {next: __next, hasNext: __hasNext};
};

var iter = __iterator([0,1,2,3,4,5,6,7,8,9], 3);
while(iter.hasNext()) {
    console.log(iter.next());
}

output

[ 0, 1, 2 ]
[ 3, 4, 5 ]
[ 6, 7, 8 ]
[ 9 ]