3

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 average score to the standard low / medium / high score.

Low score: 0-30 points
Medium score: 31-60 points
High score: 61-100 points

My question though is how to make my code a bit prettier? I am not sure if the code is considered as clear and efficient.

Any opinions would be much appreciated, thank you

Bibhudatta Sahoo
  • 4,808
  • 2
  • 27
  • 51
shieldcy
  • 592
  • 2
  • 11
  • 35
  • use ternary conditions for that – RAUSHAN KUMAR Jul 25 '17 at 13:16
  • Hello @Halcyon, it was a mistake while I was writing the question. Fixed it – shieldcy Jul 25 '17 at 13:17
  • ternary is best option for shortest way – Jaykumar Gondaliya Jul 25 '17 at 13:18
  • 1
    Aside from the medium/high mixup I don't see anything I'd change in this code. Maybe call `alert` once with a `message` variable. This code is about as clear as it's going to get. _ternary_ operators for more than one comparison gets really messy. – Halcyon Jul 25 '17 at 13:19
  • https://stackoverflow.com/questions/8584902/get-closest-number-out-of-array – caramba Jul 25 '17 at 13:21
  • I think there's something like codereview.codeexchange or something like that i can't check it right now. You may get the answer you're searching for there. – user5014677 Jul 25 '17 at 13:21
  • @user5014677: Indeed. shieldcy, after [checking their guidelines](https://codereview.stackexchange.com/help/on-topic), this might be a better fit for CodeReview. – T.J. Crowder Jul 25 '17 at 13:22
  • 1
    I'm voting to close this question as off-topic because it's probably a better fit for [CodeReview](https://codereview.stackexchange.com); check [their guidelines](https://codereview.stackexchange.com/help/on-topic) to ensure your post is on-topic there. – T.J. Crowder Jul 25 '17 at 13:23
  • Hello, thanks for your answers. I didn't know the existence of "CodeReview", sorry. – shieldcy Jul 25 '17 at 13:24

7 Answers7

3

There is no need for the if else with low, just check from smallest to highest.

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

or you can go the opposite direction and check for the highest first with greater than

epascarello
  • 204,599
  • 20
  • 195
  • 236
1

You could 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');
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Here, we iterate over the various values that make up the score range. The loop will iterate over each score range in turn, meaning you need to have the lowest score first and highest score last. We then save score name against myscore to be alerted out at a later point.

This approach allows for expandability - you can add as many score ranges in the middle without having to add any 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();
Richard Parnaby-King
  • 14,703
  • 11
  • 69
  • 129
1

You could store the messages in an array, and find the correct index like so:

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();

The magic is in the unary plus operator which converts booleans returned by comparisons to 0 or 1 accordingly. It's also easy to include more rankings if needed.

Teemu
  • 22,918
  • 7
  • 53
  • 106
0
mypoints < low ? alert("you get low score") : (mypoints < medium ? alert("you get medium score") : alert("you get high score"))
0

You can use the switch statement

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');
    }   
} 
taha
  • 997
  • 9
  • 17
-1

You can create a function which takes the score and an array as an argument with the different levels and their names {"score": 30, "text": "You got a low score"} and then just loop that and output what is closest to what you sent in and return the matching 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));
KungWaz
  • 1,918
  • 3
  • 36
  • 61