I need to generate a minimum and maximum value for a range of speeds (slow, medium, fast), the user can specify any combination of the 3 values, and receive a range that encompasses all.
Given any combination of "slow"
, "medium"
, "fast"
, getRange()
will return a [min, max]
range.
The function can be called in the following ways:
// Any combination of the values
getRange(['slow', 'medium', 'fast']); // [0, 100]
getRange(['medium', 'fast']); // [36, 100]
getRange(['slow']); // [0, 35]
// Or just a single string
getRange('fast'); // [76, 100]
// No string specified
getRange(); // [0, 100]
Is there any way to simplify my code? It seems a bit clunky and there's probably a simpler way of writing this:
function getRange(speed){
var min, max;
if(speed && speed.length){
var obj = {};
if(Array.isArray(speed)){
speed.forEach(function(s){
obj[s] = true;
});
}
else{
obj[speed] = true;
}
if(obj.slow){
min = 0;
max = 35;
}
if(obj.medium){
if(typeof min == 'undefined'){
min = 36;
}
max = 75;
}
if(obj.fast){
if(typeof min == 'undefined'){
min = 76;
}
max = 100;
}
}
if(typeof min == 'undefined'){
min = 0;
}
if(typeof max == 'undefined'){
max = 100;
}
return [min, max];
};