Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Math:Fibonacci Added #41

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/algorithms/math/fibonacci.js
Original file line number Diff line number Diff line change
@@ -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;
4 changes: 3 additions & 1 deletion src/algorithms/math/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
};
22 changes: 22 additions & 0 deletions test/algorithms/math/testFibonacci.js
Original file line number Diff line number Diff line change
@@ -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]);
});
});