Skip to content

Instantly share code, notes, and snippets.

@erkobridee
Created April 19, 2017 03:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erkobridee/cd931bdba71f13b1e7292d82122d31e0 to your computer and use it in GitHub Desktop.
Save erkobridee/cd931bdba71f13b1e7292d82122d31e0 to your computer and use it in GitHub Desktop.
es6 generators and symbols examples
function* shopping() {
// stuff on the sidewalk
// walking down the sidewalk
// go into the store with cash
const stuffFromStore = yield 'cash';
// walking to laundry place
const cleanClothes = yield 'laundry';
// walking back home
return [stuffFromStore, cleanClothes];
}
// stuff in the store
const gen = shopping();
gen.next(); // leaving our house
// walked into the store
// walking up ad down the aisles...
// purchase our stuff
gen.next('groceries'); // leaving the store with groceries
gen.next('clean clothes');
const testingTeam = {
lead : 'Amanda',
tester : 'Bill'
};
const engineeringTeam = {
testingTeam,
size : 3,
department : 'Engineering',
lead : 'Jill',
manager : 'Alex',
engineer : 'Dave'
};
function* TestingTeamIterator(team){
yield team.lead;
yield team.tester;
}
function* TeamIterator(team) {
yield team.lead;
yield team.manager;
yield team.engineer;
const testingTeamGenerator = TestingTeamIterator(team.testingTeam);
yield* testingTeamGenerator; // delegation
}
const names = [];
for(let name of TeamIterator(engineeringTeam)){
names.push(name);
}
console.log(names);
const testingTeam = {
lead : 'Amanda',
tester : 'Bill',
[Symbol.iterator]: function* () {
yield this.lead;
yield this.tester;
}
};
const engineeringTeam = {
testingTeam,
size : 3,
department : 'Engineering',
lead : 'Jill',
manager : 'Alex',
engineer : 'Dave',
[Symbol.iterator]: function* () {
yield this.lead;
yield this.manager;
yield this.engineer;
yield* this.testingTeam;
}
};
const names = [];
for(let name of engineeringTeam){
names.push(name);
}
console.log(names);
class Comment {
constructor(content, children) {
this.content = content;
this.children = children;
}
*[Symbol.iterator]() {
yield this.content;
for(let child of this.children){
yield* child;
}
}
}
const children = [
new Comment('good comment', []),
new Comment('bad comment', []),
new Comment('meh', [])
];
const tree = new Comment('Great post!', children);
const values = [];
for(let value of tree){
values.push(value);
}
console.log(values);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment