dinsdag 14 januari 2025

Iterator in javascript

const myArray = [1, 2, 3];
const iterator = myArray[Symbol.iterator]();

for (const value of myArray) {
  console.log(value); // Outputs: 1, 2, 3
}


class MyCollection {
  constructor(items) {
    this.items = items;
  }

  [Symbol.iterator]() {
    let index = 0;
    const items = this.items;

    return {
      next() {
        if (index < items.length) {
          return { value: items[index++], done: false };
        } else {
          return { done: true };
        }
      }
    };
  }
}

let tmp3 = new MyCollection([1,2,3,4,5]);
for (const value of tmp3) {
  console.log(value);
}

Ofcourse you don't have the typechecking that typescript has:
function getValue<T extends keyof {yoho: string, "ho"?: number}>(item: T) {
	return item;
}
console.log(getValue<"ho">("ho"));

Geen opmerkingen:

Een reactie posten