diff options
| -rwxr-xr-x | run.sh | 2 | ||||
| -rw-r--r-- | src/app.ts | 13 | ||||
| -rw-r--r-- | src/countries.ts | 17 |
3 files changed, 28 insertions, 4 deletions
@@ -1,4 +1,4 @@ #!/bin/sh -# Just a short-hand to run instead of typing it out in termina during development +# Just a short-hand to run instead of typing it out in terminal during development deno run --allow-all ./main.ts "$@"
\ No newline at end of file @@ -1,3 +1,4 @@ +import { green, cyan } from "https://deno.land/x/[email protected]/mod.ts"; import { Countries } from "./countries.ts"; import { Cache } from "./util/cache.ts"; import { help } from "./util/help.ts"; @@ -11,14 +12,22 @@ export async function app() { case undefined: help(); break; + case "help": + help(); + break; case "sync": await countries.sync({ force: true }); break; case "random": countries.print(countries.random()); break; - case "help": - help(); + case "capital": + const [, ...args] = Deno.args; + const capital = args.join(" "); + const country = countries.findByCapital(capital); + console.log( + green(capital) + " is the capital of " + cyan(country.name.common) + ); break; default: countries.print(Deno.args.join(" ")); diff --git a/src/countries.ts b/src/countries.ts index dba4d1a..05d6a17 100644 --- a/src/countries.ts +++ b/src/countries.ts @@ -47,7 +47,7 @@ export class Countries { return this.list; } - find(name: string): Country { + find(name: string) { name = name.toLowerCase(); // Find exact match first, then fall back to fuzzy match const country = this.list.find((c) => { @@ -62,6 +62,21 @@ export class Countries { return country; } + findByCapital(capital: string) { + const country = this.list.find((c) => { + const capitalsLowercase = c.capital.map((capital) => + capital.toLowerCase() + ); + return capitalsLowercase.includes(capital); + }); + + if (!country) { + throw Error(`Could not find the country of capital: ${capital}`); + } + + return country; + } + print(name: string) { const country = this.find(name); let currencies = []; |
