1. 程式人生 > >JS-Javascript 迭代器設計模式 Iterator pattern

JS-Javascript 迭代器設計模式 Iterator pattern

這篇博文簡短的提一下Iterator的設計模式,以及這種設計模式給我們帶來什麼樣的好處。

1.begin

為了體現面向物件的特性(近年來的ES6為這方面做了很大的努力),此篇博文的語言編寫基於typescript,當然也會附上原生js的書寫方式。

1.1迭代器給我們帶來了什麼樣的好處

迭代器可以使我們快速的遍歷一個序列物件,一個良好的迭代器使我們不用瞭解該序列底層的結構,而只用關心拿到值之後的處理,並且迭代器是相當輕量的,對於建立一個迭代器,它的程式碼開銷是非常小的。

1.2自己實現一個簡單的js迭代器

在這裡我們稱為iterator設計模式,該設計模式就是為了建立一個簡單的迭代器,當然時間有限,這裡創建出來的迭代器以傳入陣列為基礎進行迭代。

Typescript

interface MyIteratorInterface<T>{
    hasNext():boolean,
    next():T
}

class MyIterator<T> implements MyIteratorInterface<T>{
    //陣列指標
    pointer:number = 0;
    //步長
    step:number;
    //陣列物件
    arr:Array<T>;

    constructor(arr:Array<T>,step?:number){
        this
.arr = arr; this.step = step || 1; } hasNext(){ if(this.arr[this.pointer + this.step]){ return true; } return false; } next(){ while(this.pointer <= this.arr.length){ if(this.pointer++ % this.step == 0){ return
this.arr[this.pointer - 1]; } } } } let arr:number[] = [1,1,23,2,42,3,52,3,72,3]; let myIterator:MyIterator<number> = new MyIterator<number>(arr,3); console.log(`next is ${myIterator.next()} and hasNext is ${myIterator.hasNext()}`); console.log(`next is ${myIterator.next()} and hasNext is ${myIterator.hasNext()}`); console.log(`next is ${myIterator.next()} and hasNext is ${myIterator.hasNext()}`); console.log(`next is ${myIterator.next()} and hasNext is ${myIterator.hasNext()}`); console.log(`next is ${myIterator.next()} and hasNext is ${myIterator.hasNext()}`); console.log(`next is ${myIterator.next()} and hasNext is ${myIterator.hasNext()}`); console.log(`next is ${myIterator.next()} and hasNext is ${myIterator.hasNext()}`); console.log(`next is ${myIterator.next()} and hasNext is ${myIterator.hasNext()}`);

執行結果如下:
這裡寫圖片描述

Javascript

//迭代器物件
let Iterator = function(arr,step){
    if(!arr || !step){
        throw new Error("arr and step is necessary");
    }
    //需要迭代的物件
    this.arr = arr;
    //當前迭代的指標
    this.cursor = 0;
    //迭代的步長
    this.step = step;
}

Iterator.prototype = {
    //獲得下一個元素
    next:function(){
        while(this.cursor < this.arr.length){
            if(this.cursor++ % this.step == 0){
                return this.arr[this.cursor - 1];
            }
        }
    },
    //是否還有下一個元素
    hasNext:function(){
        let tempCursor = this.cursor;
        while(tempCursor < this.arr.length){
            if(tempCursor++ % this.step == 0){
                return true;
            }
        }
        return false;
    }
};

let it = new Iterator([1,2,42,3,52,3,2,4],2);
console.log(it.next(),it.hasNext());
console.log(it.next(),it.hasNext());
console.log(it.next(),it.hasNext());