Created
February 11, 2021 17:09
-
-
Save sketchpunk/a3c7c5d7d12335d3c5b2370f39a34911 to your computer and use it in GitHub Desktop.
Javascript Iterators
This file contains hidden or 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
// DEFAULT CLASS ITERATOR | |
[Symbol.iterator](){ | |
let n = this.head; | |
let result = { value:null, done:false }; | |
return { next:()=>{ | |
if( !n ) result.done = true; | |
else{ | |
result.value = n.value; | |
n = n.next; | |
} | |
return result; | |
}}; | |
} | |
// FUNCTION ITERATOR OR EXTRA ITERATORS FOR A CLASS | |
iter(){ | |
let n = this.head; | |
let result = { value:null, done:false }; | |
let next = ()=>{ | |
if( !n ) result.done = true; | |
else{ | |
result.value = n.value; | |
n = n.next; | |
} | |
return result; | |
}; | |
return { [Symbol.iterator](){ return { next }; } }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment