MIRROR: javascript for 馃悳's, a tiny runtime with big ambitions
1import { test, testDeep, summary } from './helpers.js';
2
3console.log('Iterator Tests\n');
4
5const arr = [1, 2, 3];
6const iter = arr[Symbol.iterator]();
7test('array iterator first', iter.next().value, 1);
8test('array iterator second', iter.next().value, 2);
9test('array iterator third', iter.next().value, 3);
10test('array iterator done', iter.next().done, true);
11
12const str = 'abc';
13const strIter = str[Symbol.iterator]();
14test('string iterator first', strIter.next().value, 'a');
15test('string iterator second', strIter.next().value, 'b');
16test('string iterator third', strIter.next().value, 'c');
17test('string iterator done', strIter.next().done, true);
18
19const map = new Map([
20 ['a', 1],
21 ['b', 2]
22]);
23const mapIter = map.entries();
24testDeep('map entries first', mapIter.next().value, ['a', 1]);
25testDeep('map entries second', mapIter.next().value, ['b', 2]);
26
27const set = new Set([1, 2, 3]);
28const setIter = set.values();
29test('set values first', setIter.next().value, 1);
30test('set values second', setIter.next().value, 2);
31
32let forOfSum = 0;
33for (const n of [1, 2, 3]) {
34 forOfSum += n;
35}
36test('for-of array', forOfSum, 6);
37
38let forOfStr = '';
39for (const c of 'hi') {
40 forOfStr += c;
41}
42test('for-of string', forOfStr, 'hi');
43
44const custom = {
45 data: [10, 20, 30],
46 [Symbol.iterator]() {
47 let i = 0;
48 return {
49 next: () => {
50 if (i < this.data.length) {
51 return { value: this.data[i++], done: false };
52 }
53 return { done: true };
54 }
55 };
56 }
57};
58
59let customSum = 0;
60for (const n of custom) {
61 customSum += n;
62}
63test('custom iterator', customSum, 60);
64
65let capturedNestedForOf = 0;
66const capturedFns = {};
67for (const { values = [] } of [{ values: ['a', 'bb'] }]) {
68 for (const value of values) {
69 capturedFns[value] = () => value.length;
70 capturedNestedForOf++;
71 }
72}
73test('captured nested for-of count', capturedNestedForOf, 2);
74test('captured nested for-of closure', capturedFns.bb(), 2);
75
76summary();