Skip to content

Commit

Permalink
fibonacci optimize with Memory pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
rajratnamaitry authored and mgechev committed Jul 20, 2022
1 parent a621820 commit 213636f
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/others/fibonacciMemory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Nth number of fibonacciMemory's sequence
*
* Returns the nth number of fibonacciMemory's sequence.
*
* @public
*
* @example
* var fibonacciMemory = require('path-to-algorithms/src/others/fibonacciMemory').fibonacciMemory;
* var nth = fibonacciMemory(20);
*
* console.log(nth); // 6765
*
* @param {Number} n The nth position in fibonacciMemory's sequence
*
* @module others/fibonacciMemory
*/
(function (exports) {
'use strict';

function fibonacciMemory(n) {
var i = 0;
var aux = [0, 1];
while (n != i) {
aux[i + 2] = aux[i] + aux[i + 1];
i++;
}
return aux[i];
}

exports.fibonacciMemory = fibonacciMemory;
})(typeof window === 'undefined' ? module.exports : window);
28 changes: 28 additions & 0 deletions test/others/fibonacciMemory.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
var mod = require('../../src/others/fibonacciMemory.js');
var fibonacci = mod.fibonacciMemory;

describe('fibonacci with Memory algorithm', function () {
'use strict';

it('should return value 1 with input 1.', function () {
expect(fibonacci(1)).toBe(1);
});
it('should return value 6 with input 8.', function () {
expect(fibonacci(6)).toBe(8);
});
it('should return value 7 with input 13.', function () {
expect(fibonacci(7)).toBe(13);
});
it('should return value 8 with input 21.', function () {
expect(fibonacci(8)).toBe(21);
});
it('should return value 9 with input 34.', function () {
expect(fibonacci(9)).toBe(34);
});
it('should return value 10 with input 55.', function () {
expect(fibonacci(10)).toBe(55);
});
it('should be 135301852344706760000 with input 98.', function () {
expect(fibonacci(98)).toBe(135301852344706760000);
});
});

0 comments on commit 213636f

Please sign in to comment.