Skip to content

Instantly share code, notes, and snippets.

@swannodette
Created August 11, 2009 08:38
Show Gist options
  • Save swannodette/165703 to your computer and use it in GitHub Desktop.
Save swannodette/165703 to your computer and use it in GitHub Desktop.
function() {
function $normalize(v) {
if($type(v) == "array")
{
v = v.normalize()
}
else if(['object', 'hash'].contains($type(v)))
{
v = $H(v).normalize();
}
return v;
}
function $hash(v) {
return JSON.encode($normalize(v));
};
Array.implement({
normalize: function() {
var result = [];
this.each(function(v) {
v = $normalize(v);
result.push(v);
});
return result;
}
});
Hash.implement({
normalize: function()
{
var result = [];
var sortArray = [];
this.each(function(v, k) {
sortArray.push(k);
});
sortArray.sort();
sortArray.each(function(k) {
var v = $normalize(this[k]);
result.push([k, v]);
}, this);
return result;
}
);
var Set = new Class({
initialize: function(ary)
{
this.isset = true;
this.rep = {};
if(ary && !ary.isset)
{
ary.each(function(v) {
this.rep[$hash(v)] = v;
}, this);
}
else if(ary)
{
this.rep = ary.rep;
}
},
put: function(v)
{
this.rep[$hash(v)] = v;
},
__put__: function(k, v)
{
this.rep[k] = v;
},
get: function(v)
{
return this.rep[$hash(v)];
},
remove: function(v)
{
delete this.rep[$hash(v)];
},
intersection: function(set)
{
var result = new Set();
set = new Set(set);
$H(this.rep).getValues().each(function(value) {
var hashed = $hash(value);
if(set.rep[hashed]) result.rep[hashed] = value;
}, this);
return result;
},
difference: function(set)
{
var result = new Set();
set = new Set(set);
$H(this.rep).getValues().each(function(value) {
var hashed = $hash(value);
if(!set.rep[hashed]) result.rep[hashed] = value;
}, this);
$H(set.rep).getValues().each(function(value) {
var hashed = $hash(value);
if(!this.rep[hashed]) result.rep[hashed] = value;
}, this);
return result;
},
union: function(set)
{
var result = new Set();
$H(this.rep).each(function(v, k) {
result.rep[k] = v;
}, this);
set.each(function(v) {
result.rep[$hash(v)] = v;
});
return result;
},
getValues: function()
{
return $H(this.rep).getKeys();
},
toArray: function()
{
return $H(this.rep).getValues();
}
});
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment