-1
\$\begingroup\$
function score_to_grade(score1) {

  var score = 100 - score1;

  if (score == 100)
    return 'A+';
  else if (score > 93)
    return 'A';
  else if (score > 87)
    return 'A-';
  else if (score > 81)
    return 'B+';
  else if (score > 69 )
    return 'B';
  else if (score > 63 )
    return 'B-';
  else if (score > 56 )
    return 'C+';
  else if (score > 44 )
    return 'C';
  else if (score > 38 )
    return 'C-';
  else if (score > 32 )
    return 'D+';
  else if (score > 19 )
    return 'D';
  else if (score == 0 )
    return 'F';
  else
    return 'D-';
}
\$\endgroup\$
2
\$\begingroup\$
function score_to_grade(pointsLost) {

  // A more meaningful name to what's subtracted from the total
  var score = 100 - pointsLost

  // A map of grade to score in "at least" basis. Examples, an A is at least 93.
  // You can easily add and remove mappings here
  var map = [
    ['A+', 100],
    ['A', 93],
    ['A-', 87],
    ['B+', 81],
    ['B', 69],
    ['B-', 63],
    ['C+', 56],
    ['C', 44],
    ['C-', 38],
    ['D+', 32],
    ['D', 19],
    ['D-', 1],
    ['F', 0]
  ]

  // Loop through the map and check if the score is at least a certain level
  for (var i = 0; i < map.length; i++) {
    if (score >= map[i][1]) return map[0];
  }
}
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ That assumes iterating over the properties of an object is in definition order... which you shouldn't... \$\endgroup\$ – Jeff Mercado Oct 26 '13 at 0:55
3
\$\begingroup\$

A switch statement would serve you much better in this case.

I'm not quite sure what the line var score = 100 - score1; does. is score1 the number of points the test-taker lost? It could use a much better name, such as pointsLost.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Perhaps it is just some kind of conversion. In GER we have some strange dual grading schemes: 1) [1,2,3,4,5,6] which is equivalent to US [A,B,C,D,E,F] but on the other hand a scoring system [15/14/13, 12/11/10, 9/8/7, 6/5/4, 3/2/1, 0] where you would have to write a conversion from the lower to the higher. Perhaps in this case there is a similar case. We never know ;) \$\endgroup\$ – Thomas Junk Oct 26 '13 at 0:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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