JS design patterns first met (four) - iterator pattern

definition

Iterative mode refers to provide a method for accessing a sequential polymerization of the respective elements of the object, but does not require the internal representation of the object is exposed. Iterative mode iterative process can be separated from the business logic, after iterative mode, i.e., the internal configuration of the iterative mode is not the object of interest, wherein each element can be accessed sequentially.

4.1 custom iterator each

    function each(arr, callback=()=>{}) {
        if (!Array.isArray(arr)) {
            return throw new Error('传入的第一个参数不是数组');
        }
        for (let i=0;i<arr.length;i++) {
            callback(arr[i], i, arr);
        }
    }
    each([1,2,3], function(item, index, array) {
        // console.log('item, index => ',item, index, array);
    });
复制代码

4.2 external iterator iterator

    function Iterator(obj) {
        const current = 0;
        const next = () => {
            current++;
        }
        const isDone = () => {
            return current >= obj.length;
        }  
        const getItem = () => {
            return obj[current];
        }
        return {
            next: next,
            isDone: isDone,
            getItem: getItem,
        }          
    }

    function compare(a, b) {
        while(!a.isDone() && !b.isDone()) {
            if (a.getItem() !== b.getItem()) {
                throw new Error('iterator1 和 iterator2 不相等');
            }
            a.next();
            b.next();
        }
        console.log('iterator1 和 iterator2 相等')
    }

    const iterator1 = Iterator([1,2,3]);
    const iterator2 = Iterator([1,2,3]);
    compare(iterator1, iterator2);
复制代码

4.3 ES6 Iterator iterator

Pending

to sum up

Iterator pattern is a relatively simple model, simple to very often we do not think it is a design pattern. Currently the vast majority of languages ​​have built-in iterators.

Reproduced in: https: //juejin.im/post/5cfd31fd518825728262a4f0

Guess you like

Origin blog.csdn.net/weixin_34090562/article/details/91473280