DEV Community

Discussion on: 10 Helpful JavaScript Utility Functions

Collapse
 
tracygjg profile image
Tracy Gilmore

Hi Markus, I can fully understand why the parameter orientation appears counterintuitive - because it is until you consider the following.

1) Out of min and max which one is most likely to change? I would say max.
2) What is likely to be the value of min in the majority of use cases? I would guess 0 and in many cases 1.
3) What is likely to be the value of max in the majority of use cases? I do not think we can guess that one.

So my rationale goes:
If the majority of calls set min to 0 we should have that as the default value. In order to set a default value, the parameter must follow all parameters without a default value. Given the range of variation in the value of max, we cannot determine a convenient default value so it will have to come before min.

Conversely, I think using the rest operator (...arg) means we do not care what order they are we can just use Math.min and Math.max to extract them, and as you have done above, set min to zero when only 1 values has been supplied. So, here is another option (no better or worse, just different.)

function random(...args) {
  const max = Math.max(...args);
  const min = (args.length === 1) ? 0 : Math.min(...args);

  return Math.floor(Math.random() * (max - min + 1)) + min;
}
Enter fullscreen mode Exit fullscreen mode