30 Day JavaScript Learning Challenge: Day 13

Day 13 of the 30 Day Learning Challenge and I finished off Chapter 3 of Eloquent JavaScript. There's some really good advice in this book about how to build functions (essentially make the function have as few side effects as possible). I did two of the examples. Here's the code for each:

This one recursively determines if a number is even using the following rubric:

  • Zero is even.
  • One is odd.
  • For any other number N, its evenness is the same as N - 2.

Here's the code:

function isEven(x) {
    if (x == 0) {
        return true;
    };
    if (x == 1) {
        return false;
    };

    return isEven(x - 2);
};

The next problem finds an arbitrary letter in a string:

function countChar(compareText, compareCharacter) {
    var countCharacter = 0;
    for (i = 0; i <= compareText.length; i++) {
        if (compareText.charAt(i) == compareCharacter) {
            countCharacter++;
        };
    };
    return countCharacter;
};

Nothing too special here but I'm finding that I've been spoiled by Python (typing in str.length() instead of str.length, even though Python uses length(str) instead). But nothing too serious or too tricky here. I've been a little gun-shy about doing recursion and was surprised the isEven worked pretty much out of the box (once I figured out my dumb syntax errors).

Overall a pretty productive session. Onward to Chapter 4 "Data Structures: Objects and Arrays".


links

social