When I use Set
and Map
objects in javascript, I chronically say the wrong thing:
set.length
when I meanset.size
map.length
when I meanmap.size
map.someKeyName
ormap['someKeyName']
when I meanmap.get('someKeyName')
map.someKeyName=someValue
ormap['someKeyName']=someValue
when I meanmap.set('someKeyName', someValue)
The result is a passive-aggressive undefined
or silently failing to do what I wanted, which wastes my time.
How hard would it be to make some kind of slightly-altered version of Set
and Map
that throw an Error
when I try to do any of those bad things?
Here's something that seems to do exactly what I want (tested on Chrome 59). Most of it is thanks to @T.J.Crowder 's answer here ; I had to add a special case for the
size
property for some reason.Caveat: MDN says
Map
has alength
property that's always 0. I think it's lying; or, at least, it's wrong on Chrome 59 where I'm testing it, so when I access thelength
property on my proxy object it fails with "No length for you!" as desired. It would be probably be safer to special case it to guarantee that it fails as desired regardless of whether the underlyingMap
has alength
.