Making an Iterator with ES6












0















This question has a lot of moving parts, but I'm going to start with the my first miscomprehension.



Context: An Iterator is defined as an Object that implements a next() method, which both of my examples down below have. The difference is that I'm creating an Object with a next() method differently. In my first example, I'm creating a function that returns an Object that contains a next() method. I then assign a variable to this function, so if I'm not mistaken, I am essentially making an Object on the fly with a predefined function.



var letters = ["a","b","c"];

function createIterator(array) {
var i = 0;

return { //return an Object with a next() method
next: function(){
i < array.length ? //if statement
{value: array[i++], done: false}:
{value: undefined, done: true};
}
}
}

var myIterator = createIterator(letters);
console.log(myIterator.next()) //{value: a, done: false}
console.log(myIterator.next()) //{value: b, done: false}
console.log(myIterator.next()) //{value: c, done: false}
console.log(myIterator.next()) //{value: undefined, done: true}


So, by putting the createIterator function inside a variable, myIterator, each time I run the next() function, I get the next element in the array I pass.



Okay, I thought. What if I just made the Object without the function?



var literal = {
letters: ["a", "b", "c"],
next: function(){ //same next function as before
var i = 0;
i < this.letters.length ?
{value: this.letters[i++], done: false}:
{value: undefined, done: true};
}
}

console.log(literal.next()) //{value: a, done: false}
console.log(literal.next()) //{value: a, done: false}
console.log(literal.next()) //{value: a, done: false}
console.log(literal.next()) //{value: a, done: false}


I think this is due to my misunderstanding of how I'm invoking the next() method with different ways of creating my Objects. It could be something with scope, but I'm really not entirely sure.










share|improve this question

























  • What's with that var i = 0l in the first snippet? Is this the actual code?

    – Bergi
    Nov 21 '18 at 22:13






  • 1





    Your problem appears to be that you moved the var i declaration from an outer scope into the next function, where it now is initialised to 0 on every call. Instead of being incremented as you expect.

    – Bergi
    Nov 21 '18 at 22:14
















0















This question has a lot of moving parts, but I'm going to start with the my first miscomprehension.



Context: An Iterator is defined as an Object that implements a next() method, which both of my examples down below have. The difference is that I'm creating an Object with a next() method differently. In my first example, I'm creating a function that returns an Object that contains a next() method. I then assign a variable to this function, so if I'm not mistaken, I am essentially making an Object on the fly with a predefined function.



var letters = ["a","b","c"];

function createIterator(array) {
var i = 0;

return { //return an Object with a next() method
next: function(){
i < array.length ? //if statement
{value: array[i++], done: false}:
{value: undefined, done: true};
}
}
}

var myIterator = createIterator(letters);
console.log(myIterator.next()) //{value: a, done: false}
console.log(myIterator.next()) //{value: b, done: false}
console.log(myIterator.next()) //{value: c, done: false}
console.log(myIterator.next()) //{value: undefined, done: true}


So, by putting the createIterator function inside a variable, myIterator, each time I run the next() function, I get the next element in the array I pass.



Okay, I thought. What if I just made the Object without the function?



var literal = {
letters: ["a", "b", "c"],
next: function(){ //same next function as before
var i = 0;
i < this.letters.length ?
{value: this.letters[i++], done: false}:
{value: undefined, done: true};
}
}

console.log(literal.next()) //{value: a, done: false}
console.log(literal.next()) //{value: a, done: false}
console.log(literal.next()) //{value: a, done: false}
console.log(literal.next()) //{value: a, done: false}


I think this is due to my misunderstanding of how I'm invoking the next() method with different ways of creating my Objects. It could be something with scope, but I'm really not entirely sure.










share|improve this question

























  • What's with that var i = 0l in the first snippet? Is this the actual code?

    – Bergi
    Nov 21 '18 at 22:13






  • 1





    Your problem appears to be that you moved the var i declaration from an outer scope into the next function, where it now is initialised to 0 on every call. Instead of being incremented as you expect.

    – Bergi
    Nov 21 '18 at 22:14














0












0








0








This question has a lot of moving parts, but I'm going to start with the my first miscomprehension.



Context: An Iterator is defined as an Object that implements a next() method, which both of my examples down below have. The difference is that I'm creating an Object with a next() method differently. In my first example, I'm creating a function that returns an Object that contains a next() method. I then assign a variable to this function, so if I'm not mistaken, I am essentially making an Object on the fly with a predefined function.



var letters = ["a","b","c"];

function createIterator(array) {
var i = 0;

return { //return an Object with a next() method
next: function(){
i < array.length ? //if statement
{value: array[i++], done: false}:
{value: undefined, done: true};
}
}
}

var myIterator = createIterator(letters);
console.log(myIterator.next()) //{value: a, done: false}
console.log(myIterator.next()) //{value: b, done: false}
console.log(myIterator.next()) //{value: c, done: false}
console.log(myIterator.next()) //{value: undefined, done: true}


So, by putting the createIterator function inside a variable, myIterator, each time I run the next() function, I get the next element in the array I pass.



Okay, I thought. What if I just made the Object without the function?



