Last active
November 13, 2024 08:15
-
-
Save greggman/a087a43f08f1f02c1934727dcbde971a to your computer and use it in GitHub Desktop.
Incomplete structured setter v1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const kTypedArrayConstructors = { | |
i8: Int8Array, | |
u8: Uint8Array, | |
i16: Int16Array, | |
u16: Uint16Array, | |
i32: Int32Array, | |
u32: Uint32Array, | |
f32: Float32Array, | |
f64: Float64Array, | |
i64: BigInt64Array, | |
u64: BigUint64Array, | |
}; | |
class StructuredAccessorFactory { | |
constructor(layout) { | |
const typedArraysTypes = [...new Set(Object.values(layout).map(({type}) => type))]; | |
const layoutArray = [...Object.entries(layout).map(([key, {type, byteOffset}]) => { | |
const arrayOffset = byteOffset / kTypedArrayConstructors[type].BYTES_PER_ELEMENT; | |
return { key, type, arrayOffset }; | |
})]; | |
this.create = function(buffer) { | |
const data = {}; | |
for (let i = 0; i < typedArraysTypes.length; ++i) { | |
const type = typedArraysTypes[i]; | |
data[type] = new kTypedArrayConstructors[type](buffer); | |
} | |
const accessor = {}; | |
for (let i = 0; i < layoutArray.length; ++i) { | |
const {key, type, arrayOffset} = layoutArray[i]; | |
const view = data[type]; | |
Object.defineProperty(accessor, key, { | |
enumerable: true, | |
get() { | |
return view[arrayOffset]; | |
}, | |
set(value) { | |
view[arrayOffset] = value; | |
}, | |
}); | |
} | |
return accessor; | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment