Make Set and Map initialization lazy

Reviewed By: javache

Differential Revision: D5461810

fbshipit-source-id: 6f22528bac4dd6e073e98a093e02d84114d0706a
This commit is contained in:
Alex Dvornikov 2017-07-24 07:09:37 -07:00 committed by Facebook Github Bot
parent 98258b437c
commit 0736f5d190
2 changed files with 28 additions and 6 deletions

View File

@ -128,10 +128,13 @@ if (!global.__fbDisableExceptionsManager) {
}
// Set up collections
// We can't make these lazy because `Map` checks for `global.Map` (which wouldc
// not exist if it were lazily defined).
defineProperty(global, 'Map', () => require('Map'), true);
defineProperty(global, 'Set', () => require('Set'), true);
const _shouldPolyfillCollection = require('_shouldPolyfillES6Collection');
if (_shouldPolyfillCollection('Map')) {
defineProperty(global, 'Map', () => require('Map'));
}
if (_shouldPolyfillCollection('Set')) {
defineProperty(global, 'Set', () => require('Set'));
}
// Set up Promise
// The native Promise implementation throws the following error:

View File

@ -16,7 +16,7 @@
* Checks whether a collection name (e.g. "Map" or "Set") has a native polyfill
* that is safe to be used.
*/
function shouldPolyfillES6Collection(collectionName: string): boolean {
function _shouldActuallyPolyfillES6Collection(collectionName: string): boolean {
var Collection = global[collectionName];
if (Collection == null) {
return true;
@ -43,4 +43,23 @@ function shouldPolyfillES6Collection(collectionName: string): boolean {
typeof proto.forEach !== 'function';
}
module.exports = shouldPolyfillES6Collection;
const cache: { [name: string]: bool } = {};
/**
* Checks whether a collection name (e.g. "Map" or "Set") has a native polyfill
* that is safe to be used and caches this result.
* Make sure to make a first call to this function before a corresponding
* property on global was overriden in any way.
*/
function _shouldPolyfillES6Collection(collectionName: string) {
let result = cache[collectionName];
if (result !== undefined) {
return result;
}
result = _shouldActuallyPolyfillES6Collection(collectionName);
cache[collectionName] = result;
return result;
}
module.exports = _shouldPolyfillES6Collection;