LoginSignup
1
0

More than 1 year has passed since last update.

JS,TSのCollection関連クラスの相互変換方法まとめ

Posted at

Array, Iterable, Iterator, Generator, AsyncGeneratorのそれぞれのループの回し方と相互変換のコードです。
意外にまとまっている資料がないので、最小限のコード片だけをまとめました。

ループの回し方

// ## Array ##
for(const a of array) {
  ...
}
// または
array.forEach((a, index) => { ... })

// ## Iterable ##
for(const a of iterable) {
  ...
}
// ## Iterator ##
let n = iterator.next()
while(!n.done) {
  const a = n.value
  ...
  n = iterator.next()
}
// ## Generator ##
function* generatorFunc() {
  yield "value"
}
const generator = generatorFunc()
for(const a of generator) {
  ...
}
// ## Async Generator ##
async function* asyncGeneratorFunc() {
  yield "value"
}
const asyncGenerator = asyncGeneratorFunc()
for await(const a of asyncGenerator) {
  ...
}

相互変換

Arrayへの変換

Arrayからの変換

Code1
const iterator = {
  next: () => {
    return {
      value: "iterator",
      done: true
    }
  }
}

const iterable = {
  [Symbol.iterator]: () => iterator
}
Code2
async function asyncGeneratorToArray<T>(generator: AsyncGenerator<T>): Promise<T[]> {
  const array: T[] = []
  for await(const e of generator) {
    array.push(e)
  }
  return e
}
Code3
function* arrayToGenerator<T>(array: T[]) {
  for(const e of array) {
    yield e
  }
}
Code4
async function* arrayToAsyncGenerator<T>(array: T[]) {
  for(const e of array) {
        // awaitする処理を記述可能
    yield e
  }
}

※Arrayは無限長のCollectionを扱えないので、無限長のIterableやGeneratorから変換しようとするとハングアップします。ご注意ください。

おまけ

Map,SetとArrayの変換

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0