Minimum
function minimum(a, b){
return (a < b ? a : b )
}
console.log(minimum(5,4))
In order to keep this function short, I used the conditional operator ‘?’ here.
isEven
function isEven(number) {
if (number == 0) {
return true;
} else if (number == 1) {
return false;
} else if (number > 0) {
return isEven(number - 2);
} else {
return isEven(number + 2);
}
}
console.log(isEven(5));
console.log(isEven(-2));
My idea to solve this problem for negative numbers was to go up by 2, instead of going down by 2 for positive numbers. Going to 0 is always the right direction!
In the second else ifstatement I just needed to check that number > 0
, because if the number is equal to 0, the function will return true. So if the number is neither positive nor 0 it must be negative.
But I also understand that the proposed solution with return isEven(-n)
is even better! My program will always run until the last else for negative numbers. But if you turn the sign with -n the number will get postive! Therefore the code of the last else statement will be executed only once! After that the code will be executed until the second else if statement before the number will get 0 or 1. A smaller number of calculated boolean expression will result in a faster calculation.
isEven (better version)
function isEven(number) {
if (number == 0) {
return true;
} else if (number == 1) {
return false;
} else if (number > 0) {
return isEven(number - 2);
} else {
return isEven( - number );
}
}
console.log(isEven(5));
console.log(isEven(-2));
countBs
function countBs(myString) {
var counter = 0;
for (index = 0; index < myString.length; index++) {
if (myString[index] == "B") {
counter++;
}
}
return counter;
}
console.log(countBs("ABC, BOT"));
countChar
function countChar(myString, myChar) {
var counter = 0;
for (index = 0; index < myString.length; index++) {
if (myString[index] == myChar) {
counter++;
}
}
return counter;
}
console.log(countChar("ABC, BOT, BEAN","B"));
countBs using countChar
If we already have developed countChar, we don’t need countBs any more, since countChar is more general than countBs. We could even write a shorter countBs using countChar:
function countChar(myString, myChar) {
var counter = 0;
for (index = 0; index < myString.length; index++) {
if (myString[index] == myChar) {
counter++;
}
}
return counter;
}
function countBs(myString) {
return countChar(myString, "B");
}
console.log(countBs("ABC, BOT, BEAN"));