Skip to content

Commit 213636f

Browse files
rajratnamaitrymgechev
authored andcommitted
fibonacci optimize with Memory pattern
1 parent a621820 commit 213636f

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

src/others/fibonacciMemory.js

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Nth number of fibonacciMemory's sequence
3+
*
4+
* Returns the nth number of fibonacciMemory's sequence.
5+
*
6+
* @public
7+
*
8+
* @example
9+
* var fibonacciMemory = require('path-to-algorithms/src/others/fibonacciMemory').fibonacciMemory;
10+
* var nth = fibonacciMemory(20);
11+
*
12+
* console.log(nth); // 6765
13+
*
14+
* @param {Number} n The nth position in fibonacciMemory's sequence
15+
*
16+
* @module others/fibonacciMemory
17+
*/
18+
(function (exports) {
19+
'use strict';
20+
21+
function fibonacciMemory(n) {
22+
var i = 0;
23+
var aux = [0, 1];
24+
while (n != i) {
25+
aux[i + 2] = aux[i] + aux[i + 1];
26+
i++;
27+
}
28+
return aux[i];
29+
}
30+
31+
exports.fibonacciMemory = fibonacciMemory;
32+
})(typeof window === 'undefined' ? module.exports : window);

test/others/fibonacciMemory.spec.js

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
var mod = require('../../src/others/fibonacciMemory.js');
2+
var fibonacci = mod.fibonacciMemory;
3+
4+
describe('fibonacci with Memory algorithm', function () {
5+
'use strict';
6+
7+
it('should return value 1 with input 1.', function () {
8+
expect(fibonacci(1)).toBe(1);
9+
});
10+
it('should return value 6 with input 8.', function () {
11+
expect(fibonacci(6)).toBe(8);
12+
});
13+
it('should return value 7 with input 13.', function () {
14+
expect(fibonacci(7)).toBe(13);
15+
});
16+
it('should return value 8 with input 21.', function () {
17+
expect(fibonacci(8)).toBe(21);
18+
});
19+
it('should return value 9 with input 34.', function () {
20+
expect(fibonacci(9)).toBe(34);
21+
});
22+
it('should return value 10 with input 55.', function () {
23+
expect(fibonacci(10)).toBe(55);
24+
});
25+
it('should be 135301852344706760000 with input 98.', function () {
26+
expect(fibonacci(98)).toBe(135301852344706760000);
27+
});
28+
});

0 commit comments

Comments
 (0)