Created
March 10, 2015 11:51
-
-
Save bennadel/d17e8fc18daf0104d453 to your computer and use it in GitHub Desktop.
Using Method Chaining With The Revealing Module Pattern In JavaScript
This file contains 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
// 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
Thank you 🙌