Skip to content

Commit

Permalink
feat: fibonacci algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
francislagares committed Aug 22, 2023
1 parent 4345e0f commit cb9a1bc
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
41 changes: 41 additions & 0 deletions src/algorithms/fibonacci/fibonacci.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Option 1
export const fibonacci = (n: number) => {
const result = [0, 1];

for (let i = 2; i <= n; i++) {
const a = result[i - 1];
const b = result[i - 2];

result.push(a + b);
}

return result[n];
};

const memoize = (fn: (n: number) => number) => {
const cache: { [key: string]: number } = {};

return function (...args: number[]) {
const key = JSON.stringify(args);

if (cache[key]) {
return cache[key];
}

const result = fn.apply(this, args);
cache[key] = result;

return result;
};
};

const slowFib = (n: number) => {
if (n < 2) {
return n;
}

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

// Option 2
export const memoizedFib = memoize(slowFib);
33 changes: 33 additions & 0 deletions src/algorithms/fibonacci/tests/fibonacci.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { fibonacci, memoizedFib } from '../fibonacci';

describe('Fibonacci Algorithm', () => {
test('Fib function is defined', () => {
expect(typeof fibonacci).toEqual('function');
expect(typeof memoizedFib).toEqual('function');
});

test('calculates correct fibonacci value for 1', () => {
expect(fibonacci(1)).toEqual(1);
expect(memoizedFib(1)).toEqual(1);
});

test('calculates correct fibonacci value for 2', () => {
expect(fibonacci(2)).toEqual(1);
expect(memoizedFib(2)).toEqual(1);
});

test('calculates correct fibonacci value for 3', () => {
expect(fibonacci(3)).toEqual(2);
expect(memoizedFib(3)).toEqual(2);
});

test('calculates correct fibonacci value for 4', () => {
expect(fibonacci(4)).toEqual(3);
expect(memoizedFib(4)).toEqual(3);
});

test('calculates correct fibonacci value for 15', () => {
expect(fibonacci(39)).toEqual(63245986);
expect(memoizedFib(39)).toEqual(63245986);
});
});

0 comments on commit cb9a1bc

Please sign in to comment.