Skip to content

Commit e3f6cfd

Browse files
committed
Add iterable examples
1 parent 8968976 commit e3f6cfd

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

JavaScript/f-iterator.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
'use strict';
2+
3+
const range = {
4+
start: 1,
5+
end: 10,
6+
[Symbol.iterator]() {
7+
let value = this.start;
8+
return {
9+
next: () => ({
10+
value,
11+
done: value++ === this.end + 1
12+
})
13+
};
14+
}
15+
};
16+
17+
console.dir({
18+
range,
19+
names: Object.getOwnPropertyNames(range),
20+
symbols: Object.getOwnPropertySymbols(range),
21+
});
22+
23+
for (const number of range) {
24+
console.log(number);
25+
}
26+
27+
const sum = (prev, cur) => prev + cur;
28+
const sumIterable = (...iterable) => iterable.reduce(sum);
29+
30+
const sumRange = sumIterable(...range);
31+
console.log('sumRange:', sumRange);

JavaScript/g-reverse.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
'use strict';
2+
3+
const arr = [2, 5, -1, 7, 0];
4+
5+
arr[Symbol.iterator] = function() {
6+
let index = this.length;
7+
return {
8+
next: () => ({
9+
done: index-- === 0,
10+
value: this[index]
11+
})
12+
};
13+
};
14+
15+
for (const number of arr) {
16+
console.log(number);
17+
}

0 commit comments

Comments
 (0)