— JavaScript — 1 min read
Recently I have experienced the real pain of polyfilling Number.isSafeInteger method.
What is a polyfill?A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it.
It happened at work; something was not working for IE 11, and there was a lot of culprit pull requests, but one in particular sparkled my attention. In this pull request, there was a line of code that was using Number.isSafeInteger.
1return arr.filter(Number.isSafeInteger);
Nothing special, until I checked the famous browser compatibility tables of MDN web docs to confirm that my theory was real, Number.isSafeInteger
is not supported in IE, oh snap.
I ran to the polyfill section, I copied out the recommended polyfill code, and I victoriously announced to my team, "I found it!".
1Number.isSafeInteger =2 Number.isSafeInteger ||3 function (value) {4 return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;5 };
Not that simple, it turns out that Number.isInteger was also not supported and we had no polyfill again for it. I did not want to commit the same mistake twice, so this time I double-checked the source code of the polyfill for Number.isInteger
.
1Number.isInteger =2 Number.isInteger ||3 function (value) {4 return typeof value === "number" && isFinite(value) && Math.floor(value) === value;5 };
So guess what? Yes, Number.isFinite is also not supported in IE!
1if (Number.isFinite === undefined)2 Number.isFinite = function (value) {3 return typeof value === "number" && isFinite(value);4 };
You maybe think that's it, he finished with polyfilling madness. I thought the same, I don't blame you. Do you remember the original method that I was desperately trying to polyfill?
1Number.isSafeInteger =2 Number.isSafeInteger ||3 function (value) {4 return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;5 };
It happens that Number.MAX_SAFE_INTEGER is also not supported on IE, so I had to polyfill that as well.
1if (!Number.MAX_SAFE_INTEGER) {2 Number.MAX_SAFE_INTEGER = 9007199254740991; // Math.pow(2, 53) - 1;3}
If you liked this article, consider sharing (tweeting) it to your followers.