Double search vs undefined in JavaScript Map: TryGet wanted

The JavaScript map has 2 get and has methods. The get method returns undefined if the element does not exist , or if the undefined value has been added to the map .

So, if I implement my GetAlways method or one that returns an existing one or adds a new one and returns, if not, then I am stuck with the choice of sacrificial performance at runtime, providing a dual search map or sacrificing an API cleanliness equating undefined to nonexistence on the map and thereby effectively prohibiting the safe addition of undefined values ​​to the map.

Is there a third efficient and clean choice similar to TryGet from C # ?

Code for unclean choices:

Map.prototype.GetAlways = function(name){ let child = this.get(name); if (child === undefined){ // equating undefined value to non-existence child = {}; this.set(name, child); } return child; } 

Code for slow selection:

 Map.prototype.GetAlways = function(name){ if(this.has(name)) // first map seek return this.get(name); // second map seek let child = {}; this.set(name, child); return child; } 
+5
source share
1 answer

undefined means no parameter. The only cases where it is justifiable to use is to check if an argument is missing or the function returns nothing. If someone passes undefined to your card, it is not your problem what happens.

If this bothers you, try making JS with a C ++ mentality: explicitly write in your documentation what is expected and what you guarantee. Then you do not need to spend time (and code performance) on testing these incorrect parameters. This is what we call separation of concerns.

... so I answer: do not try to allow undefined to be saved on the map, but do not do anything to prevent it in the code. Just ignore the edge case and say that people are forbidden.

+2
source

Source: https://habr.com/ru/post/1258185/


All Articles