I have been working on developing a function that will return true
if the argument provided to it is an instance of a JavaScript Map.
When we use typeof new Map()
, the returned value is object
and there isn't a built-in Map.isMap
method available.
Here is the code snippet I have come up with:
function isMap(v) {
return typeof Map !== 'undefined' &&
Map.prototype.toString.call(v) === '[object Map]' ||
v instanceof Map;
}
(function test() {
const map = new Map();
write(isMap(map));
Map.prototype.toString = function myToString() {
return 'something else';
};
write(isMap(map));
}());
function write(value) {
document.write(`${value}<br />`);
}
However, testing maps across frames and in cases where toString()
has been changed, the isMap
function fails (reasons explained here).
For example:
<iframe id="testFrame"></iframe>
<script>
const testWindow = document.querySelector('#testFrame').contentWindow;
// returns false when toString is overridden
write(isMap(new testWindow.Map()));
</script>
If you want to see a detailed demonstration of this issue, check out this Code Pen link.
I am looking for a way to modify the isMap
function so that it can accurately identify instances of Maps even when toString
is overridden or the map object is from another frame. Can this be achieved?