-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIterator.js
74 lines (66 loc) · 1.48 KB
/
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Iterator is a behavioral design pattern.
// Итератор - поведенческий шаблон проектирования.
class Iterator {
constructor(elements) {
// проверяем на объект или массив
// можно добавить другую логику для проверок
this.isArray = Array.isArray(elements);
if (!this.isArray) {
this.keys = Object.keys(elements);
}
this.index = 0;
this.elements = elements;
}
next() {
if (this.isArray) {
return this.elements[this.index++];
}
return this.elements[this.keys[this.index++]];
}
nasNext() {
if (this.isArray) {
return this.index < this.elements.length;
}
return this.index < this.keys.length;
}
}
const chocolate1 = {
milk: {
type: 'Milk1',
price: 10
},
dark: {
type: 'Dark1',
price: 15
},
withNuts: {
type: 'Nuts1',
price: 13
}
};
const chocolate2 = [
{
type: 'Milk2',
price: 10
},
{
type: 'Dark2',
price: 15
},
{
type: 'Nuts2',
price: 13
}
];
const collection1 = new Iterator(['Milk chocolate', 'Dark chocolate', 'Nuts chocolate']);
const collection2 = new Iterator(chocolate1);
const collection3 = new Iterator(chocolate2);
const logAll = (...collections) => {
collections.forEach(collection => {
console.log();
while (collection.nasNext()) {
console.log(collection.next());
}
});
};
logAll(collection1, collection2, collection3);