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 Trained1184
Total Skips149
Total Code Submissions1199
Total Times Completed448
JavaScript Completions448
Total Stars15
% of votes with a positive feedback rating79% of 87
Total "Very Satisfied" Votes56
Total "Somewhat Satisfied" Votes26
Total "Not Satisfied" Votes5
Ad
Contributors
  • matt c Avatar
  • jhoffner Avatar
  • joh_pot Avatar
  • farhanaditya Avatar
Ad