Sto cercando di estendere Array per creare un Set, ovvero una collezione che si comporti come un array ma che non inserisca duplicati.
Ho fatto cosi' ma qualcosa non funziona, cosa sbaglio? Come si puo' scrivere meglio?
codice:
Set.prototype = new Array();
function Set() {
Array.apply (this, arguments);
};
Set.prototype.push = function()
{
for (var a in arguments) {
var currentArg = arguments [a];
var equalFound = false;
for (var i in this) {
if (currentArg.equals && currentArg.equals (this[i])) {
equalFound = true;
//Continue with next arg
break;
}
}
if (!equalFound) {
Array.prototype.push.call (this, currentArg);
}
}
return this.length;
};
Set.prototype.unshift = function()
{
for (var a in arguments) {
var currentArg = arguments [a];
var equalFound = false;
for (var i in this) {
if (currentArg.equals && currentArg.equals (this[i])) {
equalFound = true;
//Continue with next arg
break;
}
}
if (!equalFound) {
Array.prototype.unshift.call (this, currentArg);
}
}
return this.length;
};
//Oggetto per il test
var TestObj = function (a1, a2)
{
this.f1 = a1;
this.f2 = a2;
this.toString = function()
{
return '(' + this.f1 + ',' + f2 + ')';
}
this.equals = function (obj)
{
if (obj instanceof TestObj) {
if (this.f1 === obj.f1 && this.f2 === obj.f2) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
};
//Lancio il test quando document.ready
$(function(){
var t1 = new TestObj ('A', 'B');
var t2 = new TestObj ('A', 'B');
var t3 = new TestObj ('A', 'C');
var t4 = new TestObj ('B', 'C');
var s = new Set();
s.push (t1);
s.push (t3, t4, t2);
console.log (s);
});