-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.test.js
More file actions
58 lines (53 loc) · 1.6 KB
/
app.test.js
File metadata and controls
58 lines (53 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
function runRecursiveFunction(recursiveFunction) {
const result = recursiveFunction(10);
console.log(result);
}
const sum = (function sum(number) {
if (number === 0) {
return 0;
}
return number + sum(number - 1);
});
runRecursiveFunction(sum); // returns 55
const sumEven = (function sumEven(number) {
if (number === 0) {
return 0;
} else if (number % 2 !== 0) {
return sumEven(number - 1);
}
return number + sumEven(number - 1);
});
runRecursiveFunction(sumEven); // returns 30
const factorial = (function factorial(number) {
if (number === 0) {
return 1;
}
return number * factorial(number - 1);
});
runRecursiveFunction(factorial); // returns 120
const fibonacci = (function fibonacci(number) {
if (number === 0) {
return [0];
} else if (number === 1) {
return [0, 1];
} else {
const sequence = fibonacci(number - 1);
sequence.push(sequence[sequence.length - 1] + sequence[sequence.length - 2]);
return sequence;
}
});
runRecursiveFunction(fibonacci); // returns [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
const binarySearch = (function binarySearch(array, value, start, end) {
if (start > end) {
return -1;
}
const middle = Math.floor((start + end) / 2);
if (array[middle] === value) {
return middle;
} else if (array[middle] > value) {
return binarySearch(array, value, start, middle - 1);
} else {
return binarySearch(array, value, middle + 1, end);
}
});
runRecursiveFunction(() => binarySearch([1, 3, 5, 7, 9], 5, 0, 4)); // returns 2