From 393b8e135d5f3559d37cdf4e7c9800e56925f374 Mon Sep 17 00:00:00 2001 From: Alex Date: Thu, 28 Mar 2019 23:51:05 +0200 Subject: [PATCH] Add code for chapter 6 in ts (#105) --- .../ts/01_breadth-first_search.ts | 42 +++++++++++++++++++ 06_breadth-first_search/ts/tsconfig.json | 9 ++++ 2 files changed, 51 insertions(+) create mode 100644 06_breadth-first_search/ts/01_breadth-first_search.ts create mode 100644 06_breadth-first_search/ts/tsconfig.json diff --git a/06_breadth-first_search/ts/01_breadth-first_search.ts b/06_breadth-first_search/ts/01_breadth-first_search.ts new file mode 100644 index 0000000..13c875d --- /dev/null +++ b/06_breadth-first_search/ts/01_breadth-first_search.ts @@ -0,0 +1,42 @@ +interface Graph { + [key: string]: T[] +}; + +function personIsSeller(name: string): boolean { + return name.endsWith('m'); +} + +const graph: 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 = []; + +function search(name: string): boolean { + let searchQueue = graph[name]; + // This array is how you keep track of which people you've searched before. + const searched = []; + + while(searchQueue.length > 0) { + const person = searchQueue.shift(); + // Only search this person if you haven't already searched them + if (!searched.includes(person)) { + if (personIsSeller(person)) { + console.log(`${person} is a mango seller!`); + return true; + } else { + searchQueue = searchQueue.concat(graph[person]); + // Marks this person as searched + searched.push(person); + } + } + } + + return false; +}; + +search('you'); \ No newline at end of file diff --git a/06_breadth-first_search/ts/tsconfig.json b/06_breadth-first_search/ts/tsconfig.json new file mode 100644 index 0000000..1e5dba5 --- /dev/null +++ b/06_breadth-first_search/ts/tsconfig.json @@ -0,0 +1,9 @@ +{ + "compilerOptions": { + "lib": [ + "dom", + "es2015", + "es2016" + ] + } +} \ No newline at end of file