Last active
January 20, 2017 20:18
-
-
Save jxm262/86d8e2c6b88d1013a4a621733e1c36e8 to your computer and use it in GitHub Desktop.
js generators better explained
This file contains 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
import "babel-polyfill"; | |
import chai from 'chai' | |
chai.should() | |
function* justin() { | |
/** | |
* CALL # 1 | |
* calls first yield -> runs expression nc(), returns 3. | |
* returns back from stack immediately (ie. console.log 1-m never called) | |
*/ | |
var m = yield 3; | |
console.log('1 - m ', m); | |
/** | |
* Call #2 | |
* skips first yield statement | |
* calls console.log(1 - m) from above, moves to yield 5 statement | |
* returns from stack after calling yield 5 | |
*/ | |
var m2 = yield 5; | |
console.log('2 - m ', m); | |
console.log('2 - m2 ', m2); | |
/** | |
* Call #3 | |
* skips first yield statement | |
* skips second yield statement | |
* calls console.log 2-m | |
* calls console.log 2-m2 | |
* And... holy shit it's not 7?? Because the yield has an expression passed into it which returns immediately before {7} is ever executed | |
*/ | |
var m3 = yield 7; | |
console.log('3 - m ', m); | |
console.log('3 - m2 ', m2); | |
console.log('3 - m3 ', m3); | |
/** | |
* Note, m3 console.logs 3-m never called because yield expression 7 is returned on 3rd call | |
*/ | |
} | |
function* idMaker(){ | |
let idx = 0; | |
while (true) { | |
let next = yield ++idx + Math.random() | |
if(next === "reset") { | |
idx = 0 | |
} | |
} | |
} | |
describe("generators", function() { | |
describe("justin function", function () { | |
it("generates thing", function () { | |
const gen = justin() | |
console.log('value ', gen.next().value) | |
console.log('value ', gen.next().value) | |
console.log('value ', gen.next("holy shit, some other expression!").value) | |
}) | |
}) | |
describe("idMaker function", function() { | |
it("increments 1 + random until reset", function() { | |
const idmaker = idMaker() | |
console.log('idMaker ', idmaker.next().value) | |
console.log('idMaker ', idmaker.next().value) | |
console.log('idMaker ', idmaker.next().value) | |
console.log('idMaker ', idmaker.next("reset").value) | |
console.log('idMaker ', idmaker.next().value) | |
}) | |
}) | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment