get-next-method-only-once.js (1157B)
1 // Copyright (C) 2023 Michael Ficarra. All rights reserved. 2 // This code is governed by the BSD license found in the LICENSE file. 3 /*--- 4 esid: sec-iterator.from 5 description: > 6 Gets the next method from the underlying iterator only once 7 info: | 8 Iterator.from ( O ) 9 10 2. Let iteratorRecord be ? GetIteratorFlattenable(O). 11 12 features: [iterator-helpers] 13 flags: [] 14 ---*/ 15 let nextGets = 0; 16 let nextCalls = 0; 17 18 class CountingIterator { 19 get next() { 20 ++nextGets; 21 let iter = (function* () { 22 for (let i = 1; i < 5; ++i) { 23 yield i; 24 } 25 })(); 26 return function () { 27 ++nextCalls; 28 return iter.next(); 29 }; 30 } 31 } 32 33 let iterator = new CountingIterator(); 34 35 assert.sameValue(nextGets, 0, 'The value of `nextGets` is 0'); 36 assert.sameValue(nextCalls, 0, 'The value of `nextCalls` is 0'); 37 38 iterator = Iterator.from(iterator); 39 40 assert.sameValue(nextGets, 1, 'The value of `nextGets` is 1'); 41 assert.sameValue(nextCalls, 0, 'The value of `nextCalls` is 0'); 42 43 iterator.toArray(); 44 45 assert.sameValue(nextGets, 1, 'The value of `nextGets` is 1'); 46 assert.sameValue(nextCalls, 5, 'The value of `nextCalls` is 5'); 47 48 reportCompare(0, 0);