I tried to filter out the generator and expected that such universal functionality should be defined anywhere in JavaScript, because it is defined for arrays, but I cannot find it. So I tried to determine this. But I can not expand the built-in generators.
I have an example generator
function make_nums ()
{
let nums = {};
nums[Symbol.iterator] = function* () {
yield 1;
yield 2;
yield 3;
};
return nums;
}
generating some numbers.
[...make_nums()]
If I create an array, I can filter the array using the function filterfor arrays.
[...make_nums()].filter(n => n > 1)
But I do not want to build an array. Instead, I want to take an old generator and build a new filter generator. For this, I wrote the following function.
function filtered (generator, filter)
{
let g = {};
g[Symbol.iterator] = function* () {
for (let value of generator)
if (filter(value))
yield value;
};
return g;
}
which can be used to accomplish what I want.
[...filtered (make_nums(), n => n > 1)]
, , filter Array. , , .
MDN , Generator.prototype , , , . - Generator.prototype,
ReferenceError:
Generator?