DEV Community

Discussion on: 10 Helpful JavaScript Utility Functions

Collapse
 
tracygjg profile image
Tracy Gilmore • Edited

Hi Technophile, Nice collection. As requested, here are a couple of suggestions.

Number 4 random(): I would assume in practice this function will be called with a min parameter of zero more than any other value, so why not set it as the default? In order to do so the parameters need to be swapped so max comes first. It might also be worth considering a third parameter of precision, defaulted to zero, to provide values other than integers. The parameter can be used as a multiplier as follows 10 ** precision.

Number 10 localStorage(), could easily be extended to support sessionStorage as well, and at the same time take the key in a function.

Collapse
 
daghall profile image
Markus Daghall

Having the max parameter first is counterintuitive to me. Making the parameters dynamic is more in line with other APIs. For example:

 function random(...args) {
  if (args.length === 1) {
    args.unshift(0);
  }

  const [min, max] = args;
  return Math.floor(Math.random() * (max - min + 1)) + min;
};
Enter fullscreen mode Exit fullscreen mode
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
Collapse
 
dostonnabotov profile image
Technophile

Thanks for the suggestions! 😃 Will definitely look into that ✔️