Skip to content

Commit

Permalink
fix: fix browser support (#172)
Browse files Browse the repository at this point in the history
Signed-off-by: Jérôme Benoit <jerome.benoit@piment-noir.org>
  • Loading branch information
jerome-benoit authored Oct 29, 2024
1 parent 88fab00 commit f94c42c
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,32 @@
import { emptyFunction, tTable } from './constants';
import type { Fn, Statistics } from './types';

/**
* The JavaScript runtime environment.
*/
enum JSRuntime {
bun = 'bun',
deno = 'deno',
node = 'node',
browser = 'browser',
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
const isBun = !!(globalThis as any).Bun || !!globalThis.process.versions.bun;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
const isDeno = !!(globalThis as any).Deno;
const isNode = globalThis.process.release.name === 'node';
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
const isBrowser = !!(globalThis as any).navigator;

const runtime: JSRuntime | 'unknown' = (() => {
if (isBun) return JSRuntime.bun;
if (isDeno) return JSRuntime.deno;
if (isNode) return JSRuntime.node;
if (isBrowser) return JSRuntime.browser;
return 'unknown';
})();

/**
* Converts nanoseconds to milliseconds.
*
Expand All @@ -17,7 +43,14 @@ export const nToMs = (ns: number) => ns / 1e6;
*/
export const mToNs = (ms: number) => ms * 1e6;

const hrtimeBigint = process.hrtime.bigint.bind(process.hrtime);
let hrtimeBigint: () => bigint;
if (runtime === JSRuntime.browser) {
hrtimeBigint = () => {
throw new Error('hrtime.bigint() is not supported in this JS environment');
};
} else {
hrtimeBigint = process.hrtime.bigint.bind(process.hrtime);
}
export const hrtimeNow = () => nToMs(Number(hrtimeBigint()));

const performanceNow = performance.now.bind(performance);
Expand Down

0 comments on commit f94c42c

Please sign in to comment.