본문 바로가기
Web/JavaScript

[TypeScript] Iterators and Generators

by llHoYall 2020. 10. 23.

Iterator is a behavioral design pattern that allows sequential traversal through a complex data structure without exposing its internal details.

Generator is a lazy iterator.

Iterables

An object is deemed iterable if it has an implementation for the Symbol.iterator property.

Some built-in types like Array, Map, Set, String, Int32Array, Uint32Array, etc. have their Symbol.iterator property already implemented.

Symbol.iterator function on an object is responsible for returning the list of values to iterate on.

for..of Statements

for..of loops over an iterable object, invoking the Symbol.iterator property on the object.

const array = [3, "hello", true];
for (let item of array) {
  console.log(item);
}
// 3
// hello
// true

for..of and for..in are some differences.

const array = [3, "hello", true];
for (let item in array) {
  console.log(item);
}
// 0
// 1
// 2

Generator

The generator is similar to iterator, but it is different in that it is evaluated when necessary.

function* generator(arr: number[]): IterableIterator<number> {
  for (let item of arr) {
    yield item;
  }
}

const arrNum = [1, 2, 3, 4, 5];
const genFn = generator(arrNum);

console.log(genFn.next());
// {value:1, done: false}

console.log(genFn.next());
// {value:2, done: false}

console.log(genFn.next());
// {value:3, done: false}

As shown in the example above, only the values required at the time of need are evaluated and returned.

 

※ If you use generator, you have to set target to ES6 or later.

'Web > JavaScript' 카테고리의 다른 글

[TypeScript] Type Inference  (0) 2020.10.25
[TypeScript] Decorators  (0) 2020.10.24
[TypeScript] Interface  (0) 2020.10.17
[TypeScript] Destructuring and Spread  (0) 2020.10.16
[TypeScript] Variable Declaration (var, let, const)  (0) 2020.10.15

댓글