Skip to content

Instantly share code, notes, and snippets.

@rotu
Created September 13, 2023 08:38
Show Gist options
  • Save rotu/9a452f418b442eeba722c6a9fba68e98 to your computer and use it in GitHub Desktop.
Save rotu/9a452f418b442eeba722c6a9fba68e98 to your computer and use it in GitHub Desktop.
Minimal ArrayBufferView compatible with DataVIew methods
// `extends null` isn't necessary but I prefer it.
class BareDataView extends null {
static fromBuffer(...args) {
// construct a new object, passing args to the DataView() constructor
// but use this (i.e. the BareDataView class) to set the prototype
return Reflect.construct(DataView, args, this)
}
}
// Select only the properties we actually want to expose
// i.e. those that are part of the ArrayBufferView interface
for (const prop of ['buffer', 'byteLength', 'byteOffset']) {
const descriptor = Object.getOwnPropertyDescriptor(DataView.prototype,prop)
Reflect.defineProperty(BareDataView.prototype, prop, descriptor)
}
// Set up some nicely chosen bytes
let myBytes = new Uint8Array([0xff,0xff,0x00,0x84,0x5f,0xed,0xff,0xff])
let b = BareDataView.fromBuffer(myBytes.buffer)
// it has the buffer property!
console.log('buffer' in b) // true
// it doesn't have other DataView member!
console.log('getUint32' in b) // false
// but we can still use DataView methods
console.log(Reflect.apply(DataView.prototype.getUint32, b, [2])) // 8675309
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment