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,25 @@
const binarySearch = (list, item) => {
let low = 0;
let high = list.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
const guess = list[mid];
if (guess === item) {
return mid;
}
if (guess > item) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return null;
};
const myList = [1, 3, 5, 7, 9];
console.log(binarySearch(myList, 3)); // 1
console.log(binarySearch(myList, -1)); // null

View File

@@ -0,0 +1,26 @@
// Finds the smallest value in an array
const findSmallest = (arr) => {
let smallest = arr[0]; // Stores the smallest value
let smallestIndex = 0; // Stores the index of the smallest value
for (let i = 1; i < arr.length; i += 1) {
if (arr[i] < smallest) {
smallest = arr[i];
smallestIndex = i;
}
}
return smallestIndex;
};
// Sort array
const selectionSort = (arr) => {
const newArr = [];
const length = arr.length;
for (let i = 0; i < length; i += 1) {
// Finds the smallest element in the array and adds it to the new array
const smallest = findSmallest(arr);
newArr.push(arr.splice(smallest, 1)[0]);
}
return newArr;
};
console.log(selectionSort([5, 3, 6, 2, 10])); // [2, 3, 5, 6, 10]

View File

@@ -0,0 +1,11 @@
const countdown = (i) => {
console.log(i);
// base case
if (i <= 0) {
return null;
}
countdown(i - 1);
return null;
};
countdown(5);

View File

@@ -0,0 +1,12 @@
const greet2 = name => console.log(`how are you, ${name}?`);
const bye = () => console.log('ok bye!');
const greet = (name) => {
console.log(`hello, ${name}!`);
greet2(name);
console.log('getting ready to say bye...');
bye();
};
greet('adit');

View File

@@ -0,0 +1,8 @@
const fact = (x) => {
if (x === 1) {
return 1;
}
return x * fact(x - 1);
};
console.log(fact(5));

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]

View File

@@ -0,0 +1,8 @@
const book = {};
// an apple costs 67 cents
book.apple = 0.67;
// milk costs $1.49
book.milk = 1.49;
book.avokado = 1.49;
console.log(book); // { apple: 0.67, milk: 1.49, avocado: 1.49 }

View File

@@ -0,0 +1,14 @@
const voted = {};
const checkVoter = (name) => {
if (voted[name]) {
console.log('kick them out!');
} else {
voted[name] = true;
console.log('let them vote!');
}
};
checkVoter('tom'); // let them vote!
checkVoter('mike'); // let them vote!
checkVoter('mike'); // kick them out!

View File

@@ -0,0 +1,34 @@
const personIsSeller = name => name[name.length - 1] === 'm';
const graph = {};
graph.you = ['alice', 'bob', 'claire'];
graph.bob = ['anuj', 'peggy'];
graph.alice = ['peggy'];
graph.claire = ['thom', 'jonny'];
graph.anuj = [];
graph.peggy = [];
graph.thom = [];
graph.jonny = [];
const search = (name) => {
let searchQueue = [];
searchQueue = searchQueue.concat(graph[name]);
// This array is how you keep track of which people you've searched before.
const searched = [];
while (searchQueue.length) {
const person = searchQueue.shift();
// Only search this person if you haven't already searched them
if (searched.indexOf(person) === -1) {
if (personIsSeller(person)) {
console.log(`${person} is a mango seller!`);
return true;
}
searchQueue = searchQueue.concat(graph[person]);
// Marks this person as searched
searched.push(person);
}
}
return false;
};
search('you'); // thom is a mango seller!

View File

