Skip to content

Instantly share code, notes, and snippets.

@luin
Created January 24, 2013 15:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luin/4623001 to your computer and use it in GitHub Desktop.
Save luin/4623001 to your computer and use it in GitHub Desktop.
Implementing iterators in JavaScript
function iterators (list) {
var index = 0;
return function () {
return list[index++];
}
}
var v;
var str = "hello world!";
var itStr = iterators(str);
console.log('Begin to iterate the string');
while (v = itStr()) {
console.log(v);
}
var arr = ['a', 'b', 'c'];
var itArr = iterators(arr);
console.log('Begin to iterate the array');
while (v = itArr()) {
console.log(v);
}
/* Outputs:
Begin to iterate the string
h
e
l
l
o
w
o
r
l
d
!
Begin to iterate the array
a
b
c
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment