7 kyu

Iterator Basics

Description:

Iterators

Description

Iterator objects enable custom iteration like CLR IEnumerable or Java Iterable. Generalize for..in to custom iterator-based iteration with for..of. Don’t require realizing an array, enabling lazy design patterns like LINQ.

Task

Your task is simple, create a counter that increments by 1 each time. You must use the iterator described below. Good luck!

Example

let fibonacci = {
  [Symbol.iterator]() {
    let pre = 0, cur = 1;
    return {
      next() {
        [pre, cur] = [cur, pre + cur];
        return { done: false, value: cur }
      }
    }
  }
}

for (let n of fibonacci) {
  // truncate the sequence at 1000
  if (n > 1000)
    break;
  console.log(n);
}

Reading: Iterators and Generators

Iterators
Fundamentals

Stats:

CreatedJul 22, 2015
PublishedJul 22, 2015
Warriors Trained1200
Total Skips149
Total Code Submissions1216
Total Times Completed457
JavaScript Completions457
Total Stars16
% of votes with a positive feedback rating80% of 90
Total "Very Satisfied" Votes59
Total "Somewhat Satisfied" Votes26
Total "Not Satisfied" Votes5
Ad
Contributors
  • matt c Avatar
  • jhoffner Avatar
  • joh_pot Avatar
  • farhanaditya Avatar
Ad