@@ -0,0 +1,72 @@
// the graph
const graph = {};
graph.start = {};
graph.start.a = 6;
graph.start.b = 2;
graph.a = {};
graph.a.fin = 1;
graph.b = {};
graph.b.a = 3;
graph.b.fin = 5;
graph.fin = {};
// The costs table
const costs = {};
costs.a = 6;
costs.b = 2;
costs.fin = Infinity;
// the parents table
const parents = {};
parents.a = 'start';
parents.b = 'start';
parents.fin = null;
let processed = [];
const findLowestCostNode = (itCosts) => {
let lowestCost = Infinity;
let lowestCostNode = null;
Object.keys(itCosts).forEach((node) => {
const cost = itCosts[node];
// If it's the lowest cost so far and hasn't been processed yet...
if (cost < lowestCost && (processed.indexOf(node) === -1)) {
// ... set it as the new lowest-cost node.
lowestCost = cost;
lowestCostNode = node;
}
});
return lowestCostNode;
};
let node = findLowestCostNode(costs);
while (node !== null) {
const cost = costs[node];
// Go through all the neighbors of this node
const neighbors = graph[node];
Object.keys(neighbors).forEach((n) => {
const newCost = cost + neighbors[n];
// If it's cheaper to get to this neighbor by going through this node
if (costs[n] > newCost) {
// ... update the cost for this node
costs[n] = newCost;
// This node becomes the new parent for this neighbor.
parents[n] = node;
}
});
// Mark the node as processed
processed = processed.concat(node);
// Find the next node to process, and loop
node = findLowestCostNode(costs);
}
console.log('Cost from the start to each node:');
console.log(costs); // { a: 5, b: 2, fin: 6 }

View File

@@ -0,0 +1,29 @@
// You pass an array in, and it gets converted to a set.
let statesNeeded = new Set(['mt', 'wa', 'or', 'id', 'nv', 'ut', 'ca', 'az']);
const stations = {};
stations.kone = new Set(['id', 'nv', 'ut']);
stations.ktwo = new Set(['wa', 'id', 'mt']);
stations.kthree = new Set(['or', 'nv', 'ca']);
stations.kfour = new Set(['nv', 'ut']);
stations.kfive = new Set(['ca', 'az']);
const finalStations = new Set();
while (statesNeeded.size) {
let bestStation = null;
let statesCovered = new Set();
Object.keys(stations).forEach((station) => {
const states = stations[station];
const covered = new Set([...statesNeeded].filter(x => states.has(x)));
if (covered.size > statesCovered.size) {
bestStation = station;
statesCovered = covered;
}
});
statesNeeded = new Set([...statesNeeded].filter(x => !statesCovered.has(x)));
finalStations.add(bestStation);
}
console.log(finalStations); // Set { 'kone', 'ktwo', 'kthree', 'kfive' }

View File

@@ -0,0 +1,7 @@
if (word_a[i] === word_b[j]) {
// The letters match
cell[i][j] = cell[i - 1][j - 1] + 1;
} else {
// The letters don't match
cell[i][j] = Math.max(cell[i - 1][j], cell[i][j - 1]);
}

View File

@@ -0,0 +1,9 @@
const initializeMatrix = (rows, cols) => {
const matrix = [];
for (let i = 0; i < rows.length; i += 1) {
matrix.push(Array(cols.length).fill(0));
}
return matrix;
};
export default initializeMatrix;

View File

@@ -0,0 +1,27 @@
import base from './base';
const diff = (firstWord, secondWord) => {
const arr1 = firstWord.split('');
const arr2 = secondWord.split('');
const matrix = initializeMatrix(arr1, arr2);
for (let i = 0; i < arr1.length; i += 1) {
for (let j = 0; j < arr2.length; j += 1) {
if (arr1[i] === arr2[j]) {
if (i > 0 && j > 0) {
matrix[i][j] = matrix[i - 1][j - 1] + 1;
} else {
matrix[i][j] = 1;
}
} else {
if (i > 0 && j > 0) {
matrix[i][j] = Math.max(matrix[i - 1][j], matrix[i][j - 1]);
} else {
matrix[i][j] = 0;
}
}
}
}
return matrix[arr1.length - 1][arr2.length - 1];
};
export default diff;