では、巨大配列で 先頭削除・追加(キュー操作) を進捗付きで安全に処理するブラウザ用サンプルを作ります。
例:先頭削除・末尾追加を進捗バー付きで処理(100万件)
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>巨大配列キュー処理デモ</title>
<style>
#progress {
width: 100%;
background-color: #eee;
border-radius: 5px;
overflow: hidden;
margin: 10px 0;
}
#bar {
height: 20px;
background-color: #2196F3;
width: 0%;
}
</style>
</head>
<body>
<h1>巨大配列キュー処理デモ</h1>
<div id="progress"><div id="bar"></div></div>
<p id="status">準備中...</p>
<script>
// FastQueue クラスを使用
class FastQueue {
constructor() {
this.data = [];
this.head = 0;
}
enqueue(value) {
this.data.push(value); // 末尾追加
}
dequeue() {
if (this.head >= this.data.length) return undefined;
return this.data[this.head++]; // 先頭削除はコピー不要
}
size() {
return this.data.length - this.head;
}
}
// 100万件のキューを作成
let q = new FastQueue();
const size = 1000000;
for (let i = 0; i < size; i++) q.enqueue(i);
const chunk = 10000; // 1万件ずつ処理
let processed = 0;
function processChunk() {
for (let i = 0; i < chunk && q.size() > 0; i++) {
let v = q.dequeue();
q.enqueue(v * 2); // 末尾追加(加工して戻す)
}
processed += chunk;
// 進捗バー更新
const percent = Math.min(100, Math.floor((processed / size) * 100));
document.getElementById('bar').style.width = percent + '%';
document.getElementById('status').textContent = `処理中... ${percent}%`;
if (q.size() > 0) {
setTimeout(processChunk, 0); // 次のチャンクを処理
} else {
document.getElementById('status').textContent = `完了! 残りサイズ = ${q.size()}`;
}
}
// スタート
processChunk();
</script>
</body>
</html>
HTMLポイント解説
- FastQueue を使って先頭削除を高速化
- shift を使わず、
headインデックスをずらすだけ - 巨大配列でも O(1) で先頭削除が可能
- shift を使わず、
- 末尾追加も高速
- push は元々高速なので、大量追加でも問題なし
- チャンク処理でブラウザが固まらない
- 一度に全処理せず、
chunkごとにsetTimeoutで分割 - UI の更新(進捗バー)も可能
- 一度に全処理せず、
- 進捗バーで可視化
- ユーザーに「処理が進んでいる」ことを知らせられる
- メモリ効率が良い
- 中間配列は作らず、元配列を直接操作
- 巨大データでもメモリ消費を抑えられる
💡 このサンプルを応用すると、
- 巨大配列のリアルタイム処理(ゲームのスコア計算、ログ集計など)
- Webブラウザでの安全な大量データ処理
- データストリームをキューで扱う処理
などに応用できます。


