Refactor algorithms structure.

This commit is contained in:
Oleksii Trekhleb
2018-04-02 08:45:50 +03:00
parent 6e4d7a1750
commit f3503f1d5e
4 changed files with 2 additions and 1 deletions

View File

@ -0,0 +1,8 @@
# Fibonacci Number
In mathematics, the Fibonacci numbers are the numbers in the following
integer sequence, called the Fibonacci sequence, and characterized by
the fact that every number after the first two is the sum of the two
preceding ones:
`0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...`

View File

@ -0,0 +1,15 @@
import fibonacci from '../fibonacci';
describe('fibonacci', () => {
it('should calculate fibonacci correctly', () => {
expect(fibonacci(1)).toBe(1);
expect(fibonacci(2)).toBe(1);
expect(fibonacci(3)).toBe(2);
expect(fibonacci(4)).toBe(3);
expect(fibonacci(5)).toBe(5);
expect(fibonacci(6)).toBe(8);
expect(fibonacci(7)).toBe(13);
expect(fibonacci(8)).toBe(21);
expect(fibonacci(20)).toBe(6765);
});
});

View File

@ -0,0 +1,26 @@
// Calculate fibonacci number at specific position using Dynamic Programming approach.
export default function fibonacci(numberPosition) {
if (numberPosition === 1) {
return 1;
}
let iterationsCounter = numberPosition - 1;
// Calculated fibonacci number.
let fib = null;
// Previous fibonacci number.
let fibPrev = 1;
// Before previous fibonacci number.
let fibPrevPrev = 0;
while (iterationsCounter) {
// Calculate current value using two previous ones.
fib = fibPrev + fibPrevPrev;
// Shift previous values.
fibPrevPrev = fibPrev;
fibPrev = fib;
iterationsCounter -= 1;
}
return fib;
}