Last active
July 8, 2018 04:00
-
-
Save thinkgarden/01e8bc015bae8c1c4a579735a7ecc491 to your computer and use it in GitHub Desktop.
[generate] some sample for generate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function *foo() { | |
var x = yield 2; | |
z++; | |
var y = yield (x * z); | |
console.log( x, y, z ); | |
} | |
var z = 1; | |
var it1 = foo(); | |
var it2 = foo(); | |
var val1 = it1.next().value; // 2 <-- yield 2 | |
var val2 = it2.next().value; // 2 <-- yield 2 | |
val1 = it1.next( val2 * 10 ).value; // 40 <-- x:20, z:2 | |
val2 = it2.next( val1 * 5 ).value; // 600 <-- x:200, z:3 | |
it1.next( val2 / 2 ); // y:300 | |
// 20 300 3 | |
it2.next( val1 / 4 ); // y:10 | |
// 200 10 3 | |
// 迭代器 | |
var something = (function() { | |
var nextVal; | |
return { | |
[Symbol.iterator]: function(){return this;}, | |
next: function(){ | |
if(nextVal === undefined) { | |
nextVal = 1; | |
} | |
else { | |
nextVal = (3* nextVal) + 6; | |
} | |
return {done: false, value: nextVal} | |
} | |
} | |
})() | |
for (var v of something) { | |
console.log( v ); | |
// 不要死循环! | |
if (v > 500) { | |
break; | |
} | |
} | |
// 1 9 33 105 321 969 | |
// 可以通过生成器实现前面的这个 something 无限数字序列生产者,类似这样: | |
function *something() { | |
var nextVal; | |
while (true) { | |
if (nextVal === undefined) { | |
nextVal = 1; } | |
else { | |
nextVal = (3 * nextVal) + 6; | |
} | |
yield nextVal; | |
} | |
} | |
//现在,可以通过 for..of 循环使用我们雕琢过的新的 *something() 生成器 | |
for (var v of something()) { | |
console.log( v ); | |
// 不要死循环! | |
if (v > 500) { | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment