Skip to content

Latest commit

 

History

History
70 lines (54 loc) · 1.25 KB

File metadata and controls

70 lines (54 loc) · 1.25 KB

39. implement range()

Problem

https://bigfrontend.dev/problem/implement-range

Problem Description

Can you create a range(from, to) which makes following work?

for (let num of range(1, 4)) {
  console.log(num);
}
// 1
// 2
// 3
// 4

This is a simple one, could you think more fancy approaches other than for-loop?

Notice that you are not required to return an array, but something iterable would be fine.

Solution

/**
 * @param {integer} from
 * @param {integer} to
 */
function range(from, to) {
  // The iterator object that will be returned
  // when calling the Symbol.iterator method of an object.
  // The iterator object has a method named next which
  // generates values for the iteration.
  const iterator = {
    from: from,
    to: to,
    next() {
      if (this.from > this.to) {
        return { done: true };
      }

      const value = { value: this.from, done: false };
      this.from++;
      return value;
    },
  };

  // Return an object that has a method named
  // Symbol.iterator for the for...of to work.
  // When for..of starts, it calls that method once.
  return {
    [Symbol.iterator]() {
      return iterator;
    },
  };
}

Reference

Iterables