Skip to content

Instantly share code, notes, and snippets.

@rogerwschmidt
Last active July 7, 2017 17:49
Show Gist options
  • Select an option

  • Save rogerwschmidt/7cce2770b17bd6a4743d1e46a8ec4f18 to your computer and use it in GitHub Desktop.

Select an option

Save rogerwschmidt/7cce2770b17bd6a4743d1e46a8ec4f18 to your computer and use it in GitHub Desktop.

Javascipt Generators and Iterators

Objectives

  • 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.

What are Javascript Generators

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); // Derek

source

Why are Javascript Generators useful

Javascript 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.

Use a generator to create a fibonacci sequence

Exercise

Using generators, create a function that will return each element of the fibonacci sequence when .next() is invoked

answer

Use a generator to create an iterator on an array like object.

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);
}

source

Use an iterators to create custom object traversal.

Exercise

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment