Home > Web Front-end > JS Tutorial > Iterable - JavaScript Challenges

Iterable - JavaScript Challenges

Patricia Arquette
Release: 2024-11-03 19:22:29
Original
895 people have browsed it

Iterable - JavaScript Challenges

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


Iterable related challenges


Iterable

/**
 * @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]
Copy after login

Reference

  • Iterator - MDN
  • Iteration protocols - MDN
  • [Iterator.prototypeSymbol.iterator - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator/Symbol.iterator)

The above is the detailed content of Iterable - JavaScript Challenges. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template