If you compare two arrays with the "==" operator, they will never be equal. These are different instances.
If you want to use an array object:
- Determine how two arrays are compared.
- Subclass Set and override the "has" method.
.
function eqArray (a1, a2) {
if (!(a1 instanceof Array && a2 instanceof Array))
return false;
if ( a1.length != a2.length)
return false;
for (var i = 0, n=a1.length; i < n; i++) {
if (a1[i] instanceof Array && a2[i] instanceof Array) {
if (!eqArray(a1[i], a2[i]))
return false;
}
else if (a1[i] != a2[i])
return false;
}
return true;
}
function MySet(elems) {
var set = new Set (elems);
set.__proto__ = MySet.prototype;
return set;
}
MySet.prototype = new Set;
MySet.prototype.has = function (elem) {
if (elem instanceof Array){
for (var v of this) {
if (v instanceof Array && eqArray(elem,v))
return true;
}
return false;
}else {
return Set.prototype.has.call (this, elem);
}
}
var a = new MySet();
a.add([1]);
a.has([1]);
eqArray([1],[1]);
source
share