Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Fibonacci solution w/ recursion and memoization #268

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add recursive Fibonacci function using memoization
mateusmlo authored Dec 12, 2018

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
commit 4de64ad66a49d90f6640b738049e092d70133c92
19 changes: 19 additions & 0 deletions src/algorithms/math/fibonacci/fibonacciRecursiveMemoized.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//memoize function use a Map to store function arguments and results, which are returned if found inside cache
const memoize = fn => {
const cache = new Map();

return num => {
if (cache.has(num)) return cache.get(num);

const result = fn(num);
cache.set(num, result);
return result;
};
};

//fibonacci function decorated with the memoize function, every call will first pass through the cache before it's computed
const fibonacci = memoize(n => {
if (n === 0 || n === 1) return n;

return fibonacci(n - 1) + fibonacci(n - 2);
});