Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created March 10, 2015 11:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bennadel/d17e8fc18daf0104d453 to your computer and use it in GitHub Desktop.
Save bennadel/d17e8fc18daf0104d453 to your computer and use it in GitHub Desktop.
Using Method Chaining With The Revealing Module Pattern In JavaScript
// 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 );
}
}
@bgrand-ch
Copy link

Thank you 🙌

@bennadel
Copy link
Author

My pleasure :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment