Fallthrough issue in Javascript switch statement

1.1k views Asked by At

I have a large array of features with p and u properties. I want to find the smallest and highest p and u in the array and create this switch statement in a loop. This works about 99.9% of the time. However. I have one data set where the max and min turn out to be the same even if the values are evenly distributed and the average is not the same. Stumped.

            switch(true) {
                case p > max_p:
                    max_p = p;
                case u > max_u:
                    max_u = u;
                case p < min_p:
                    min_p = p;
                case u < min_u:
                    min_u = u;
            }

I run through the loop in firebug and can see that max_u gets sometimes updated if u < max_u. For example u = 0.066, max_u = 0.088.

Pycharm tells me about a fallthrough issue but the statement works fine on every other dataset I throw at it.

I can split the statement into two. The performance loss is minor but I would like to understand how this could happen.

Thanks, Dennis

edit:

Split into two statement that dataset works completely fine without a break in the statement.

            switch(true) {
                case p > max_p:
                    max_p = p;
                case p < min_p:
                    min_p = p;
            }
            switch(true) {
                case u > max_u:
                    max_u = u;
                case u < min_u:
                    min_u = u;
            }

edit: I accepted the answer given which works but I am still puzzled why something like this would happen.

enter image description here

1

There are 1 answers

2
Andy On BEST ANSWER

Assuming you have an array of objects with u and p properties (if I've read the question correctly), here's a simple function that will give you the min/max values you want and save you the problems of using switch and/or if conditions.

var arr = [
 { p: 10, u: 101},
 { p: 11, u: 1},
 { p: 1, u: 3},
 { p: 2, u: 7},
 { p: 21, u: 1011},
 { p: 6, u: 2},
 { p: 2, u: 13}
]

function getInt(arr, key, type) {
  return Math[type].apply(null, arr.map(function (el) {
    return el[key];
  }));
}

var min_p = getInt(arr, 'p', 'min'); // 1
var max_p = getInt(arr, 'p', 'max'); // 21
var min_u = getInt(arr, 'u', 'min'); // 1
var max_u = getInt(arr, 'u', 'max'); // 1001

DEMO