Initially I was trying to do a switch but in the next lines I will explain why it didn't work like that.
Having two arrays like those ones:
const countries = [ 'France', 'Italy', 'Spain' ];
const cities = [ 'Paris', 'Marseille', 'Rome', 'Naples', 'Milan', 'Madrid' ];
As you can see, there is a connection between the countries and the cities:
France has Paris and Marseille
Italy has Rome, Naples and Milan
Spain has Madrid
The logic of my application should check for those countries alphabetically, (F > I > S), then check if the available city.
If there is a country present but no city was provided, as default it should use the capital city (first from the list). If there are multiple cities, the capital should be checked for the last one.
Examples:
Input: countries = [ 'France' ]; cities = [ 'Marseille']
Result: doThis('Marseille');
Input: countries = [ 'France' ]; cities = []
Result: doThis('Paris');
Input: countries = [ 'France' ]; cities = [ 'Paris', 'Marseille']
Result: doThis('Marseille');
Here is the code:
const doThat = (city: string) => {
console.log(city);
};
const myFunc = (countries: string[], cities: string[]) => {
if (countries.includes('France')) {
if (cities.includes('Marseille')) {
doThat('Marseille');
} else doThat('Paris');
} else if (countries.includes('Italy')) {
if (cities.includes('Naples')) {
doThat('Naples');
} else if (cities.includes('Milan')) {
doThat('Naples');
} else doThat('Rome');
} else if (countries.includes('Spain')) {
doThat('Madrid');
} else doThat('empty');
};
It cannot work with a switch because it would be something like:
switch (countries) {
case countries.includes('France'): ... // cannot be boolean here
...
}
Is there a way to make it better/more readable?