-
Notifications
You must be signed in to change notification settings - Fork 1
/
45-Function_Generator.html
80 lines (71 loc) · 1.87 KB
/
45-Function_Generator.html
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
75
76
77
78
79
80
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Function Generator</title>
</head>
<body>
<script>
// function generator adalah function yang mengenerate data sesuai yang kita butuhkan
function* createNames() {
yield 'Eko';
yield 'Andy';
yield 'Frian';
}
console.log(createNames());
// Data Generator tidak bisa di akses tapi bisa di iterasi (di looping);
const names = createNames();
for (const name of names) {
console.log(name);;
}
console.log('\n');
console.log('\n');
console.log('contoh lazy:');
console.log('\n');
// lazy
function* buatGanjil(value) {
for (let i = 1; i <= value; i++) {
if (i % 2 === 1) {
// generator bersifat lazy
console.log(`Yield ${i}`);
yield i;
}
}
}
// lazy adalah data tidak akan tampil sebelum dipanggil
const numbers = buatGanjil(10);
for (const number of numbers) {
console.log(number);
}
console.log('\n');
console.log('\n');
console.log('contoh eager:');
console.log('\n');
// eager
function buatGanjilArray(values) {
const result = [];
for (let i = 1; i <= values; i++) {
if (i % 2 === 1) {
console.log(`Yield ${i}`);
result.push(i);
}
}
return result;
}
const ganjils = buatGanjilArray(10);
for (let ganjil of ganjils) {
console.log(ganjil);
}
console.log('\n');
console.log('\n');
console.log('cara ngambil value generator');
console.log('\n');
const angka = buatGanjil(100)
console.log(angka.next().value);
console.log(angka.next().value);
console.log(angka.next().value);
</script>
</body>
</html>