Exercise 1)
I originally read the question wrong and made
function solve() {
alert(Math.min(3, 2));
}
console.log(solve())
Then i made:
function min(a, b) {
if (a < b) return a;
else return b;
}
console.log(min(52, 23));
I guess they both do the same thing in a way, but the first wasn’t the correct way to get the outcome.
Exercise 2)
My first attempt was (below), and i was really confused to start out with
function isEven(n) {
if (n % 0 === 0) {
return "even";
}
else if (n % 1 === 0) {
return "odd";
}
else if (n % n - 2) return "?";
}
console.log(isEven(75));
Then i found out (below) was the answer. I thought we had to use the “%” operator in the formula, how exactly does the “==” calculate the remainder? Struggling to understand how this formula is working. Any suggestions on how to understand - should i reread and re-watch the videos?
function isEven(n) {
if (n == 0) return true;
else if (n == 1) return false;
else if (n < 0) return isEven(-n);
else return isEven(n - 2);
}
console.log(isEven(50));
Exercise 3)
Again, quite confused (my attempt below). Why is ‘ch’ in the formula? Not sure how I’m meant to understand it - any suggestions?
function countBs(a) {
var bCounter = countBs(a[B]);
for (var i = 0; i < bCounter.length; i++);
return i;
}
console.log(countBs("BB"));
Edit ~
I took a little look at other people’s answers and how they arranged the formula and now i kind of understand the logic behind it. I then made this:
function countBs(string, stringChr) {
counter = 0;
for (var i = 0; i < string.length; i++) {
if (string[i] === stringChr){
counter++;
}
}
return counter;
}
console.log(countBs("BBBB", "B"));