In this article, we study the packages/react/src/BadMapPolyfill.js file source code.
/**
* Copyright © Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* @flow
*/
export let hasBadMapPolyfill: boolean;
if (__DEV__) {
hasBadMapPolyfill = false;
try {
const frozenObject = Object.freeze({});
/* eslint-disable no-new */
new Map([[frozenObject, null]]);
new Set([frozenObject]);
/* eslint-enable no-new */
} catch (e) {
// TODO: Consider warning about bad polyfills
hasBadMapPolyfill = true;
}
}
Map’s been available across browsers since July 2015. The Map object holds key-value pairs and remembers the original insertion order of the keys.
This code above tries to create a new Map and new Set in a try block and if it fails, it is caught in the catch block and hasBadMapPolyfill
set to true, otherwise hasBadMapPolyfill
remains false.
eslint-enable no-new
ESLint docs states that no-new disallows new operators outside of assignments or comparisons. The goal of using new with a constructor is typically to create an object of a particular type and store that object in a variable, such as:
var person = new Person();
It’s less common to use new and not store the result, such as:
new Person();
This rule is aimed at maintaining consistency and convention by disallowing constructor calls using the new keyword that do not assign the resulting object to a variable.
Map and Set pollyfills:
Map in MDN docs provides a link to Map polyfill available in core-js
Set in MDN docs provides a link to Map polyfill available in core-js
Where is this hasBadMapPollyfill used?
hasBadMapPollyfill is used in /packages/react-reconciler/src/ReactFiber.js
Except the code you see in BadMapPollyfill is written here again. I do not know the reason why.
About me:
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.
I am open to work on an interesting project. Send me an email at ramu.narasinga@gmail.com
My Github - https://github.com/ramu-narasinga
My website - https://ramunarasinga.com
My Youtube channel - https://www.youtube.com/@thinkthroo
Learning platform - https://thinkthroo.com
Codebase Architecture - https://app.thinkthroo.com/architecture
Best practices - https://app.thinkthroo.com/best-practices
Production-grade projects - https://app.thinkthroo.com/production-grade-projects
References:
https://github.com/facebook/react/blob/main/packages/react/src/BadMapPolyfill.js
https://github.com/search?q=repo%3Afacebook%2Freact%20hasBadMapPolyfill&type=code
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
Top comments (0)