1 /* 2 * Copyright (c) 2023-2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 function* countAppleSales() { 17 const saleList = [3, 7, 5]; 18 for (let i = 0; i < saleList.length; i++) { 19 yield saleList[i]; 20 } 21 } 22 23 const foo = function* () { 24 yield 'a'; 25 yield 'b'; 26 yield 'c'; 27 }; 28 let str = ''; 29 for (const val of foo()) { 30 str = str + val; 31 } 32 console.log(str); // Expected output: "abc" 33 34 class MyGenerator { 35 public *getValues() { 36 // you can put the return type Generator<number>, but it is ot necessary as ts will infer 37 let index = 1; 38 while (true) { 39 yield index; 40 index = index + 1; 41 42 if (index > 10) { 43 break; 44 } 45 } 46 } 47 } 48 49 function* func1() { 50 yield 42; 51 } 52 function* func2() { 53 yield* func1(); 54 } 55 const iterator = func2(); 56 console.log(iterator.next().value); // Expected output: 42 57 58 function* g1() { 59 yield 2; 60 yield 3; 61 yield 4; 62 } 63 function* g2() { 64 yield 1; 65 yield* g1(); 66 yield 5; 67 } 68 const gen = g2(); 69 console.log(gen.next()); // {value: 1, done: false} 70 console.log(gen.next()); // {value: 2, done: false} 71 console.log(gen.next()); // {value: 3, done: false} 72 console.log(gen.next()); // {value: 4, done: false} 73 console.log(gen.next()); // {value: 5, done: false} 74 console.log(gen.next()); // {value: undefined, done: true} 75