Added a Set data structure.

This commit is contained in:
Richard Davey 2016-11-30 00:18:23 +00:00
parent 8d01f78a66
commit e34d53a969

108
v3/src/structs/Set.js Normal file
View file

@ -0,0 +1,108 @@
var Set = function ()
{
this.values = [];
};
Set.prototype.constructor = Set;
Set.prototype = {
add: function (value)
{
if (this.values.indexOf(value) === -1)
{
this.values.push(value);
}
},
delete: function (value)
{
var index = this.values.indexOf(value);
if (index > -1)
{
this.values.splice(index, 1);
}
},
clear: function ()
{
this.values.length = 0;
},
contains: function (value)
{
return (this.values.indexOf(value) > -1);
},
union: function (set)
{
var newSet = new Set();
set.values.forEach(function (value)
{
newSet.add(value);
});
this.values.forEach(function (value)
{
newSet.add(value);
});
return newSet;
},
intersect: function (set)
{
var newSet = new Set();
this.values.forEach(function (value)
{
if (set.contains(value))
{
newSet.add(value);
}
});
return newSet;
},
difference: function (set)
{
var newSet = new Set();
this.values.forEach(function (value)
{
if (!set.contains(value))
{
newSet.add(value);
}
});
return newSet;
}
};
Object.defineProperties(Set.prototype, {
length: {
writable: true,
enumerable: false,
get: function ()
{
return this.values.length;
},
set: function (value)
{
return this.values.length = value;
}
}
});
module.exports = Set;