Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSHint warning "Function declared within loop referencing an outer scope variable may lead to confusing semantics" . How can I improve the code?

JSHint shows the error: "Function declared within loop referencing an outer scope variable may lead to confusing semantics". How can I improve the following code to get rid of the warning?

var getPrecedence  = function getPrecedence(operator, operators) {
    var keys = Object.keys(Object(operators));
    for (var i = 0, len = keys.length; i < len; i++) {
        var check = Object.keys(operators[keys[i]]).some(function (item) {
            return item === operator;
    });
    if (check) return operators[keys[i]][operator];
    }
};
like image 299
Kasia Avatar asked Jan 25 '18 11:01

Kasia


1 Answers

You are supposed not to use the function expression inside the loop body, but instead declare it outside:

function getPrecedence(operator, operators) {
    function isOperator(item) {
//  ^^^^^^^^^^^^^^^^^^^^^^^^^^^
        return item === operator;
    }
    var keys = Object.keys(Object(operators));
    for (var i = 0, len = keys.length; i < len; i++) {
        var check = Object.keys(operators[keys[i]]).some(isOperator);
//                                                       ^^^^^^^^^^
        if (check) return operators[keys[i]][operator];
    }
}

Of course the whole thing could be simplified by just using includes instead of some, and find instead of the loop:

function getPrecedence(operator, operators) {
    var keys = Object.keys(Object(operators));
    var opkey = keys.find(key =>
        Object.keys(operators[key]).includes(operator)
    );
    if (opkey) return operators[opkey][operator];
}

And finally, Object.keys(…).includes(…) can be simplified to operator in operators[key].

like image 152
Bergi Avatar answered Oct 17 '22 00:10

Bergi