1

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!

1
  • 1
    several syntax errors pop out... Commented Nov 3, 2016 at 20:14

1 Answer 1

3

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]);

Sign up to request clarification or add additional context in comments.

1 Comment

Great, and if I would want to add a switch statement, to yield some other thing depending on the number I am getting from the array? (I edited the question to show more details about this)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.