Search code examples
javascriptangularjsunderscore.jsjslintgulp-eslint

Break from underscore loop with lint issues


Below is the code, trying to break the loop once the result is found by returning true

ngModel.$parsers.unshift(function (viewValue) {
                    let names = scope.vm.names;

                    _.find(names, function (elem) {
                        let name = elem.name;

                        if (name && viewValue) {
                            if (name.toLowerCase() === viewValue.toLowerCase()) {
                                ngModel.$setValidity('unique', false);
                                return true; // break out of this loop
                            } else {
                                ngModel.$setValidity('unique', true);
                            }
                        }
                    });
                    return viewValue;
                });

Code is working absolutely fine as per the expectations, but lint throws error as:

 × Unnecessary 'else' after 'return'. (no-else-return)
 27 |                                     ngModel.$setValidity('unique', false);
 28 |                                     return true; // break out of this loop
 29 |                                 } else {
    |                                        ^
 30 |                                     ngModel.$setValidity('unique', true);
 31 |                                 }
 32 |                             }

How to suppress this error or is there a way to write better code to get rid off this?


Solution

  • To solve the lint warnings, you can use below code.

    if (name && viewValue) {
        let equal = name.toLowerCase() === viewValue.toLowerCase();
        ngModel.$setValidity('unique', !equal);
        if (equal) {
            return true; // break out of this loop
        }
    }
    

    To set the unique status, boolean is used and if this is true, then from if, true is returned.