Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the type of a typedArray?

To test if an object is an array, there is a method -

const myarray = [1,2,3,4]; 
Array.isArray(myarray); 
//returns true

Is there a similar method for typed arrays (for example, Uint8Array)?

const int8 = new Uint8Array([0,1,2,3]);
Array.isArray(int8); //returns false

How can I find out if an object is a typed array, and what kind of typed array?

like image 990
NicoWheat Avatar asked Oct 18 '25 00:10

NicoWheat


1 Answers

You can use a comparison with its constructor 1:

const int8 = new Uint8Array([0,1,2,3]);
console.log(int8.constructor === Uint8Array);

// so you can do
function checkTypedArrayType(someTypedArray) {
  const typedArrayTypes = [
    Int8Array,
    Uint8Array,
    Uint8ClampedArray,
    Int16Array,
    Uint16Array,
    Int32Array,
    Uint32Array,
    Float32Array,
    Float64Array,
    BigInt64Array,
    BigUint64Array
  ];
  const checked = typedArrayTypes.filter(ta => someTypedArray.constructor === ta);
  return checked.length && checked[0].name || null;
}

console.log(checkTypedArrayType(int8));

// but this can be hugely simplified
function checkTypedArrayType2(someTypedArray) {
  return someTypedArray && 
    someTypedArray.constructor && 
    someTypedArray.constructor.name || 
    null;
}

console.log(checkTypedArrayType2(int8));

// which can actually be generalized to
const whatsMyType = someObject => 
  someObject && 
    someObject.constructor && 
    someObject.constructor.name && 
    someObject.constructor.name || 
    null;

console.log(whatsMyType(int8));
console.log(whatsMyType([1,2,3,4]));
console.log(whatsMyType("hello!"))
console.log(whatsMyType(/[a-z]/i))

1 Note that no version of Internet Explorer supports the name property. See MDN. See also

like image 135
KooiInc Avatar answered Oct 20 '25 13:10

KooiInc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!