Shortest way to compare your score to 3 ranges in jQuery

I have the following code:

function display_message() {
    var low = data.result[0].max; //returns 30
    var medium = data.result[1].max; // returns 60
    var high = data.result[2].max; // returns 100

    // mypoints are 67 for example
    if(mypoints > low) {
        if(mypoints > medium) {
            alert('You got a high score');
        } else {
            alert('You got a medium score');
        }
    } else {
        alert('You got a low score');
    }
}

      

This code works fine. I compare my GPA to a standard low / medium / high score.

Low score: 0-30 points


Average score: 31-60 points


High score:61-100 points

My question, though, is how to make my code a little prettier? I'm not sure if the code is considered clear and efficient.

Any opinions would be much appreciated, thanks

+3


source to share


7 replies


No need for if else with low, just check from lowest to highest.

if (mypoints <= low) {
  //low msg
} else if (mypoints <= medium) {
  //medium msg
} else {
  //high msg
}

      



or you can go in the opposite direction and check the height first with more than

+3


source


You can use a condition without nested conditions.



if (mypoints > medium) {
    alert('You got a high score');
} else if (mypoints > low) {
    alert('You got a medium score');
} else {
    alert('You got a low score');
}

      

+1


source


Here, we iterate over the different values ​​that make up the evaluation range. The loop will iterate over each range of scores in turn , which means that you need to have the lowest score first and highest score last. We then save the name of the counter with myscore

to be alerted later.

This approach allows extensibility - you can add the same score ranges in the middle without adding more if / else blocks.

let data = {result: [{max: 30}, {max: 60}, {max: 100}]},
    mypoints = 67;

function display_message() {
  let score_range = {
      low: data.result[0].max, //returns 30
      medium: data.result[1].max, // returns 60
      high: data.result[2].max // returns 100
    },
    myscore = 'fail';

  for (var score in score_range) {
    if (score_range.hasOwnProperty(score)) {
      if (mypoints > score_range[score]) {
        myscore = score;
      }
    }
  }
  alert('You got a ' + myscore + ' score!');
}
display_message();
      

Run codeHide result


+1


source


You can store the messages in an array and find the correct index, for example:

function display_message() {
    var low = 30,
        medium = 60,
        rank;
    mypoints = 67; // for example
    rank = ['low', 'medium', 'high'][+(mypoints > low) + +(mypoints > medium)];
    console.log('You got a ' + rank + ' score');
}

display_message();
      

Run codeHide result


The magic is in the unary plus operator, which converts booleans returned by comparison with 0 or 1, respectively. Plus, it's easy to include more ranks when needed.

+1


source


mypoints < low ? alert("you get low score") : (mypoints < medium ? alert("you get medium score") : alert("you get high score"))

      

0


source


You can use the operator switch

function display_message() {
    var low = data.result[0].max; //returns 30
    var medium = data.result[1].max; // returns 60
    var high = data.result[2].max; // returns 100

    switch (true) {
      case mypoints > medium:
        alert('You got a high score');
        break;
      case mypoints > low:
        alert('You got a medium score');
        break;
      default:
        alert('You got a low score');
    }   
} 

      

0


source


You can create a function that takes an estimate and an array as an argument with different levels and their names {"score": 30, "text": "You got a low score"}

, and then just loops that and outputs what is closest to what you sent and returns the appropriate text.

Example:

var myScore = 50,
    scoreIntervals = [{
            "score": 30,
            "text": "Low score"
        },{
            "score": 60,
            "text": "Average score"
        },{
            "score": 100,
            "text": "High score"
        }];

function evaluateScore(score, scoreIntervals) {
    var output = scoreIntervals[scoreIntervals.length - 1].text;
    $.each(scoreIntervals, function(key, val) {
        if(score <= val.score) {
            output = val.text;
            return false;
        }
    });
    return output;
}

console.log(evaluateScore(myScore, scoreIntervals));

      

-1


source







All Articles