Node: [Feature Request] isTypedArray

Created on 27 May 2019  路  3Comments  路  Source: nodejs/node

Is your feature request related to a problem? Please describe.
Please describe the problem you are trying to solve.

The crypto module provides many functions (example) which take string | Buffer | TypedArray | DataView.

Currently, we can check if strings easily by using:

typeof someVariable === 'string'

We can check for Buffers using:

Buffer.isBuffer(someVariable)

We can also check if something is a DataView via:

someVariable instanceof DataView

It would be nice if we also had a util function to check if something is any one of the many TypedArray variants as well.

Describe the solution you'd like
Please describe the desired behavior.

function isTypedArray(obj) {
  return obj instanceof UInt8Array ||
    obj instanceof Uint8ClampedArray ||
    obj instanceof Uint16Array // and so on
}

Describe alternatives you've considered
Please describe alternative solutions or features you have considered.

A visible TypedArray constructor to allow:

someVariable instanceof TypedArray
question

Most helpful comment

we actually have util.types.isTypedArray, gonna close this out as it exists.

All 3 comments

function isTypedArray(obj) {
  return obj instanceof UInt8Array ||
    obj instanceof Uint8ClampedArray ||
    obj instanceof Uint16Array // and so on
}

FWIW, if you're rolling your own function or if you want to publish an npm module for this, it's probably better as something like this:

const TypedArray = Object.getPrototypeOf(Int8Array);
function isTypedArray(obj) { return obj instanceof TypedArray; }

That will be both more concise and more future-proof if further TypedArray variants are added to the language.

we actually have util.types.isTypedArray, gonna close this out as it exists.

Thanks a lot! Can't believe I overlooked that.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

akdor1154 picture akdor1154  路  3Comments

srl295 picture srl295  路  3Comments

cong88 picture cong88  路  3Comments

dfahlander picture dfahlander  路  3Comments

danielstaleiny picture danielstaleiny  路  3Comments