Skip to content

Instantly share code, notes, and snippets.

@gblazex
Last active August 29, 2015 14:02
Show Gist options
  • Save gblazex/12b9310aec60e1ddc8c0 to your computer and use it in GitHub Desktop.
Save gblazex/12b9310aec60e1ddc8c0 to your computer and use it in GitHub Desktop.
// JavaScript
function memoize(fn) {
var memo = {}
return function(x) {
return memo[x] || (memo[x] = fn(x))
}
}
// Swift
func memoize<T: Hashable, U>( body: ((T)->U, T)->U ) -> (T)->U {
var memo = Dictionary<T, U>()
var result: ((T)->U)!
result = { x in
if let q = memo[x] { return q }
let r = body(result, x)
memo[x] = r
return r
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment