Skip to content

Commit

Permalink
use native fn when possible
Browse files Browse the repository at this point in the history
  • Loading branch information
billyvg committed May 21, 2024
1 parent e9de4b7 commit c4cf4ec
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions packages/browser-utils/src/getNativeImplementation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ interface CacheableImplementations {

const cachedImplementations: Partial<CacheableImplementations> = {};

/**
* isNative checks if the given function is a native implementation
*/
// eslint-disable-next-line @typescript-eslint/ban-types
function isNative(func: Function): boolean {
return func && /^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString());
}

/**
* Get the native implementation of a browser function.
*
Expand All @@ -32,8 +40,14 @@ export function getNativeImplementation<T extends keyof CacheableImplementations
return cached;
}

const document = WINDOW.document;
let impl = WINDOW[name] as CacheableImplementations[T];

// Fast path to avoid DOM I/O
if (isNative(impl)) {
return (cachedImplementations[name] = impl.bind(WINDOW) as CacheableImplementations[T]);
}

const document = WINDOW.document;
// eslint-disable-next-line deprecation/deprecation
if (document && typeof document.createElement === 'function') {
try {
Expand Down Expand Up @@ -62,8 +76,7 @@ export function getNativeImplementation<T extends keyof CacheableImplementations

/** Clear a cached implementation. */
export function clearCachedImplementation(name: keyof CacheableImplementations): void {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete cachedImplementations[name];
cachedImplementations[name] = undefined;
}

/**
Expand Down

0 comments on commit c4cf4ec

Please sign in to comment.