Skip to content

Instantly share code, notes, and snippets.

@quickredfox
Created June 20, 2012 19:35
Show Gist options
  • Save quickredfox/2961735 to your computer and use it in GitHub Desktop.
Save quickredfox/2961735 to your computer and use it in GitHub Desktop.
CappedObject for Nic
var CappedObject = function( limit ){
items = {};
length = 0 ;
this.put = function( string ) {
if( items[string] ) return string;
items[string] = string;
length++;
if( length > limit ){
delete items[ Object.keys( items )[0]];
length --;
};
return string;
};
this.has = function( string ) {
return Boolean( items[string] );
};
this.getLength = function() {
return length
};
this.getItems = function() {
return Object.keys( items )
}
return this;
};
/* Usage */
var cache = new CappedObject( 2 );
cache.put( "Bleh Bleh")
console.log( cache.getLength())
cache.put( "Mah Mah")
console.log( cache.getLength())
cache.put( "Ooo Ooo")
console.log( cache.getLength())
cache.put( "Bleh Ooo")
console.log( cache.getLength())
console.log( cache.getItems())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment