UNPKG

countries-capitals

Version:

A simple package to get the capital of the countries

101 lines (100 loc) 3.35 kB
'use strict'; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const countries_json_1 = __importDefault(require("./countries.json")); const random_item_1 = __importDefault(require("random-item")); class Countries { constructor(countries = countries_json_1.default) { this.countries = countries; this.original = countries; } list() { return this.original; } reset() { this.countries = this.original; return this; } containString(str1, str2) { return str1.toLowerCase().includes(str2.toLowerCase()); } byName(name) { this.countries = this.countries.filter(({ country }) => this.containString(country, name)); return this; } byCapital(capital) { this.countries = this.countries.filter(({ city }) => { if (capital === null) { return city === null; } if (city === null) { return false; } return this.containString(city, capital); }); return this; } byLocation(region) { this.countries = this.countries.filter(({ location }) => { if (region === null) { return location === null; } if (location === null) { return false; } return this.containString(location, region); }); return this; } locations() { const locations = this.original.map(item => item.location).filter(Boolean); return [...new Set(locations)].sort(); } byIndependence(year, operator = '=') { const validOperators = ['=', '>', '>=', '<', '<=']; const op = validOperators.includes(operator) ? operator : '='; this.countries = this.countries.filter(({ independence }) => { if (year === null) { return independence === null; } if (independence === null) { return false; } return this.compare(parseInt(independence, 10), op, year); }); return this; } longest() { const capitalsArray = this.original.map(({ city }) => city).filter(Boolean); const capital = capitalsArray.reduce((acc, cur) => { return acc.length > cur.length ? acc : cur; }); this.reset().byCapital(capital); return this; } compare(firstValue, operator, secondValue) { switch (operator) { case '>': return firstValue > secondValue; case '>=': return firstValue >= secondValue; case '<': return firstValue < secondValue; case '<=': return firstValue <= secondValue; default: return firstValue == secondValue; } } toJson() { return this.countries; } get capital() { const countriesFound = this.countries.length; if (!countriesFound) { throw new Error('Country not found'); } if (countriesFound === 1) { return this.countries[0].city; } return random_item_1.default(this.countries).city; } } exports.default = Countries;