Skip to content

Instantly share code, notes, and snippets.

@karolk
Last active October 20, 2015 16:18
Show Gist options
  • Save karolk/1fc677a58bb7be9e4459 to your computer and use it in GitHub Desktop.
Save karolk/1fc677a58bb7be9e4459 to your computer and use it in GitHub Desktop.
simple, but production ready implementation of memoisation in js
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
(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