- What are Javascript Generators
- Why are Javascript Generators useful
- Use a generator to create a fibonacci sequence
- Use a generator to create an iterator on an array like object.
Generators are a function they allow you to define an iterative algorithm which can maintain its own state.
function* idMaker() {
yield 'Wes';
yield 'Charlie';
yield 'Scott';
yield 'Roger';
yield 'Jamieson';
yield 'Derek';
}
const gen = idMaker();
console.log(gen.next().value); // Wes
console.log(gen.next().value); // Charlie
console.log(gen.next().value); // Scott
console.log(gen.next().value); // Roger
console.log(gen.next().value); // Jamieson
console.log(gen.next().value); // DerekJavascript generators are useful because they just do the work necesseary to get you to the next step of your algorith. An example is if you need to read a file line by line, but you don't want to load the entire file into memory.
Using generators, create a function that will return each element of the fibonacci sequence when .next() is invoked
An object is iterable if it defines its iteration behavior, such as what values are looped over in a for..of construct. Some built-in types, such as Array or Map, have a default iteration behavior, while other types (such as Object) do not.
let arrayLikeObject = {
'0' : 'item0',
'1' : 'item1',
'2' : 'item2',
'3' : 'item3',
'4' : 'item4'
}
arrayLikeObject[Symbol.iterator] =
function*(){
for(const key of Object.keys(this)){
yield this[key]
}
}
for(const value of arrayLikeObject){
console.log(value);
}Create a function that takes an object, and a sorting function. Return the same object, with an iterator that would traverse the object in the order specified by the sorting function.