forked from nnupoor-zz/js_designpatterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiterator.js
33 lines (29 loc) · 809 Bytes
/
iterator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Access elements of a collection sequentially without
// needing to know the underlying representation.
/************
Iterator
************/
function Iterator(arr) {
var currentPosition = -1;
return {
hasNext:function() {
return currentPosition+1 < arr.length;
},
next: function() {
if(!this.hasNext())
return null;
currentPosition++;
return arr[currentPosition];
}
}
}
// Example Usage
var people = [{id:1,name:'John'}, {id:2,name:'George'}, {id:3,name:'Guy'}];
var peopleIterator = Iterator(people); // Create Iterator for 'people'
while(peopleIterator.hasNext()) {
var person = peopleIterator.next();
console.log(person.name + '\'s id is: ' + person.id + '!');
}
// John's id is: 1!
// George's id is: 2!
// Guy's id is: 3!