var literal = {
letters: ["a", "b", "c"],
next: function(){ //same next function as before
var i = 0;
i < this.letters.length ?
{value: this.letters[i++], done: false}:
{value: undefined, done: true};
}
}

console.log(literal.next()) //{value: a, done: false}
console.log(literal.next()) //{value: a, done: false}
console.log(literal.next()) //{value: a, done: false}
console.log(literal.next()) //{value: a, done: false}


I think this is due to my misunderstanding of how I'm invoking the next() method with different ways of creating my Objects. It could be something with scope, but I'm really not entirely sure.










share|improve this question
















This question has a lot of moving parts, but I'm going to start with the my first miscomprehension.



Context: An Iterator is defined as an Object that implements a next() method, which both of my examples down below have. The difference is that I'm creating an Object with a next() method differently. In my first example, I'm creating a function that returns an Object that contains a next() method. I then assign a variable to this function, so if I'm not mistaken, I am essentially making an Object on the fly with a predefined function.



var letters = ["a","b","c"];

function createIterator(array) {
var i = 0;

return { //return an Object with a next() method
next: function(){
i < array.length ? //if statement
{value: array[i++], done: false}:
{value: undefined, done: true};
}
}
}

var myIterator = createIterator(letters);
console.log(myIterator.next()) //{value: a, done: false}
console.log(myIterator.next()) //{value: b, done: false}
console.log(myIterator.next()) //{value: c, done: false}
console.log(myIterator.next()) //{value: undefined, done: true}


So, by putting the createIterator function inside a variable, myIterator, each time I run the next() function, I get the next element in the array I pass.



Okay, I thought. What if I just made the Object without the function?



var literal = {
letters: ["a", "b", "c"],
next: function(){ //same next function as before
var i = 0;
i < this.letters.length ?
{value: this.letters[i++], done: false}:
{value: undefined, done: true};
}
}

console.log(literal.next()) //{value: a, done: false}
console.log(literal.next()) //{value: a, done: false}
console.log(literal.next()) //{value: a, done: false}
console.log(literal.next()) //{value: a, done: false}


I think this is due to my misunderstanding of how I'm invoking the next() method with different ways of creating my Objects. It could be something with scope, but I'm really not entirely sure.







javascript javascript-objects






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 22:16







brnn

















asked Nov 21 '18 at 22:07









brnnbrnn

175




175













  • What's with that var i = 0l in the first snippet? Is this the actual code?

    – Bergi
    Nov 21 '18 at 22:13






  • 1





    Your problem appears to be that you moved the var i declaration from an outer scope into the next function, where it now is initialised to 0 on every call. Instead of being incremented as you expect.

    – Bergi
    Nov 21 '18 at 22:14



















  • What's with that var i = 0l in the first snippet? Is this the actual code?

    – Bergi
    Nov 21 '18 at 22:13






  • 1





    Your problem appears to be that you moved the var i declaration from an outer scope into the next function, where it now is initialised to 0 on every call. Instead of being incremented as you expect.

    – Bergi
    Nov 21 '18 at 22:14

















What's with that var i = 0l in the first snippet? Is this the actual code?

– Bergi
Nov 21 '18 at 22:13





What's with that var i = 0l in the first snippet? Is this the actual code?

– Bergi
Nov 21 '18 at 22:13




1




1





Your problem appears to be that you moved the var i declaration from an outer scope into the next function, where it now is initialised to 0 on every call. Instead of being incremented as you expect.

– Bergi
Nov 21 '18 at 22:14





Your problem appears to be that you moved the var i declaration from an outer scope into the next function, where it now is initialised to 0 on every call. Instead of being incremented as you expect.

– Bergi
Nov 21 '18 at 22:14












1 Answer
1






active

oldest

votes


















1














In the first example i is captured in a closure so it works. In the second example i gets created new every time you call the function. You could make is a property of the object:






var literal = {
letters: ["a", "b", "c"],
i: 0,
next: function(){ //same next function as before
return this.i < this.letters.length ?
{value: this.letters[this.i++], done: false}:
{value: undefined, done: true};
}
}

console.log(literal.next())
console.log(literal.next())
console.log(literal.next())
console.log(literal.next())





Of course you can also implement this in a way that it will work as an iterator in other contexts and is simpler:






var G = {
letters: ["a", "b", "c"],
[Symbol.iterator]: function*(){
yield *this.letters
}
}

// now the object works as an iterable:
console.log([...G])
// or
let iter = G[Symbol.iterator]()
console.log(iter.next())
console.log(iter.next())
console.log(iter.next())
console.log(iter.next())








