Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Create an instance of our cache and set some keys. Notice that the [new] operator
// is optional since the SimpleCache (and revealing module pattern) doesn't use
// prototypical inheritance. And, we can use method-chaining to set the cache keys.
var cache = SimpleCache()
.set( "foo", "Bar" )
.set( "hello", "world" )
.set( "beep", "boop" )
;
console.log( cache.has( "beep" ) );
// ---------------------------------------------------------- //
// ---------------------------------------------------------- //
// I provide a super simple cache container.
function SimpleCache() {
// Create an object without a prototype so that we don't run into any cache-key
// conflicts with native Object.prototype properties.
var cache = Object.create( null );
// Reveal the public API.
return({
get: get,
has: has,
remove: remove,
set: set
});
// ---
// PUBLIC METHODS.
// ---
// I get the value cached at the given key; or, undefined.
function get( key ) {
return( cache[ key ] );
}
// I check to see if the given key has a cached value.
function has( key ) {
return( key in cache );
}
// I remove the given key (and associated value) from the cache.
// --
// NOTE: Returns [this] for method chaining.
function remove( key ) {
delete( cache[ key ] );
// CAUTION: In this context, [this] does not refer to the SimpleCache instance;
// rather, it refers to the public API that was "revealed". As such, method
// chaining can only work in conjunction with "public" methods.
return( this );
}
// I cache the given value at the given key.
// --
// NOTE: Returns [this] for method chaining.
function set( key, value ) {
cache[ key ] = value;
// CAUTION: In this context, [this] does not refer to the SimpleCache instance;
// rather, it refers to the public API that was "revealed". As such, method
// chaining can only work in conjunction with "public" methods.
return( this );
}
}
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.