Kovacs Akos Kovacs Akos - 4 months ago 28
Javascript Question

Simple modulo tester

I have a simple, modulo based script, which runs for 3 and 6 digits to

else
. There are also cases for these numbers, which condition should fit also to these numbers.

function caffeineBuzz(n){
var returnvalue;

if (n % 3 == 0)
returnvalue = "Java";
if (n % 3 == 0 && n % 4 == 0)
returnvalue = "Coffee";
if (n % 3 == 0 && n % 2 == 0)
returnvalue = "Java" + "Script"
if (n % 4 == 0 && n % 2 == 0)
returnvalue = "Coffee" + "Script"
else
returnvalue = "mocha_missing!"

return returnvalue;
}


n
stands for input, that is an integer and returnvalue should be a string.

Update:
Most specific -> less specific approach helped me, but there are cases, when it returns with wrong value.

function caffeineBuzz(n){
var returnvalue;

if (n % 4 == 0)
returnvalue = "Coffee" + "Script"
else if (n % 3 == 0 && n % 4 == 0)
returnvalue = "Coffee";
else if (n % 3 == 0 && n % 2 == 0)
returnvalue = "Java" + "Script"
else if (n % 3 == 0)
returnvalue = "Java";
else
returnvalue = "mocha_missing!"

return returnvalue;
}

Answer

This function is the guesstimation of the answer based on comments.

function caffeineBuzz(n){
    //Storing n's modulos to not calculate them multiple times
    var mod3 = (n % 3 == 0)
    var mod4 = (n % 4 == 0);
    var mod2 = mod4 || (n % 2 == 0);

    //Maybe: return (mod3 ? ("Java" + (mod4 ? "Coffee" : "")) + (mod2 ? "Script" : "") : "mocha_missing!");
    return (mod3 ? ((mod4 ? "Coffee" : "Java") + (mod2 ? "Script" : "")) : ("mocha_missing!"));
}
Comments