Skip to content

Instantly share code, notes, and snippets.

@blackakula
Created April 9, 2018 22:08
Show Gist options
  • Save blackakula/02fdbacb911a1f421aa6edd1bde1e89d to your computer and use it in GitHub Desktop.
Save blackakula/02fdbacb911a1f421aa6edd1bde1e89d to your computer and use it in GitHub Desktop.
Functional programming: Fibonacci function with memoization (n=8)
const resultCombination = cache => result => (getResult = true) => getResult ? result : cache
const cacheResult = ({resultCombination}) => result => n => resultCombination({...result(false), [n]: result()})(result())
const memoize = ({resultCombination, cacheResult}) => cache => f => n => cache.hasOwnProperty(n)
? resultCombination(cache)(cache[n])
: cacheResult({resultCombination})(f(cache)(n))(n)
const fib2 = ({resultCombination, cacheResult, memoize}) => f1Result => f => n => resultCombination(f1Result(false))(f1Result() + memoize({resultCombination, cacheResult})(f1Result(false))(f)(n - 2)())
const fib = ({resultCombination, cacheResult, memoize, fib2}) => cache => n => n === 1 || n === 2
? resultCombination(cache)(1)
: fib2({resultCombination, cacheResult, memoize})(memoize({resultCombination, cacheResult})(cache)(fib({resultCombination, cacheResult, memoize, fib2}))(n - 1))(fib({resultCombination, cacheResult, memoize, fib2}))(n)
console.log('THE RESULT: ' + fib({
resultCombination,
cacheResult: ({resultCombination}) => result => n => {
console.log(`Caching result: f(${n})=${result()}`)
return cacheResult({resultCombination})(result)(n)
},
memoize: ({resultCombination, cacheResult}) => cache => f => n => {
console.log(cache.hasOwnProperty(n) ? `Cache hit for n=${n}` : `Calculating value for f(${n})`)
return memoize({resultCombination, cacheResult})(cache)(f)(n)
},
fib2
})({})(8)(true))
// Calculating value for f(7)
// Calculating value for f(6)
// Calculating value for f(5)
// Calculating value for f(4)
// Calculating value for f(3)
// Calculating value for f(2)
// Caching result: f(2)=1
// Calculating value for f(1)
// Caching result: f(1)=1
// Caching result: f(3)=2
// Cache hit for n=2
// Caching result: f(4)=3
// Cache hit for n=3
// Caching result: f(5)=5
// Cache hit for n=4
// Caching result: f(6)=8
// Cache hit for n=5
// Caching result: f(7)=13
// Cache hit for n=6
// THE RESULT: 21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment