SyntaxError: Unexpected Identifier (Generators in ES6)

前端 未结 2 1582
说谎
说谎 2020-12-01 13:03

I came up with this simple experiment after reading the documentation on generators from MDN:

var nodes = {
    type: \'root\',
    value: [
        { type: \         


        
2条回答
  •  青春惊慌失措
    2020-12-01 13:50

    Summarizing the comments: you can't use yield inside a regular function, so you can't use yield with forEach. Here an example of "generatorized" foreach:

    function * foreach (arr, fn) {
      var i
    
      for (i = 0; i < arr.length; i++) {
        yield * fn(arr[i])
      }
    }
    
    function * gen (number) {
      yield number + 1
      yield number + 2
      yield number + 3
    }
    
    function * other () {
      yield * foreach([1, 2, 3], gen)
    }
    
    for (var i of other()) {
        console.log(i)
    }
    

    UPDATE Also the original problem can be solved quite elegantly using such a helper:

    var nodes = {
      type: 'root',
      value: [
        { type: 'char', value: 'a' },
        { type: 'char', value: 'b' },
        { type: 'root', value: [
            { type: 'char', value: 'c' },
            { type: 'char', value: 'd' },
            { type: 'char', value: 'e' },
          ] 
        },
      ],
    }
    
    function * foreach (arr, fn) {
      var i
    
      for (i = 0; i < arr.length; i++) {
        yield * fn(arr[i])
      }
    }
    
    function * value (val) {
      yield val
    }
    
    function * recursiveGenerator(node) {
      yield * node.type === 'root' ?  foreach(node.value, recursiveGenerator) : value(node.value)
    }
    
    for (var generated of recursiveGenerator(nodes)) {
      console.log(generated);
    }
    

    So the generator itself becomes a one-liner!

提交回复
热议问题