EloquentJS - Functions Excercise

Minimum

Write a function min that takes two arguments and returns their minimum.

1
2
3
function min(a,b){
return a < b ? a :b
}

Recursion

Define a recursive function isEven corresponding to this description. The function should accept a number parameter and return a Boolean.

1
2
3
4
5
6
7
8
9
10
function isEven(num){
if(num == 0){
return true;
} else if (num ==1){
return false;
} else if ( num < 0 ){
num = Math.abs(num)
}
return isEven(num-2);
}

Bean Counting

Write a function countBs that takes a string as its only argument and returns a number that indicates how many uppercase “B” characters are in the string.

Next, write a function called countChar that behaves like countBs, except it takes a second argument that indicates the character that is to be counted (rather than counting only uppercase “B” characters). Rewrite countBs to make use of this new function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function countBs(str){
var counter = 0;
for(var i = 0; i<str.length; i++){
if(str.charAt(i) == "B"){
counter ++;
}
}
return counter;
}

function countChar(str, letter){
var counter = 0;
for(var i = 0; i<str.length; i++){
if(str.charAt(i) == letter){
counter ++;
}
}
return counter;
}

//Rewrite function countBs
function countBs(str){
return countChar(str, "B");
}