File tree 2 files changed +36
-0
lines changed
2 files changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * A function to get nth Fibonacci number
3
+ * @param number The input integer
4
+ * @return {number } Fibonacci number of `number`
5
+ * @example nthFibonacci(4) => 3 | nthFibonacci(6) => 8
6
+ * @see https://en.m.wikipedia.org/wiki/Fibonacci_number
7
+ * @author MohdFaisalBidda <https://github.com/MohdFaisalBidda>
8
+ */
9
+
10
+ export const nthFibonacci = ( number : number ) : number => {
11
+ if ( number < 0 ) throw "Number should be greater than 0" ;
12
+
13
+ if ( number === 0 ) return 0 ;
14
+
15
+ let a = 0 , b = 1 ;
16
+
17
+ for ( let i = 1 ; i < number ; ++ i ) {
18
+ const c = a + b ;
19
+
20
+ a = b ;
21
+ b = c ;
22
+ }
23
+
24
+ return b ;
25
+ } ;
Original file line number Diff line number Diff line change
1
+ import { nthFibonacci } from '../Fibonacci' ;
2
+
3
+ describe ( 'nthFibonacci' , ( ) => {
4
+ test ( 'should return correct value' , ( ) => {
5
+ expect ( nthFibonacci ( 0 ) ) . toBe ( 0 ) ;
6
+ expect ( nthFibonacci ( 1 ) ) . toBe ( 1 ) ;
7
+ expect ( nthFibonacci ( 5 ) ) . toBe ( 5 ) ;
8
+ expect ( nthFibonacci ( 4 ) ) . toBe ( 3 ) ;
9
+ expect ( nthFibonacci ( 0 ) ) . toBe ( 0 ) ;
10
+ } ) ;
11
+ } ) ;
You can’t perform that action at this time.
0 commit comments