Jonny Piazzi
Jonny Piazzi

Reputation: 3784

Extending All Javascript Arrays at Once

I have an application using simple arrays (Array) and typed arrays (TypedArray).

I developed some needed extensions to the array types like (min, max, sum, ...).

But here's the tricky part: how define the created functions for all arrays in javascript?

If was some inheritance hierarchy between all of them, this problem would be more simpler. But so far I found no greater parent class.

For now I'm doing this:

// MIN FUNCTION
Array              .prototype.min =
Int8Array          .prototype.min =
Int16Array         .prototype.min =
Int32Array         .prototype.min =
Uint8Array         .prototype.min =
Uint16Array        .prototype.min =
Uint32Array        .prototype.min =
Uint8ClampedArray  .prototype.min =
Float32Array       .prototype.min =
Float64Array       .prototype.min = function () {
    // my code;
}

// MAX FUNCTION
Array              .prototype.max =
Int8Array          .prototype.max =
Int16Array         .prototype.max =
Int32Array         .prototype.max =
Uint8Array         .prototype.max =
Uint16Array        .prototype.max =
Uint32Array        .prototype.max =
Uint8ClampedArray  .prototype.max =
Float32Array       .prototype.max =
Float64Array       .prototype.max = function () {
    // my code;
}

// GO ON...

This is so monstrously ugly to look that I want to rip my eyes out.

How can I improve that? There is something to connect all these types to be used?

EDITED QUESTION:
How can I write this code without explicitly writing all types of javascript array?

Upvotes: 2

Views: 146

Answers (2)

Jimish Fotariya
Jimish Fotariya

Reputation: 1097

If you are going to us this in browser, then you can get a list of available arrays from window object itself.

var availableAr = [];
Object.getOwnPropertyNames(window).forEach(function(name){	
	if( name.toString().indexOf('Array')!== -1 ){
     	 availableAr.push( name.toString() )
    }
})
console.log(availableAr);
console.log( 
        new window[ availableAr[0] ]()
  );

Upvotes: 0

Petr Skocik
Petr Skocik

Reputation: 60058

This appears to work:

function arMax(){
    var len = this.length;
    var i;
    var max=-Infinity;
    for(i=0;i<len;i++)
        if(this[i]>max)
            max=this[i];
    return max;
}
function arMin(){
    var len = this.length;
    var i;
    var min=+Infinity;
    for(i=0;i<len;i++)
        if(this[i]<min)
            min=this[i];
    return min;
}
for(tp of [ 
    Array, 
    Int8Array, 
    Int16Array,
    Int32Array,
    Uint8Array,
    Uint16Array,
    Uint32Array,
    Uint8ClampedArray,
    Float32Array,
    Float64Array,
]){
    tp.prototype.max = arMax;
    tp.prototype.min = arMin;
}

console.log([ 2, 34, 3, 2, -43, -1 ].max())
console.log([ 2, 34, 3, 2, -43, -1 ].min())

Upvotes: 3

Related Questions