Set.prototype.has () with predicate

var myset = new Set();
    
myset.add({ key: 123, value: 100 });
var has = myset.has({ key: 123, value: 100 });    
console.log(has); // false
       
var obj = {
    key: 456,
    value: 200
};

myset.add(obj);
has = myset.has(obj);
console.log(has); // true
    
has = myset.has(x => x.key === 123);    
console.log(has); // false
Run codeHide result

The problem in this case: I just add { key: 123, value: 100 }in myset, why doesn't it contain { key: 123, value: 100 }?

Another case, if I use objinstead { key: 123, value: 100 }, it will return true.

Set.prototype.has () says:

The has () method returns a boolean value indicating whether an element with the specified value exists in the Set object or not.

But this does not mean that specified value:?

It is clear that in this case { key: 123, value: 100 }both are { key: 123, value: 100 }similar, and .... I get false. So what is specifiedhere?

And the second question: why don't they support the method predicatein has()?

In my example. It is harder to search if I use for...of...:

for (let obj of myset) {
    if (obj.key === 123) return true;
}

While it can be built in with prediction:

has = myset.has(x => x.key === 123)

, ?

+4
2

{ key: 123, value: 100 } === { key: 123, value: 100 } false, JavaScript . , , , .

var a = {};
var b = a;
a === b; // true 

true, . , a b - , a b.

a.x = 1;
b.x === 1; // true

myset.has(x => x.key === 123) , , . , has , , , .

+1

Set.prototype.has , , :

{ key: 123 } !== { key: 123 } // true

, . , , , Set , . , .

, Array.prototype.find:

Set.prototype.find = function () {
    return Array.prototype.find.apply([...this], arguments);
};
+1

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


All Articles