Skip to content

Instantly share code, notes, and snippets.

@gergelyke
Last active August 29, 2015 14:00
Show Gist options
  • Save gergelyke/5c8be1e285eca6aaced5 to your computer and use it in GitHub Desktop.
Save gergelyke/5c8be1e285eca6aaced5 to your computer and use it in GitHub Desktop.
Generators
function* naturalNumbers(){
var n = 1;
while (true){
yield n++;
}
}
var numbers = naturalNumbers();
console.log (numbers.next());
console.log (numbers.next());
console.log (numbers.next());
console.log (numbers.next());
function* naturalNumbers(){
var n = 1;
while (n < 3){
yield n++;
}
}
var numbers = naturalNumbers();
console.log (numbers.next());
console.log (numbers.next());
//{ value: 2, done: false}
//yepp, out of numbers
console.log (numbers.next());
//{value: undefined, done: true}
var thunk = require('thunkify');
var fs = require('fs');
var read = thunk(fs.readFile);
var co = require('co');
//will be run sequentially
var sizes = co(function *(){
var a = yield read('.gitignore');
var b = yield read('README.md');
var c = yield read('package.json');
return [a.length, b.length, c.length];
});
//traditional callbacks
sizes(function (err, lengths) {
console.log(lengths);
});
var thunk = require('thunkify');
var fs = require('fs');
var read = thunk(fs.readFile);
var co = require('co');
// co is just for control flow goodness
var sizes = co(function *(){
var a = read('.gitignore');
var b = read('README.md');
var c = read('package.json');
// note: now it will run in parallel
return [
(yield a).length,
(yield b).length,
(yield c).length
];
});
// won't work, yield can only be used in generator function
yield sizes;
{
"name": "generator_example",
"version": "0.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"license": "ISC",
"dependencies": {
"co": "^3.0.6",
"co-redis": "^1.1.0",
"redis": "^0.10.1",
"thunkify": "^2.1.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment