Search code examples
javascriptes6-map

ES6 Map, showing exception intermittently , Uncaught TypeError: map.put is not a function


Few weeks back map.put used to work, but now we get this error message intermittently :

var mapTypeSubtype = new Map();
Uncaught TypeError: mapTypeSubtype.put is not a function
    at Test.js:411
    at Array.forEach (<anonymous>)
    at objGenericListener (Test.js:410)

Is this an issue from Javascript api side? I saw the documentation and there is no method like .put , it has been changed to .set. But the strange thing is put used to work without any issues, but now its intermittently working. Any suggestions? To change it to .set it will be a big change for us as we have used maps in many places in our project.

Update

After doing a lot of search from where the put method is introduced, I saw that there is a js which gets loaded in browser which is internal to salesforce. And this was defined in that.

Map.prototype.put = function(a, b) {
    a && "undefined" != typeof b && (a in this.map || this.size++,
    this.map[a] = b)
}

So i think this might not be loaded sometimes which is breaking our implementation.

Thanks


Solution

  • As you knew that there is not any put method in the Map class, as the @Mahendra Pratap mentioned on ES6 document (https://www.ecma-international.org/ecma-262/6.0/#sec-map-constructor).

    You can run something like below script before using Map to prevent refactoring your project:

    Map.prototype.put = function(key, value){
        return this.set(key, value);
    }
    

    More details

    Some Guesses of Why your code working:

    • Maybe there is Map.prototype.put somewhere on your project or in the included libraries.
    • There is put method in the HashMap class in the java not in the javascript. Make sure you are using javascript.
    • You can find some implementation of HashMap in javascript here: JavaScript Hashmap Equivalent