Skip to content

Instantly share code, notes, and snippets.

@sketchpunk
Created February 11, 2021 17:09
Show Gist options
  • Save sketchpunk/a3c7c5d7d12335d3c5b2370f39a34911 to your computer and use it in GitHub Desktop.
Save sketchpunk/a3c7c5d7d12335d3c5b2370f39a34911 to your computer and use it in GitHub Desktop.
Javascript Iterators
// 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