2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】配列を二重配列に分解する提案

Last updated at Posted at 2025-11-10

これはなに?

Iterator Chunking
[1, 2, 3, 4, 5, 6, 7, 8]

 ↓

[ [1, 2, 3], [4, 5, 6], [7, 8] ] // chunking
[ [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8] ] // sliding

TC39Iterator Chunkingという提案がなされていました。
ステージは2.7であり、仕様はおおむね固まっていて検証段階というところです。

Iterator Chunking

TC39の提案。
イテレータを重複する、もしくは重複しないサブシーケンスに分割します。

presentations to committee

過去のプレゼン

September 2025
July 2025
May 2025
October 2024
January 2024

motivation

ストリームを一度に複数の値で使用すると便利な場合があります。
たとえば、あるアルゴリズムでは隣接する要素も参照する必要があります。

chunking

重複しないサブシーケンスを、chankingで解決します。

const digits = () => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].values();

let chunksOf2 = Array.from(digits().chunks(2));
// [ [0, 1], [2, 3], [4, 5], [6, 7], [8, 9] ]

let chunksOf3 = Array.from(digits().chunks(3));
// [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [9] ]

let chunksOf4 = Array.from(digits().chunks(4));
// [ [0, 1, 2, 3], [4, 5, 6, 7], [8, 9] ]

ユースケース。

・ページネーション
・カレンダーなどのグリッドレイアウト
・バッチ/ストリーム処理
・行列演算
・フォーマット/エンコード
・バケット化

sliding window

隣接するシーケンスが必要な場合、これは一般的にスライディングウィンドウと呼ばれます。

let windowsOf2 = Array.from(digits().windows(2));
// [ [0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9] ]

let windowsOf3 = Array.from(digits().windows(3));
// [ [0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9] ]

let windowsOf4 = Array.from(digits().windows(4));
// [ [0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9] ]

ユースケース。

・平均などの計算
・文脈依存アルゴリズム
・カルーセル

prior art

多言語。

language library chunks windows
C++ std::ranges::views chunk slide
Clojure core partition partition
Elm List.Extra groupsOf groupsOfWithStep
Haskell split chunksOf divvy
Java Stream Gatherers.windowFixed Gatherers.windowSliding
Kotlin Iterable chunked windowed
.NET System.Linq Enumerable.Chunk --
PHP array array_chunk --
Python itertools (3.12) batched
Python more-itertools grouper windowed
Ruby Enumerable each_slice each_cons
Rust Iterator array_chunks map_windows
Rust slice chunks windows
Scala Seq grouped sliding
Swift Sequence -- --

感想

先日紹介したJoint Iterationと似たような配列操作関数であり、実は提案者も同じだったりします。
このひと他にもIterator SequencingとかAsync Iterator Helpersとか配列関係のproposalばっかりやっていて、どんだけ配列好きなんだよ。

このIterator Chunkingについては、正直、どういうときに使うのかよくわかりません。
特にchunkingのほうは自力でも一瞬で書けますし。
sliding windowは尺取り法とかで使えるかもしれません。
それにしても使用場面が少なすぎる気はしますが。
ユースケースで紹介されている例はちょっとよくわかりませんでした。

2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?