Domanda

I am wondering how I can re-write this function to resolve the JSLint error "unnecessary else after disruption". I understand the basics of this error, and have already rewritten functions of a model like

 myFunction.doThing = function () {
   if (user.likesCats) {
     return patCat;
   }
   else (user.likesDogs {
     return patDog;
   }
 };

to be like this instead:

 myFunction.doThing = function () {
   if (user.likesCats) {
     return patCat;
   }
   return patDog;
 }; 

But I am unsure how to fix the if, else if, else construction in this function so that it conforms to JSLint's "do not continue with unnecessary else's after a break" rule:

myFunction.getRange = function () {
  if (this.settings.allowedValues) {
    return {
      min: Min,
      max: Max
    };
  } else if (this.settings.range) {
    return {
      min: range[0],
      max: range[1]
    };
  } else {
    return {
      min: 0,
      max: 1
    };
  }
};
È stato utile?

Soluzione 2

There are basically two approaches to this: Single Exit Point vs. Early Exit. I personally prefer the latter:

myFunction.getRange = function () {

  if (this.settings.allowedValues) {
    return {
      min: Min,
      max: Max
    };
  } 

  if (this.settings.range) {
    return {
      min: range[0],
      max: range[1]
    };
  }

  return {
    min: 0,
    max: 1
  };

};

In this case it doesn't matter much, but real-life code with early exits (return, break etc) is easier to read and maintain than "single exit" one with many else branches and temp variables.

Altri suggerimenti

Wouldn't you just set a variable instead of returning it

myFunction.getRange = function () {
    var range;
    if (this.settings.allowedValues) {
        range = {
            "min": Min,
            "max": Max
        };
    } else if (this.settings.range) {
        range = {
            "min": range[0],
            "max": range[1]
        };
    } else {
        range = {
            "min": 0,
            "max": 1
        };
    }
    return range;
};

Just get rid of the final else - it's not needed. If the previous conditions aren't met it will just return those values anyway.

myFunction.getRange = function () {
  if (this.settings.allowedValues) {
    return {
      min: Min,
      max: Max
    };
  } else if (this.settings.range) {
    return {
      min: range[0],
      max: range[1]
    };
  }
  return { min: 0, max: 1 };
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top