Files
grokking_algorithms/06_breadth-first_search/ES6/01_breadth-first_search.js
Yossi Adler ec2890a93d 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
2017-11-13 08:12:59 -08:00

35 lines
978 B
JavaScript

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!