3 ms·
To make my point clear, here is a question. What is wrong with the following function that counts the number of unique strings in a list of strings? functi
by amelius 11y ago
To make my point clear, here is a question. What is wrong with the following function that counts the number of unique strings in a list of strings?
function count_unique_strings(l)
{
var m = {};
l.forEach(function(s)
{
m[s] = true;
});
var count = 0;
for(var k in m) ++count;
return count;
}
To see why this function is incorrect, run it with the following input:
console.log(count_unique_strings(["alpha", "bravo", "bravo", "charlie"]));
console.log(count_unique_strings(["alpha", "bravo", "bravo", "__proto__"]));
- dchest 11y agoWhat is wrong with the following function The implementation is wrong: you're using Object when you want to use Map. Object is not suitable for this, and seems like you know it, and it's in language specs.
- amelius 11y agoYes, I stated beforehand that the implementation is wrong. My point is that it is not obvious from the implementation (and certainly not for beginners).
- deleted 11y ago[deleted]