code from chapter 4 in javascript

This commit is contained in:
Kevin Nguyen
2016-06-16 23:00:05 -07:00
parent 96c766f9d9
commit 4ad9398ab2
5 changed files with 60 additions and 0 deletions

View File

@@ -0,0 +1,11 @@
'use strict';
function sum(arr) {
let total = 0;
for (let x = 0; x < arr.length; x++) {
total += arr[x];
}
return total;
}
console.log(sum([1, 2, 3, 4])) // 10

View File

@@ -0,0 +1,10 @@
'use strict';
function sum(list) {
if (list.length === 0) {
return 0;
}
return list[0] + sum(list.slice(1));
}
console.log(sum([1, 2, 3, 4])) // 10

View File

@@ -0,0 +1,10 @@
'use strict';
function count(list) {
if (list.length === 0) {
return 0;
}
return 1 + count(list.slice(1));
}
console.log(count([0, 1, 2, 3, 4, 5])); // 6

View File

@@ -0,0 +1,11 @@
'use strict';
function max(list) {
if (list.length === 2) {
return list[0] > list[1] ? list[0] : list[1];
}
let sub_max = max(list.slice(1));
return list[0] > sub_max ? list[0] : sub_max;
}
console.log(max([1, 5, 10, 25, 16, 1])); // 25

View File

@@ -0,0 +1,18 @@
'use strict';
function quicksort(array) {
if (array.length < 2) {
// base case, arrays with 0 or 1 element are already "sorted"
return array;
} else {
// recursive case
let pivot = array[0];
// sub-array of all the elements less than the pivot
let less = array.slice(1).filter(function(el) { return el <= pivot; });
// sub-array of all the elements greater than the pivot
let greater = array.slice(1).filter(function(el) { return el > pivot; });
return quicksort(less).concat([pivot], quicksort(greater));
}
}
console.log(quicksort([10, 5, 2, 3])); // [2, 3, 5, 10]