💾Iterator

extending built-in iterable iterators with methods map(), filter() ...

JSiterationiterator ⟩ Iterator (extension)

(deprecated , use Iterable+ext instead)

extending built-in iterable iterators with methods map(), filter() ...

// --------------------
//     ⭐ Iterator
// --------------------
// 🧨 雷區:
// • must use function declaration. (can't use class declaration)
// • the prototype of a class is unwritable❗
function Iterator() {}            // function declaration

// ⭐ reassign/overwrite prototype❗️ 
// • prototype of all built-in (iterable) iterators
Iterator.prototype = Object.getPrototypeOf(     // IteratorPrototype
    Object.getPrototypeOf(                      // ArrayIteratorPrototype
        [][Symbol.iterator]()                   // Array iterator
    )
);

// ⭐ extending `Iterator.prototype`
// ---------------------------------
// - 🔸 .filter()     -> generator
// - 🔸 .map()        -> generator
// - 🔸 .take()       -> generator
//
// - 🔸 .every()      -> boolean
// - 🔸 .some()       -> boolean
// - 🔸 .toArray()    -> array
// - 🔸 .forEach()    -> (returns `undefined`)

// 🔸 .filter()
Iterator.prototype.filter = function*(condition) {
    for (const value of this) {
        if (condition(value)) yield value;
    }
};

// 🔸 .map()
Iterator.prototype.map = function*(f) {
    for (const value of this) { yield f(value) }
};

// 🔸 .take()
// turn "infinite" iterator into "finite"
Iterator.prototype.take = function*(n) {
    for (const value of this) {
        if (n > 0) {
            n -= 1;
            yield value;
        } else { return }
    }
};

// 🔸 .forEach()
Iterator.prototype.forEach = function(handle) {
    for (const value of this) { handle(value) }
};

// 🔸 .every()
Iterator.prototype.every = function(condition) {
    for (const value of this) { if (!condition(value)) return false }
    return true;
};

// 🔸 .some()
Iterator.prototype.some = function(condition) {
    for (const value of this) { if (condition(value)) return true }
    return false;
};

// 🔸 .toArray()
Iterator.prototype.toArray = function() {
    return [...this];
};

// ⭐️ export
module.exports = Iterator;

Last updated