Does Js Set.has() Method Do Shallow Checks?
Solution 1:
According to docs:
The Set object lets you store unique values of any type, whether primitive values or object references.
As you are adding objects, their references will be stored internally and your check will return false
because your are passing different object to has
method.
Actually, your case is even covered in the Examples section of the has method reference.
Solution 2:
In regards to objects, Sets handle unique references.
new Set([ {a: 1}, {a: 1} ])
has two items.
var x = {a: 1}; new Set([ x, x ]);
has one item.
There is no way to have Set use a custom comparison function.
Solution 3:
It's expected that any native JavaScript API compare objects by their references and not their contents (including shallow comparison):
({a:1,b:2})!==({a:1,b:2})
Set
isn't an exclusion, it does ===
comparison for every value but NaN
when it looks up values with has
or stores unique values.
This could be achieved by extending Set
and using deep comparison in has
, etc. methods but it would be inefficient.
A more efficient way is to use Map
instead, because entries should be stored and retrieved by normalized keys, but actual objects are supposed to be stored. This can be done by using JSON.stringify
, but object keys should be preferable sorted as well, so third-party implementation like json-stable-stringify
may be used.
At this point there are may be not much benefits from extending either Set
or Map
because most methods should be overridden:
classDeepSet{
constructor (iterable = []) {
this._map = new Map();
for (const v of iterable) {
this.add(v);
}
}
_getNormalizedKey(v) {
// TODO: sort keysreturn (v && typeof v === 'object') ? JSON.stringify(v) : v;
}
add(v) {
this._map.set(this._getNormalizedKey(v), v);
returnthis;
}
has(v) {
returnthis._map.has(this._getNormalizedKey(v));
}
// etc
}
Notice that this set is intended only for plain objects that can be correctly serialized to JSON. There may be other ways to serialize object contents but none of them will handle all possible values correctly, e.g. symbols and class instances.
Solution 4:
You can't compare references like arrays and objects for equality. You can compare values though!!!
const s = new Set();
let a = {a: 1, b:2};
let b = {a: 2, b: 3};
s.add(a);
s.add(b);
s.has(a); //true
Post a Comment for "Does Js Set.has() Method Do Shallow Checks?"