Skip to content

Commit db9d611

Browse files
committed
added iterator pattern
1 parent 1061051 commit db9d611

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

design-patterns/iterator.html

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<title>JavaScript Patterns</title>
5+
<meta charset="utf-8">
6+
</head>
7+
<body>
8+
<script>
9+
var element;
10+
while (element - agg.next()) {
11+
// do something with the element
12+
console.log(element);
13+
}
14+
15+
while (agg.hasNext()) {
16+
// do something with the next element...
17+
console.log(agg.next());
18+
}
19+
20+
var agg = (function () {
21+
22+
var index = 0,
23+
data = [1, 2, 3, 4, 5],
24+
length = data.length;
25+
26+
return {
27+
28+
next: function () {
29+
var element;
30+
if (!this.hasNext()) {
31+
return null;
32+
}
33+
element = data[index];
34+
index = index + 2;
35+
return element;
36+
},
37+
38+
hasNext: function () {
39+
return index < length;
40+
},
41+
42+
rewind: function () {
43+
index = 0;
44+
},
45+
46+
current: function () {
47+
return data[index];
48+
}
49+
50+
};
51+
}());
52+
53+
// this loop logs 1, then 3, then 5
54+
while (agg.hasNext()) {
55+
console.log(agg.next());
56+
}
57+
58+
// go back
59+
agg.rewind();
60+
console.log(agg.current()); // 1
61+
</script>
62+
</body>
63+
</html>

0 commit comments

Comments
 (0)