You can solve this by putting one else
at the end of your code. This would make the following algorithm:
Se a cidade for SAO PAULO
Filial01
Se a cidade for RIO DE JANEIRO
Filial02
...
Se não for nenhuma delas
Central
function run(cidadeFilial) {
cidadeFilial = cidadeFilial.toUpperCase();
if (cidadeFilial == 'SAO PAULO') {
return 'Filial01';
} else if (cidadeFilial == 'RIO DE JANEIRO') {
return 'Filial02';
} else if (cidadeFilial == 'CURITIBA') {
return 'Filial03';
} else if (cidadeFilial == 'FLORIANOPOLIS') {
return 'Filial03';
} else if (cidadeFilial == 'SANTOS') {
return 'Filial04';
} else if (cidadeFilial == 'GUARUJA') {
return 'Filial05';
} else if (cidadeFilial == 'BELO HORIZONTE') {
return 'Filial05';
} else {
return 'Central';
}
}
console.log(run('FLORIANOPOLIS'));
console.log(run('teste'));
And it is possible to reduce the number of if
s using a "if A or B". See example below:
if (cidadeFilial == 'CURITIBA' || cidadeFilial == 'FLORIANOPOLIS') {
return 'Filial03';
}
Solving with switch
Instead of using several if else
, recommended for this type of case is the switch
, as it facilitates the reading of the code and the writing as well. If you do not know how the switch
it works, take a read on this question, that although it is in another language, the concept is the same: How the switch works behind the scenes?
The algorithm will be the same as the one quoted at the beginning of the answer, because the default
fulfils the role of senão
as long as the case
s fulfil the role of if (cidadeFilial == 'CIDADE')
, and you can also group cities that have the same branch to run the same code, see:
function run(cidadeFilial) {
cidadeFilial = cidadeFilial.toUpperCase();
switch (cidadeFilial) {
case 'SAO PAULO':
return 'Filial01';
case 'RIO DE JANEIRO':
return 'Filial02';
case 'CURITIBA':
case 'FLORIANOPOLIS':
return 'Filial03';
case 'SANTOS':
return 'Filial04';
case 'GUARUJA':
case 'BELO HORIZONTE':
return 'Filial05';
default:
return 'Central';
}
}
console.log(run('FLORIANOPOLIS'));
console.log(run('teste'));
In the case of cities with the same branch, here simply is made a "if" with two conditions:
Se a cidade for CURITIBA ou FLORIANOPOLIS
Filial03
I believe you have an error in your implementation code: Santos and Guarujá should probably have the same branch, not Guarujá and Belo Horizonte, right? :)
– Rafael Tavares
Did any of the answers solve your problem? If the question is solved, consider accepting an answer. See more details at How and why to accept an answer?
– Rafael Tavares