Search code examples
javascriptmathematical-optimization

Need Javascript mathematical expression or formula to place number range in groups


Need some quick help determining an equation or formula for taking a given number with min/max range, and evaluating it into 1 of 3 'groups.' Being a bit lazy I know, but wanted to see if there was a clever equation I could use rather than a switch/case statement.

Input:

0–5

Output (groups/returned integers):

0, 1, or 2

Mapping (input must fall into/equal output):

0–2 = 0
3 = 1
4–5 = 2

Solution

  • You're not going to do better performance-wise than the switch/case. But if you want extra-clever, howsabout:

    (x >> 2) + (x >= 3)