Create a function that receives an integer as an argument and returns a string such as:
This can be done using 3 if statements like below but can this be done only using 2 if statements?
const intToStr = (intVal) => {
if (intVal % 4 == 0 && intVal % 7 == 0) {
return "FooBar";
}
if (intVal % 7 == 0) {
return "Bar";
}
if (intVal % 4 == 0) {
return "Foo";
}
}
console.log(intToStr(4*7));
console.log(intToStr(7));
console.log(intToStr(4));
Yes, it can be done with just 2 if statements.
const intToStr = (intVal) => {
let str = '';
if (intVal % 4 === 0) {
str += "Foo";
}
if (intVal % 7 === 0) {
str += "Bar";
}
return str;
}
console.log(intToStr(4*7));
console.log(intToStr(7));
console.log(intToStr(4));
Remember that you can sum strings. As value returned in case input is dividable by the same values as in two other ifs, you can just add strings in case input fulfills that condition.
To make it more clear:
var output = '';
if(intVal % 4 === 0)
{
output = output + 'Foo' ;
}
if(intVal % 7 === 0)
{
output = output + 'Bar' ;
}
return output;
That way you have two conditions and their cumulative values returned.