Skip to content

Instantly share code, notes, and snippets.

@KalpasWang
Created December 19, 2019 14:58
Show Gist options
  • Save KalpasWang/74784e78b8b0f3388657bf09b0ff15ed to your computer and use it in GitHub Desktop.
Save KalpasWang/74784e78b8b0f3388657bf09b0ff15ed to your computer and use it in GitHub Desktop.
迭代器模式
var element;
while (element = agg.next()) {
// do something with the element
console.log(element);
}
// use hasNext()
while (agg.hasNext()) {
// do something with the next element...
console.log(agg.next());
}
var agg = (function() {
var index = 0,
data = [1, 2, 3, 4, 5],
length = data.length;
return {
next: function() {
var element;
if (!this.hasNext()) {
return null;
}
element = data[index];
index = index + 2;
return element;
},
hasNext: function() {
return index < length;
},
rewind: function() {
index = 0;
},
current: function() {
return data[index];
}
};
}());
// this loop logs 1, then 3, then 5
while (agg.hasNext()) {
console.log(agg.next());
}
// go back
agg.rewind();
console.log(agg.current()); // 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment