From 213636fc58768364fd60ae959c61e1b136a5e85e Mon Sep 17 00:00:00 2001 From: Rajratna Maitry <49335238+rajratnamaitry@users.noreply.github.com> Date: Mon, 11 Jul 2022 12:54:55 +0530 Subject: [PATCH] fibonacci optimize with Memory pattern --- src/others/fibonacciMemory.js | 32 +++++++++++++++++++++++++++++ test/others/fibonacciMemory.spec.js | 28 +++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 src/others/fibonacciMemory.js create mode 100644 test/others/fibonacciMemory.spec.js diff --git a/src/others/fibonacciMemory.js b/src/others/fibonacciMemory.js new file mode 100644 index 00000000..256979bd --- /dev/null +++ b/src/others/fibonacciMemory.js @@ -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); diff --git a/test/others/fibonacciMemory.spec.js b/test/others/fibonacciMemory.spec.js new file mode 100644 index 00000000..a2c5c118 --- /dev/null +++ b/test/others/fibonacciMemory.spec.js @@ -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); + }); +});