From 600d671b804c791ae9934d35994ca058175d60eb Mon Sep 17 00:00:00 2001 From: htoopyae Date: Tue, 16 Oct 2018 11:01:46 +0630 Subject: [PATCH] Math:Fibonacci Added --- src/algorithms/math/fibonacci.js | 25 +++++++++++++++++++++++++ src/algorithms/math/index.js | 4 +++- test/algorithms/math/testFibonacci.js | 22 ++++++++++++++++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 src/algorithms/math/fibonacci.js create mode 100644 test/algorithms/math/testFibonacci.js diff --git a/src/algorithms/math/fibonacci.js b/src/algorithms/math/fibonacci.js new file mode 100644 index 00000000..117633bf --- /dev/null +++ b/src/algorithms/math/fibonacci.js @@ -0,0 +1,25 @@ +/** + * Show fibonacci sequence up to a given number + * @param {Number} num given number + */ +const fibonacci = (num) => { + let n1 = 0; + let n2 = 1; + const fibo = []; + + if (num < 0) { + throw new Error('Not a positive number'); + } + + while (n1 <= num) { + fibo.push(n1); + + const sum = n1 + n2; + n1 = n2; + n2 = sum; + } + + return fibo; +}; + +module.exports = fibonacci; diff --git a/src/algorithms/math/index.js b/src/algorithms/math/index.js index 41b2e488..25a8bcea 100644 --- a/src/algorithms/math/index.js +++ b/src/algorithms/math/index.js @@ -3,11 +3,13 @@ const gcd = require('./gcd'); const fastexp = require('./fast_exp'); const lcm = require('./lcm'); const modularInverse = require('./modular_inverse'); +const fibonacci = require('./fibonacci'); module.exports = { extendedEuclidean, gcd, fastexp, lcm, - modularInverse + modularInverse, + fibonacci }; diff --git a/test/algorithms/math/testFibonacci.js b/test/algorithms/math/testFibonacci.js new file mode 100644 index 00000000..d216f7fb --- /dev/null +++ b/test/algorithms/math/testFibonacci.js @@ -0,0 +1,22 @@ +/* eslint-env mocha */ +const fibonacci = require('../../../src/algorithms/math/fibonacci'); + +const assert = require('assert'); + +describe('Fibonacci', () => { + it('should return 0 if given number is 0', () => { + assert.deepStrictEqual(fibonacci(0), [0]); + }); + + it('should throw an error if the number is negative', () => { + assert.throws(() => fibonacci(-5)); + }); + + it('should return fibonacci sequence up to 10', () => { + assert.deepStrictEqual(fibonacci(10), [0, 1, 1, 2, 3, 5, 8]); + }); + + it('should return fibonacci sequence up to 100', () => { + assert.deepStrictEqual(fibonacci(100), [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]); + }); +});