Skip to content

Instantly share code, notes, and snippets.

@thejefflarson

thejefflarson/set.js

Created Jun 17, 2010
Embed
What would you like to do?
// A Set implementation. If you create a set with a particular length it
// will be capped at that length. The array is kept in order of addition.
propublica.models.Set = propublica.Model.extend({
init : function(vals, cap){
this._super();
this._attrs.values = [];
this._attrs.values = vals;
this._commit();
this.setCap(cap);
},
unshift : function(value){
this._attrs.values.unshift(value);
this._commit();
return this.indexOf(value);
},
push : function(value){
this._attrs.values.push(value);
this._commit();
return this.indexOf(value);
},
del : function(value){
this._attrs = _.without(this._attrs.values, value);
this._commit();
return value;
},
empty : function(){
return this._attrs.values.length > 0;
},
size : function(){
return this._attrs.values.length;
},
capacity : function(){
return this.cap || -1;
},
pop : function(){
var val = this._attrs.values.pop();
this._commit();
return val;
},
find : function(item){
return this.indexOf(item) > -1 ? this._attrs.values[this.indexOf(item)] : null;
},
indexOf : function(item){
return _.indexOf(this._attrs.values, item);
},
empty : function(){
this._attrs.values.length = 0;
},
values : function(){
return this._attrs.values;
},
setCap : function(cap){
if(cap) this.cap = cap;
this._commit();
},
union : function(other_set){
return new (this.init)(_.uniq(this._attrs.values, other_set));
},
intersect : function(other_set){
return new (this.init)(_.intersect(this._attrs.values, other_set));
},
_cap : function(){
if(this.cap) this._attrs.values = this._attrs.values.slice(0, this.cap);
},
_commit : function(){
this._attrs.values = _.uniq(this._attrs.values);
this._cap();
this.length = this._attrs.values.length;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.