The code I have is:
var level = function (d) {
if (value(d) > median + stdev) {
return 1;
} else if (value(d) > median) {
return 2
I'd recommend to avoid multiple calls to value
:
function level(d) {
var diff = value(d) - median;
if (diff > 0) {
if (diff > stdev)
return 1;
else
return 2;
else
if (diff > -stdev)
return 3;
else
return 4;
}
Also I've nested the if-else-statements in a (hopefully) more meaningful structure - that depends on your usecase though. Might be more helpful if you returned values like -2
, -1
, 1
and 2
instead or something. A ternary operator could save you some writing, but it's not necessarily getting clearer.
Alternatively, some maths could help you:
function level(d) {
var diff = value(d) - median;
return 2 + (diff > 0 ? -.5 : .5) * (Math.abs(diff) > stdev ? 3 : 1);
}
Though it leads to 3
instead of 4
in case value(d) === median-stdev
. See @6502's answer on how to avoid that.