From 88cf645af9ff5f3284db564c4c452d5c37edf89b Mon Sep 17 00:00:00 2001 From: Rytikov Dmitrii Date: Thu, 12 Oct 2017 17:54:28 +0300 Subject: [PATCH] add es6 code for breadth-first-search --- .../es6/01_breadth-first_search.js | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 06_breadth-first_search/es6/01_breadth-first_search.js diff --git a/06_breadth-first_search/es6/01_breadth-first_search.js b/06_breadth-first_search/es6/01_breadth-first_search.js new file mode 100644 index 0000000..5f3836c --- /dev/null +++ b/06_breadth-first_search/es6/01_breadth-first_search.js @@ -0,0 +1,32 @@ +const graph = {}; +graph.you = ['alice', 'bob', 'claire']; +graph.bob = ['anuj', 'peggy']; +graph.alice = ['peggy']; +graph.claire = ['thom', 'jonny']; +graph.anuj = []; +graph.peggy = []; +graph.thom = []; + +const isSeller = name => name[name.length - 1] === 'm'; + +const search = (name, graph) => { + const iter = (waited, visited) => { + if (waited.length === 0) { + return false; + } + const [current, ...rest] = waited; + if (visited.has(current)) { + return iter(rest, visited); + } + if (isSeller(current)) { + console.log(`${current} is a mango seller!`); + return true; + } + visited.add(current); + const personFriends = graph[current]; + return iter([...rest, ...personFriends], visited); + }; + return iter(graph[name], new Set()); +}; + +search('you');