LoginSignup
0
1

More than 5 years have passed since last update.

TypedArrayで非同期的にデータの切り貼り(splice等)をしたい

Posted at

もちろん、ガシガシ同期的にspliceを実装することもできるでしょう。ただ、この方法だと小さなデータなら良いでしょうが、巨大なデータをspliceする時には、長時間のブロッキングが起きてしまうので、望ましくありません。

そういう時は、非同期的にspliceと同等の処理を実装する方法があります。
1. subarrayで切り出し
2. Blobのコンストラクタでつなげて
3. readAsArrayBufferで新しいArrayBufferにデータをコピーします。
いずれの処理でも、同期的データのコピーは行われていないため、大きなデータでも問題なく動作します。

今回は、Array.prototype.spliceをエミュレートしましたが、Blob + readAsArrayBufferの応用範囲は広く、実際には、この方法を応用して、もっと自由な形で、TypeArrayを切り貼りする機会の方が多いかもしれません。TypedArrayの練習問題的な意味で・・・。

// eslint-disable-next-line max-params
const spliceTypedArray = (array, startIndex, count, ...insertion) => {
  const blob = new Blob([
    array.subarray(0, startIndex),
    new array.constructor(insertion),
    count != null ? array.subarray(startIndex + count) : null,
  ]);
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = eve => {
      resolve(new array.constructor(reader.result));
    };
    reader.onerror = eve => {
      reject(reader.error);
    };
    reader.readAsArrayBuffer(blob);
  });
};
0
1
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
0
1