1

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?

1 Answer 1

3

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.

1
  • Absolutely genius, worked like a charm. Thanks @Tushar Commented Apr 17, 2017 at 12:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.