Skip to content

Instantly share code, notes, and snippets.

@klequis
Last active October 27, 2021 23:30
Show Gist options
  • Save klequis/b5e0d580679c96abfee08e5942d10691 to your computer and use it in GitHub Desktop.
Save klequis/b5e0d580679c96abfee08e5942d10691 to your computer and use it in GitHub Desktop.
Calculate Fibbonacci numbers using Map() as memory cache
const fibTest = [
{
in: 0,
out: 0,
},
{
in: 1,
out: 1
},
{
in: 2,
out: 1
},
{
in: 3,
out: 2,
},
{
in: 4,
out: 3,
},
{
in: 5,
out: 5,
},
{
in: 6,
out: 8,
},
{
in: 7,
out: 13,
},
{
in: 8,
out: 21,
},
{
in: 9,
out: 34,
},
{
in: 10,
out: 55,
},
{
in: 11,
out: 89,
},
]
const memorize = (fn) => {
const map1 = new Map();
return n => {
const have = map1.get(n)
if (have === undefined) {
const newVal = fn(n)
map1.set(n, newVal)
return newVal
}
return have
}
}
const fib = (n) => {
if (n === 0) return 0
if (n === 1) return 1
return fibMem(n-1) + fibMem(n-2)
}
const fibMem = memorize(fib)
fibTest.forEach(f => {
const out = fibMem(f.in)
console.log(`expect ${f.out}, actual ${out}:`, f.out === out)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment