Add code for chapter 3 and 4 in ts (#103)

This commit is contained in:
Alex
2019-03-28 23:51:36 +02:00
committed by Aditya Bhargava
parent 97003f16df
commit d77cde9e67
8 changed files with 94 additions and 0 deletions

View File

@@ -0,0 +1,10 @@
function sum(arr: number[]): number {
let total = 0;
arr.forEach(number => {
total += number;
});
return total;
}
console.log(sum([1, 2, 3, 4]));

View File

@@ -0,0 +1,9 @@
function sum(arr: number[]): number {
if (arr.length === 1) {
return arr[0];
}
return arr[0] + sum(arr.slice(1));
}
console.log(sum([1, 2, 3, 4]));

View File

@@ -0,0 +1,9 @@
function count<T>(list: T[]): number {
if (list.length === 1) {
return 1;
}
return 1 + count(list.slice(1));
}
console.log(count([1, 2, 3]));

View File

@@ -0,0 +1,15 @@
function max(arr: number[]): number | null {
if (arr.length === 0) {
return null;
}
if (arr.length === 1) {
return arr[0];
}
const subMax = max(arr.slice(1));
return arr[0] > subMax ? arr[0] : subMax;
};
console.log(max([1, 2, 4, 3]));

View File

@@ -0,0 +1,13 @@
function quicksort(arr: number[]): number[] {
if (arr.length < 2) {
return arr;
}
const pivot = arr[0];
const less = arr.slice(1).filter(el => el <= pivot);
const greater = arr.slice(1).filter(el => el > pivot);
return quicksort(less).concat(pivot, quicksort(greater));
}
console.log(quicksort([10, 5, 2, 3]));