Add ES6 Examples to all chapters (#38)

* add ES6 example for binary search

* add ES6 example for selection sort

* add ES6 example for countdown

* add ES6 example for greet

* add ES6 example for factorial

* edit ES6 example for quicksort

* add ES6 example for loop sum

* add ES6 example for recursive sum

* add ES6 example for recursive count

* add ES6 example for recursive max

* add ES6 example for price of groceries

* add ES6 example for check voter

* add ES6 example for breadth-first search

* add ES6 example for dijkstras algorithm

* edit ES6 example for dijkstras algorithm

* edit ES6 example for set covering

* add ES6 example for longest common subsequence
This commit is contained in:
Yossi Adler
2017-11-13 18:12:59 +02:00
committed by Aditya Bhargava
parent 1a81d3e6b2
commit ec2890a93d
20 changed files with 328 additions and 18 deletions

View File

@@ -0,0 +1,9 @@
const sum = (arr) => {
let total = 0;
for (let x = 0; x < arr.length; x += 1) {
total += arr[x];
}
return total;
};
console.log(sum([1, 2, 3, 4])); // 10

View File

@@ -0,0 +1,8 @@
const 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,8 @@
const 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,9 @@
const max = (list) => {
if (list.length === 2) {
return list[0] > list[1] ? list[0] : list[1];
}
const subMax = max(list.slice(1));
return list[0] > subMax ? list[0] : subMax;
};
console.log(max([1, 5, 10, 25, 16, 1])); // 25

View File

@@ -0,0 +1,12 @@
const quickSort = (array) => {
if (array.length < 2) {
return array;
}
const pivot = array[0];
const less = array.filter(item => item < pivot);
const greater = array.filter(item => item > pivot);
return [...quickSort(less), pivot, ...quickSort(greater)];
};
console.log(quickSort([10, 5, 2, 3])); // [2, 3, 5, 10]

View File

@@ -1,18 +0,0 @@
const quickSort = (array) => {
if (array.length < 2) {
return array;
}
if (array.length === 2) {
// if first elem more than second will swap them and return it like new array.
return array[0] < array[1] ? array : [array[1], array[0]];
}
const pivot = array[0]
const itemsAreLessPivotSubArray = array.filter(item => item < pivot);
const itemsAreMoreThenPivotSubArray = array.filter(item => item > pivot);
return [...quickSort(itemsAreLessPivotSubArray), pivot, ...quickSort(itemsAreMoreThenPivotSubArray)];
};
module.exports = quickSort;
console.log(quicksort([10, 5, 2, 3])); // [2, 3, 5, 10]