multithreading
Version:
The missing standard library for multithreading in JavaScript (Works in the browser, Node.js, Deno, Bun).
50 lines (49 loc) • 1.62 kB
JavaScript
const CANDIDATES = [
"ArrayBuffer",
"MessagePort",
"ReadableStream",
"WritableStream",
"TransformStream",
"OffscreenCanvas",
"ImageBitmap",
"VideoFrame",
"AudioData",
"RTCDataChannel",
];
// Pre-compute the available constructors once.
// We use a dense array to avoid sparse array lookups.
const CONSTRUCTORS = [];
const G = globalThis;
for (let i = 0; i < CANDIDATES.length; i++) {
const ctor = G[CANDIDATES[i]];
if (typeof ctor !== "undefined") {
CONSTRUCTORS.push(ctor);
}
}
// Cache length to avoid property lookup in the hot loop
const LEN = CONSTRUCTORS.length;
// Cache ArrayBuffer specifically if it exists (it's index 0 usually)
// This allows a "Fast Path" for the most common transfer type.
const AB = G.ArrayBuffer;
class TransferableInstance {
static [Symbol.hasInstance](instance) {
// Fast Fail: Null check
if (!instance)
return false;
// Fast Fail: Primitive check
// "object" check excludes primitives. Transferables are never functions,
// and typeof function !== 'object', so this correctly filters functions too.
if (typeof instance !== "object")
return false;
// Fast Path: ArrayBuffer
// 90% of transferables are ArrayBuffers. Check this O(1) before entering the loop.
if (AB && instance instanceof AB)
return true;
for (let i = 0; i < LEN; i++) {
if (instance instanceof CONSTRUCTORS[i])
return true;
}
return false;
}
}
export const Transferable = TransferableInstance;