Created
June 20, 2012 19:35
-
-
Save quickredfox/2961735 to your computer and use it in GitHub Desktop.
CappedObject for Nic
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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