0

If I create a custom generator, I can set the value/done as I see fit, but I believe I am going this wrong here using es6 generators as I can't seem to set the value/done as I want. When I set something, it all goes into the "value", but the generator's return "done: false" -- I am trying to force a "done: true"

var A = [
    {id: 1, page: 'page one'},
    {id: 2, page: 'page two'},
    {id: 3, page: 'page three'},
    {id: 4, page: 'page four'},
  ]
function* gen(iteree) {
    let input = yield null
    while(true) 
      input = yield iteree(input) ? iteree(input) : { done: true}
}

// this will be built out more, just showing a 
// passing of a function here
let inter = (a) => { 
       return A[a]
}

let c = gen(inter)
    console.log(c.next())
    console.log(c.next(4)) // <-- **I want this to yield {value: null, done: true}**

but it yields: {value: {done: true}, done: false}

james emanon
  • 11,185
  • 11
  • 56
  • 97

2 Answers2

1

"Forcing done" would be accomplished by return. When in a generator

yield 4;
// {value: 4, done: false}

return 4;
// {value: 4, done: true}
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
1

Here is what I came up with to create the answer you were looking for within your code.

    var A = [
    {id: 1, page: 'page one'},
    {id: 2, page: 'page two'},
    {id: 3, page: 'page three'},
    {id: 4, page: 'page four'},
  ]
function* gen(iteree) {
    let input = yield null
    while(input <= A.length) {
      if(iteree(input)){
        yield iteree(input) 
      }else{
        return null;
      }
   }
}

// this will be built out more, just showing a 
// passing of a function here
let inter = (a) => { 
       return A[a]
}

let c = gen(inter)
console.log(c.next())
console.log(c.next(4))
Aaron Franco
  • 1,560
  • 1
  • 14
  • 19
  • yeah - this is good, and what I ended up doing. Problem I found is once you return "true" the generator becomes dead. I'd like to start it up again, without having to gen a new generator. – james emanon Mar 27 '16 at 22:49
  • You want to iterate the same array again with the same generator? – Aaron Franco Mar 27 '16 at 23:03
  • yeah, the idea is that it is a stepper -- it can go forward or backward (passing into the generator) - I guess that goes against the "essence" of a generator, but it must of a usage beyond lzy eval. – james emanon Mar 27 '16 at 23:06
  • 1
    Maybe this will help for now? http://stackoverflow.com/questions/32444463/es6-reverse-iterate-an-array-using-for-of-have-i-missed-something-in-the-spec – Aaron Franco Mar 27 '16 at 23:09