aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorFridon <[email protected]>2022-06-22 00:01:18 +0400
committerFridon <[email protected]>2022-06-22 00:01:18 +0400
commitcab126423c647aeac1a2a692b4918772d4e56150 (patch)
treeb56c0a4f08af73f97d52af1b751a6409f20552c3 /src
parent336862f977962d3cbb88e9b7bcf288045c377ac5 (diff)
downloadcountryfetch-cab126423c647aeac1a2a692b4918772d4e56150.tar.xz
countryfetch-cab126423c647aeac1a2a692b4918772d4e56150.zip
add find by capital
Diffstat (limited to 'src')
-rw-r--r--src/app.ts13
-rw-r--r--src/countries.ts17
2 files changed, 27 insertions, 3 deletions
diff --git a/src/app.ts b/src/app.ts
index 09db256..10129e1 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -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 = [];