JAVASCRIPT   16

safe_globals.js

Guest on 15th May 2021 10:17:17 AM

  1. 'use strict';
  2.  
  3. const copyProps = (unsafe, safe) => {
  4.   for (const key of [...Object.getOwnPropertyNames(unsafe),
  5.                      ...Object.getOwnPropertySymbols(unsafe)
  6.   ]) {
  7.     if (!Object.getOwnPropertyDescriptor(safe, key)) {
  8.       Object.defineProperty(
  9.         safe,
  10.         key,
  11.         Object.getOwnPropertyDescriptor(unsafe, key));
  12.     }
  13.   }
  14. };
  15. const makeSafe = (unsafe, safe) => {
  16.   copyProps(unsafe.prototype, safe.prototype);
  17.   copyProps(unsafe, safe);
  18.   Object.setPrototypeOf(safe.prototype, null);
  19.   Object.freeze(safe.prototype);
  20.   Object.freeze(safe);
  21.   return safe;
  22. };
  23.  
  24. exports.SafeMap = makeSafe(Map, class SafeMap extends Map {});
  25. exports.SafeSet = makeSafe(Set, class SafeSet extends Set {});
  26. exports.SafePromise = makeSafe(Promise, class SafePromise extends Promise {});

Raw Paste


Login or Register to edit or fork this paste. It's free.