Last active
October 20, 2015 16:18
-
-
Save karolk/1fc677a58bb7be9e4459 to your computer and use it in GitHub Desktop.
simple, but production ready implementation of memoisation in js
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
do () -> | |
getStorage = () -> | |
storage = | |
values: {} | |
isStored: (key) -> | |
key of @values | |
getValue: (key) -> | |
@values[key] | |
store: (key, value) -> | |
@values[key] = value | |
storage | |
memo = (origFn) -> | |
storage = getStorage() | |
wrappedFn = (key) -> | |
if storage.isStored key | |
return storage.getValue key | |
value = origFn.apply this, arguments | |
storage.store key, value | |
value | |
@memo = memo |
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
(function() { | |
function getStorage() { | |
var storage = { | |
values: {}, | |
isStored: function(key) {return key in storage.values}, | |
getValue: function(key) {return storage.values[key]}, | |
store: function(key, value) {storage.values[key] = value} | |
} | |
return storage | |
} | |
function memo(origFn) { | |
var storage = getStorage() | |
var wrappedFn = function(key) { | |
if (storage.isStored(key)) { | |
return storage.getValue(key) | |
} | |
var value = origFn.apply(this, arguments) | |
storage.store(key, value) | |
return value | |
} | |
return wrappedFn | |
} | |
this.memo = memo | |
})(this) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment