Skip to content

Instantly share code, notes, and snippets.

@eligrey
Last active September 1, 2023 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eligrey/c5a252f1f48cbdd8bf2b344b4ddaea65 to your computer and use it in GitHub Desktop.
Save eligrey/c5a252f1f48cbdd8bf2b344b4ddaea65 to your computer and use it in GitHub Desktop.
lock well-known built-in JS iterable prototypes
const freezeProp = <T = any>(
object: T,
property: string | symbol | number,
value = (object as any)[property],
): T =>
Object.defineProperty(object, property, {
value,
configurable: false,
writable: false,
enumerable: false,
});
const tamperResist = (): void => {
const { childNodes: nodeList, children: htmlCollection } = document.createDocumentFragment();
[
[],
new Set(),
new Map(),
nodeList,
document.createElement('_').classList,
htmlCollection,
'',
].forEach((iterable) => {
freezeProp(Object.getPrototypeOf(iterable), Symbol.iterator);
Object.freeze(Object.getPrototypeOf(iterable[Symbol.iterator]()));
});
// proposed base iterator prototype API: https://github.com/tc39/proposal-iterator-helpers#extending-iterator-prototype
const baseIteratorPrototype = (self as any)?.Iterator?.prototype;
if (baseIteratorPrototype) {
Object.freeze(baseIteratorPrototype);
}
}
@eligrey
Copy link
Author

eligrey commented Sep 1, 2023

do not use with old versions of regenerator runtime: tc39/proposal-iterator-helpers#286

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment