DD2480-G9 / metrics-graphics

A library optimized for concise and principled data graphics and layouts.
http://metricsgraphicsjs.org
Mozilla Public License 2.0
0 stars 0 forks source link

Requirement: Use generator functions to create iterators #3

Closed lobax closed 6 years ago

lobax commented 6 years ago

Generators offer a simple, clean way to write custom iterators.

Using ES6 classes, and iterator could be constructed like this:

class RangeIterator {
  constructor(start, stop) {
    this.value = start;
    this.stop = stop;
  }

  [Symbol.iterator]() { return this; }

  next() {
    var value = this.value;
    if (value < this.stop) {
      this.value++;
      return {done: false, value: value};
    } else {
      return {done: true, value: undefined};
    }
  }
}

// Return a new iterator that counts up from 'start' to 'stop'.
function range(start, stop) {
  return new RangeIterator(start, stop);
}

Which can be radically simplified by using a generator function instead:

function* range(start, stop) {
  for (var i = start; i < stop; i++)
    yield i;
}

This can furthermore be used to refactor complicated loops, by using generator functions to handle the parts that generate the data. Then, one can simply use it in a for-of loop: for (let data of myNewGenerator(args))

More information: https://hacks.mozilla.org/2015/05/es6-in-depth-generators/

RickardBjorklund commented 6 years ago

No longer needed since assignment 3 is done!