Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
58 lines (58 sloc) 1.49 KB
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: Iterator
Description: implements a specialized language
*/
var element;
while (element - agg.next()) {
// do something with the element
console.log(element);
}
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
// reference
// http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#iteratorpatternjquery
// http://shop.oreilly.com/product/9780596806767.do?sortby=publicationDate
</script>
</body>
</html>