1
+ import { error } from "console" ;
1
2
import { computeLexicographicDistance } from "./util.js" ;
2
3
3
4
/**
@@ -11,9 +12,8 @@ export function compareStrings(a: string, b: string): number {
11
12
// The distance will be a number less than 0 if string `a` is lexicographically less than `b`, 1
12
13
// if it is greater, and 0 if the strings are equal.
13
14
const distance = computeLexicographicDistance ( a , b ) ;
14
-
15
- // TODO(you): Finish this method.
16
-
15
+ if ( distance < 0 ) return - 1 ;
16
+ if ( distance > 0 ) return 1 ;
17
17
return 0 ;
18
18
}
19
19
@@ -24,7 +24,17 @@ export function compareStrings(a: string, b: string): number {
24
24
* @return The factorial of n.
25
25
*/
26
26
export function computeFactorial ( n : number ) : number {
27
- return 0 ;
27
+ if ( n < 0 ) {
28
+ return 0 ;
29
+ }
30
+ if ( n === 0 || n === 1 ) {
31
+ return 1 ;
32
+ }
33
+ let result = 1 ;
34
+ for ( let i = 2 ; i <= n ; i ++ ) {
35
+ result *= i ;
36
+ }
37
+ return result ;
28
38
}
29
39
30
40
/**
@@ -34,7 +44,14 @@ export function computeFactorial(n: number): number {
34
44
* @return An array containing the first `n` Fibonacci values.
35
45
*/
36
46
export function getFirstNFibonacciNumbers ( n : number ) : number [ ] {
37
- return [ ] ;
47
+ if ( n <= 0 ) return [ ] ;
48
+ if ( n === 1 ) return [ 0 ] ;
49
+
50
+ const fibSeries : number [ ] = [ 1 , 1 ] ;
51
+ for ( let i = 2 ; i < n ; i ++ ) {
52
+ fibSeries . push ( fibSeries [ i - 1 ] + fibSeries [ i - 2 ] ) ;
53
+ }
54
+ return fibSeries ;
38
55
}
39
56
40
57
/**
@@ -58,12 +75,16 @@ export function binarySearch(
58
75
}
59
76
60
77
const pivotIndex = Math . floor ( ( start + end ) / 2 ) ; // The index in the middle of the array.
61
-
62
- // TODO(you): Finish implementing this algorithm
63
-
64
- // If values[pivotIndex] is equal to value then return `pivotIndex`.
65
- // Else if values[pivotIndex] is greater than the value, then
66
- // call ` binarySearch(values, start, pivotIndex - 1, value)` and return its value;
67
- // Else call `binarySearch(values, pivotIndex + 1, end, value)` and return its value.
78
+ if ( values [ pivotIndex ] === value ) {
79
+ return pivotIndex ;
80
+ } else if ( values [ pivotIndex ] > value ) {
81
+ return binarySearch ( values , start , pivotIndex - 1 , value ) ;
82
+ } else {
83
+ return binarySearch ( values , pivotIndex + 1 , end , value ) ;
84
+ }
68
85
return - 1 ;
69
86
}
87
+ // If values[pivotIndex] is equal to value then return `pivotIndex`.
88
+ // Else if values[pivotIndex] is greater than the value, then
89
+ // call `binarySearch(values, start, pivotIndex - 1, value)` and return its value;
90
+ // Else call `binarySearch(values, pivotIndex + 1, end, value)` and return its value.
0 commit comments