Created
April 17, 2018 14:07
-
-
Save digvijaybhakuni/26ef6ec1c6cda5751ac70b1b8ae0177f to your computer and use it in GitHub Desktop.
Javascript Concept
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const test = [1, 2, 3]; | |
for(const t of test){ | |
t | |
} | |
console.log(test); | |
const iterator = test[Symbol.iterator]() | |
iterator | |
console.log(iterator.next()); | |
console.log(iterator.next()); | |
console.log(iterator.next()); | |
console.log(iterator.next()); | |
// Custom Object that have iterator | |
const makeCustomObjectWithIterator = (count) => { | |
return { | |
[Symbol.iterator]: () => { | |
let ctr = 0; | |
return { | |
next: () => { | |
ctr++; | |
if(ctr <= count){ | |
return { value: Math.round(Math.random() * 10) , done: false } | |
} | |
return { done: true } | |
} | |
} | |
} | |
} | |
} | |
const aIterable = makeCustomObjectWithIterator(5); | |
for(const i of aIterable){ | |
i | |
} | |
const bIterable = makeCustomObjectWithIterator(10); | |
for(const i of bIterable){ | |
i | |
} | |
// Iterator can be asyncronus that is fetch data from an API | |
// And Generator in javascript is just a syntax sugar over it. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment