Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutual recursion and JSLint - function was used before it was defined

If I write the following code, JSLint complains that 'isOdd' was used before it was defined. Is there a way to write mutually recursive code and still please JSLint?

var isEven = function(n) {
    if (n === 0) {
        return true;
    }
    return isOdd(n - 1);
};

var isOdd = function(n) {
    if (n === 0) {
        return false;
    }
    return isEven(n - 1);
};
like image 853
johnnyodonnell Avatar asked Aug 22 '17 02:08

johnnyodonnell


2 Answers

For JSLint, you have to add a global variables directive to the top of the file, so that it ignores usage of temporary "undefined" functions and variables.

/*global isOdd */

var isEven = function(n) {
    if (n === 0) {
        return true;
    }
    return isOdd(n - 1);
};

var isOdd = function(n) {
    if (n === 0) {
        return false;
    }
    return isEven(n - 1);
};

You could also declare isOdd at the top, but then you would change your actual code because a linting program doesn't understand hoisting:

var isOdd;

var isEven = function(n) {
    if (n === 0) {
        return true;
    }
    return isOdd(n - 1);
};

isOdd = function(n) {
    if (n === 0) {
        return false;
    }
    return isEven(n - 1);
};

like image 61
Nano Miratus Avatar answered Oct 19 '22 18:10

Nano Miratus


Converting these functions to methods of an object quell the error message from JSLint. This also does a better job of keeping the global namespace less polluted.

var numUtil = {
    isEven: function(n) {
        if (n === 0) {
            return true;
        }
        return this.isOdd(n - 1);
    },
    isOdd: function(n) {
        if (n === 0) {
            return false;
        }
        return this.isEven(n - 1);
    }
};
like image 1
johnnyodonnell Avatar answered Oct 19 '22 17:10

johnnyodonnell