infinnie / infinnie.github.io

https://infinnie.github.io/
Apache License 2.0
0 stars 1 forks source link

JavaScript: Emulating the LINQ operators’ behavior #9

Open infinnie opened 7 years ago

infinnie commented 7 years ago
var Where = function (arr, g) {
    return {
        [Symbol.iterator]: function*() {
            var x;
            for (x of arr) {
                if (g(x)) {
                    yield x;
                }
            }
        }
    };
};

var arr = [0, 1, 2, 3, 4];
var iterable = Where(arr, function (x) {
    return x % 2 === 0;
});

for (let t of iterable) {
    console.log(t);
} // 0, 2, 4

arr[0] = 1;

for (let t of iterable) {
    console.log(t);
} // only 2 & 4: 0 is gone now