DEV Community

Mitchell
Mitchell

Posted on • Edited on

Iterable - JavaScript Challenges

You can find all the code in this post in the repo Github.


Iterable related challenges


Iterable

Rewriting the Symbol.iterator properity to create an iterator object.

The iterator object includes two properties:

  1. value: the current value of the current iteration call, undefined when the iterator is over.
  2. done: whether the iteration has finished.
/**
 * @param {any} data
 * @return {object}
 */

function createCustomIterable(data) {
  return {
    [Symbol.iterator]() {
      let index = 0;
      return {
        next() {
          if (index < data.length) {
            return {
              value: data[index++],
              done: false,
            };
          } else {
            return {
              value: undefined,
              done: true,
            };
          }
        },
      };
    },
  };
}

// Usage example:
const customIterable = createCustomIterable([1, 2, 3, 4]);

// Using for...of loop
for (const item of customIterable) {
  console.log(item);
}
/**
 * 1
 * 2
 * 3
 * 4
 */

// Using spread operator
const arrayFromIterable = [...customIterable];
console.log(arrayFromIterable); // => [1, 2, 3, 4]

// Using Array.from()
const anotherArray = Array.from(customIterable);
console.log(anotherArray); // => [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Reference

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more