share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53421122%2fmaking-an-iterator-with-es6%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    In the first example i is captured in a closure so it works. In the second example i gets created new every time you call the function. You could make is a property of the object:






    var literal = {
    letters: ["a", "b", "c"],
    i: 0,
    next: function(){ //same next function as before
    return this.i < this.letters.length ?
    {value: this.letters[this.i++], done: false}:
    {value: undefined, done: true};
    }
    }

    console.log(literal.next())
    console.log(literal.next())
    console.log(literal.next())
    console.log(literal.next())





    Of course you can also implement this in a way that it will work as an iterator in other contexts and is simpler:






    var G = {
    letters: ["a", "b", "c"],
    [Symbol.iterator]: function*(){
    yield *this.letters
    }
    }

    // now the object works as an iterable:
    console.log([...G])
    // or
    let iter = G[Symbol.iterator]()
    console.log(iter.next())
    console.log(iter.next())
    console.log(iter.next())
    console.log(iter.next())








    share|improve this answer






























      1














      In the first example i is captured in a closure so it works. In the second example i gets created new every time you call the function. You could make is a property of the object:






      var literal = {
      letters: ["a", "b", "c"],
      i: 0,
      next: function(){ //same next function as before
      return this.i < this.letters.length ?
      {value: this.letters[this.i++], done: false}:
      {value: undefined, done: true};
      }
      }

      console.log(literal.next())
      console.log(literal.next())
      console.log(literal.next())
      console.log(literal.next())





      Of course you can also implement this in a way that it will work as an iterator in other contexts and is simpler:






      var G = {
      letters: ["a", "b", "c"],
      [Symbol.iterator]: function*(){
      yield *this.letters
      }
      }

      // now the object works as an iterable:
      console.log([...G])
      // or
      let iter = G[Symbol.iterator]()
      console.log(iter.next())
      console.log(iter.next())
      console.log(iter.next())
      console.log(iter.next())








      share|improve this answer




























        1












        1








        1







        In the first example i is captured in a closure so it works. In the second example i gets created new every time you call the function. You could make is a property of the object:






        var literal = {
        letters: ["a", "b", "c"],
        i: 0,
        next: function(){ //same next function as before
        return this.i < this.letters.length ?
        {value: this.letters[this.i++], done: false}:
        {value: undefined, done: true};
        }
        }

        console.log(literal.next())
        console.log(literal.next())
        console.log(literal.next())
        console.log(literal.next())





        Of course you can also implement this in a way that it will work as an iterator in other contexts and is simpler:






        var G = {
        letters: ["a", "b", "c"],
        [Symbol.iterator]: function*(){
        yield *this.letters
        }
        }

        // now the object works as an iterable:
        console.log([...G])
        // or
        let iter = G[Symbol.iterator]()
        console.log(iter.next())
        console.log(iter.next())
        console.log(iter.next())
        console.log(iter.next())








        share|improve this answer















        In the first example i is captured in a closure so it works. In the second example i gets created new every time you call the function. You could make is a property of the object:






        var literal = {
        letters: ["a", "b", "c"],
        i: 0,
        next: function(){ //same next function as before
        return this.i < this.letters.length ?
        {value: this.letters[this.i++], done: false}:
        {value: undefined, done: true};
        }
        }

        console.log(literal.next())
        console.log(literal.next())
        console.log(literal.next())
        console.log(literal.next())





        Of course you can also implement this in a way that it will work as an iterator in other contexts and is simpler:






        var G = {
        letters: ["a", "b", "c"],
        [Symbol.iterator]: function*(){
        yield *this.letters
        }
        }

        // now the object works as an iterable:
        console.log([...G])
        // or
        let iter = G[Symbol.iterator]()
        console.log(iter.next())
        console.log(iter.next())
        console.log(iter.next())
        console.log(iter.next())








        var literal = {
        letters: ["a", "b", "c"],
        i: 0,
        next: function(){ //same next function as before
        return this.i < this.letters.length ?
        {value: this.letters[this.i++], done: false}:
        {value: undefined, done: true};
        }
        }

        console.log(literal.next())
        console.log(literal.next())
        console.log(literal.next())
        console.log(literal.next())





        var literal = {
        letters: ["a", "b", "c"],
        i: 0,
        next: function(){ //same next function as before
        return this.i < this.letters.length ?
        {value: this.letters[this.i++], done: false}:
        {value: undefined, done: true};
        }
        }

        console.log(literal.next())
        console.log(literal.next())
        console.log(literal.next())
        console.log(literal.next())





        var G = {
        letters: ["a", "b", "c"],
        [Symbol.iterator]: function*(){
        yield *this.letters
        }
        }

        // now the object works as an iterable:
        console.log([...G])
        // or
        let iter = G[Symbol.iterator]()
        console.log(iter.next())
        console.log(iter.next())
        console.log(iter.next())
        console.log(iter.next())





        var G = {
        letters: ["a", "b", "c"],
        [Symbol.iterator]: function*(){
        yield *this.letters
        }
        }

        // now the object works as an iterable:
        console.log([...G])
        // or
        let iter = G[Symbol.iterator]()
        console.log(iter.next())
        console.log(iter.next())
        console.log(iter.next())
        console.log(iter.next())






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 21 '18 at 22:30

























        answered Nov 21 '18 at 22:15









        Mark MeyerMark Meyer

        38.5k33159




        38.5k33159
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53421122%2fmaking-an-iterator-with-es6%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            If I really need a card on my start hand, how many mulligans make sense? [duplicate]

            Alcedinidae

            Can an atomic nucleus contain both particles and antiparticles? [duplicate]