Add code for chapter 6 in ts (#105)

This commit is contained in:
Alex
2019-03-28 23:51:05 +02:00
committed by Aditya Bhargava
parent 62c3b39668
commit 393b8e135d
2 changed files with 51 additions and 0 deletions

View File

@@ -0,0 +1,42 @@
interface Graph<T> {
[key: string]: T[]
};
function personIsSeller(name: string): boolean {
return name.endsWith('m');
}
const graph: Graph<string> = {};
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');

View File

@@ -0,0 +1,9 @@
{
"compilerOptions": {
"lib": [
"dom",
"es2015",
"es2016"
]
}
}