Nicolas Nicolas - 1 month ago 6
Javascript Question

Construct generator function from array

I am trying to build a generator function from an array. The simplest example would be:

const array = [1,2,3,4]

function * createGenerator () {
array.map(function(elem){
yield elem
}
}


And I would expect:

function * createGenerator () {
yield 1
yield 2
yield 3
yield 4
}


Also if I want to add a switch statement like this:

function processServerActions (array) {
for (let elem in array) {
switch(elem) {
case 1:
yield 1111
case 2:
yield 22222
case 3:
yield 333333
yield 444444
case 4:
yield 55555
}
}

}


But is not working. What am I missing?

Thanks!

Answer

The callback can only return the callback. For yielding the generator function, the yield has to be inside of the function, but outside of a nested callback.

Better you use for ... of for yielding a value.

function* createGenerator() {
    for (let elem of array){
        yield elem;
    }
}  

const array = [1,2,3,4],
      c = createGenerator();

console.log([...c]);

You need for (let elem of array) with of instead of in.

function* createGenerator() {
    for (let elem of array) {
        switch(elem) {
            case 1:
                yield 1111;
                break;
            case 2:
                yield 22222;
                break;
            case 3:
                yield 333333;
                yield 444444;
                break;
            case 4:
                yield 55555;
        }
    }
}

const array = [1,2,3,4],
      c = createGenerator();

console.log([...c]);