{"id":3292,"date":"2020-01-29T09:36:21","date_gmt":"2020-01-29T08:36:21","guid":{"rendered":"https:\/\/solidt.eu\/site\/?p=3292"},"modified":"2022-07-25T08:35:42","modified_gmt":"2022-07-25T07:35:42","slug":"javascript-create-an-iterator","status":"publish","type":"post","link":"https:\/\/solidt.eu\/site\/javascript-create-an-iterator\/","title":{"rendered":"Javascript create an iterator"},"content":{"rendered":"\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">obj[Symbol.iterator] \/\/ a function that returns an Iterator 'instance'\nobj[Symbol.iterator]() \/\/ Iterator\n\/\/ an iterator is an object with an method: \n\/\/ .next() that returns { value: any,  done: boolean}\n{ next: () => ({ value: 1, done: false}) }\n\n\/\/ generators return an Iterator\nfunction* range(from, to) {\n  let i = from;\n  while (i &lt;= to) {\n    yield i;\n    i++;\n  }\n}\n\nconst a = { [Symbol.iterator]: () => range(0, 10) };\nfor (const item of a) console.log(item);\n\n(()=>{\nfunction* iterator(iterable) {\n\tfor(const item of iterable)\n\t\tyield item;\n}\nconst x = ['a', 'b'];\nconst y = ['c', 'd'];\nconsole.log(x.concat(y));\nconst b = { [Symbol.iterator]: () => iterator(x.concat(y)) };\nfor (const item of b) console.log(item);\n})();\n<\/pre>\n\n\n\n<p><a href=\"https:\/\/codeburst.io\/a-simple-guide-to-es6-iterators-in-javascript-with-examples-189d052c3d8e\">https:\/\/codeburst.io\/a-simple-guide-to-es6-iterators-in-javascript-with-examples-189d052c3d8e<\/a><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">const myFavouriteAuthors = {\n  allAuthors: {\n    fiction: [\n      'Agatha Christie', \n      'J. K. Rowling',\n      'Dr. Seuss'\n    ],\n    scienceFiction: [\n      'Neal Stephenson',\n      'Arthur Clarke',\n      'Isaac Asimov', \n      'Robert Heinlein'\n    ],\n    fantasy: [\n      'J. R. R. Tolkien',\n      'J. K. Rowling',\n      'Terry Pratchett'\n    ],\n  },\n  [Symbol.iterator]() {\n    \/\/ Get all the authors in an array\n    const genres = Object.values(this.allAuthors);\n    \n    \/\/ Store the current genre and author index\n    let currentAuthorIndex = 0;\n    let currentGenreIndex = 0;\n    \n    return {\n      \/\/ Implementation of next()\n      next() {\n        \/\/ authors according to current genre index\n        const authors = genres[currentGenreIndex];\n        \n        \/\/ doNotHaveMoreAuthors is true when the authors array is exhausted.\n        \/\/ That is, all items are consumed.\n        const doNothaveMoreAuthors = !(currentAuthorIndex &lt; authors.length);\n        if (doNothaveMoreAuthors) {\n          \/\/ When that happens, we move the genre index to the next genre\n          currentGenreIndex++;\n          \/\/ and reset the author index to 0 again to get new set of authors\n          currentAuthorIndex = 0;\n        }\n        \n        \/\/ if all genres are over, then we need tell the iterator that we \n        \/\/ can not give more values.\n        const doNotHaveMoreGenres = !(currentGenreIndex &lt; genres.length);\n        if (doNotHaveMoreGenres) {\n          \/\/ Hence, we return done as true.\n          return {\n            value: undefined,\n            done: true\n          };\n        }\n        \n        \/\/ if everything is correct, return the author from the \n        \/\/ current genre and incerement the currentAuthorindex\n        \/\/ so next time, the next author can be returned.\n        return {\n          value: genres[currentGenreIndex][currentAuthorIndex++],\n          done: false\n        }\n      }\n    };\n  }\n};\n\nfor (const author of myFavouriteAuthors) {\n  console.log(author);\n}\n\nconsole.log(...myFavouriteAuthors)<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>https:\/\/codeburst.io\/a-simple-guide-to-es6-iterators-in-javascript-with-examples-189d052c3d8e<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[5,4,1],"tags":[],"class_list":["post-3292","post","type-post","status-publish","format-standard","hentry","category-javascript","category-programming","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/3292","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/comments?post=3292"}],"version-history":[{"count":5,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/3292\/revisions"}],"predecessor-version":[{"id":3324,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/3292\/revisions\/3324"}],"wp:attachment":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/media?parent=3292"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/categories?post=3292"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/tags?post=3292"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}