5
5

More than 5 years have passed since last update.

TypedArrayに便利なメソッドをつける

Posted at

TypedArrayを使っているときに、これあったら便利だよね的なメソッド(本当はこういうことはやらないほうがいいんだけど)。

javascript
(function(){

function TypedArrayMixin(){
    this.forEach = function(callback){
        for(var i = 0, n = this.length; i < n; ++i) callback(this[i], i);
    };

    this.map = function(callback, context){
        var ret = new this.constructor(this.length),
            i, n;
        for(i = 0, n = this.length; i < n; ++i) ret[i] = callback.call(context, this[i], i);
        return ret;
    };

    this.reduce = function(callback, initialValue){
        var current = this[0], i = 1, n;
        if(initialValue != null){
            current = initialValue;
            i = 0;
        }
        for(n = this.length; i < n; ++i) current = callback(current, this[i], i, this);
        return current;
    };

    this.copy = function(){
        return new this.constructor(this);
    };

    this.concat = function(){
        var length = this.length, offset = length, ret;
        Array.prototype.forEach.call(arguments, function(array){
            length += array.length;            
        });
        ret = new this.constructor(length);
        ret.set(this);
        Array.prototype.forEach.call(arguments, function(array){
            ret.set(array, offset);
            offset += array.length;
        });
        return ret;
    };

    this.toString = function(){
        var i, n, a = [];
        for(i = 0, n = this.length; i < n; ++i) a[i] = this[i];
        return a.toString();
    };
}

function setMixin(constructor, mixin){
    mixin.call(constructor.prototype);
}

var constructors = [
    Int8Array,
    Int16Array,
    Int32Array,
    Uint8Array,
    Uint16Array,
    Uint32Array,
    Float32Array
];
this.Float64Array || constructors.push(Float64Array);
this.Uint8ClampedArray || constructors.push(Uint8ClampedArray);

constructors.forEach(function(constructor){
    setMixin(constructor, TypedArrayMixin);
});

}).call(this);

forEach,map,reduceは速度的にあまり使えなさそうだけど、copy,concatは使いどころがあるかも。

たとえばcopyだと

javascript
var bytes = new Uint8Array(8);
bytes.set([1,2,3,4]);
var bb = new BlobBuilder;

//元のbufferを参照しているので想定とは違う結果に…(エラーでないし)。
bb.append(bytes.subarray(0, 4).buffer);
//byteLengthが4の新しいbuffer
bb.append(bytes.subarray(0, 4).copy().buffer);

concatだと

javascript
//arr = [bytes1, bytes2, bytes3, ...] こんな感じのUint8Arrayの配列があったとする
var bb = BlobBuilder;

//これよりも
arr.forEach(function(bytes){
    bb.append(bytes.buffer);
});

//大体こっちの方が速い
bb.append(Uint8Array.prototype.concat.apply(new Uint8Array(0), arr).buffer);
5
5
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
5
5