Add probability functions to the Math object

I would like to discuss the possibility of adding functions to the math object related to probabilities, such as factorial (possibly with the addition of the x! operator too), permutations with and without repetition, and combinations with and without repetition. The formulas for these functions are quite simple and they all come from the factorial function which consists of multiplying a given number by every number smaller than itself and bigger than 0 (for example 4 factorial is 4*3*2*1 = 24, and 0 factorial is 1 by convention).
This would be quite useful to have in the native Math object in my opinion, so I'd like to hear other opinions on this!

Welcome @ImRodry ! Thanks for posting.

Things that would need to be considered:

A x! operator would conflict with TypeScript which has it's own post-fix ! operator.

The other risk is that factorials get large very quickly. Anything more than 18! starts to be too large to always express precisely as the result will be larger than Number.MAX_SAFE_INTEGER. So maybe a BigInt would be a more appropriate value to use with larger inputs.

Hey! Thanks for your feedback!

I totally forgot about the conflicts with TypeScript so the x! operator would most likely not be viable, so we can scrap that idea and keep that to the function Math.factorial.
As for the bigint issue, you're right, 19! does go over the max safe integer limit, so my proposal is to accept both numbers and bigints in Math.factorial (since the given value should always be quite small), and then convert them to a bigint, since that should be easily done with no issues. Let me know how that sounds!

While these are useful for certain kinds of program - I've certainly wanted them myself - I would wager that only an extremely small fraction of all JS programs would actually need these. The standard library in JavaScript is generally limited to utilities which are either awkward or impossible to do in user code (e.g. Intl or WeakRef) or things which are needed by a wide variety of programs (e.g. Object.fromEntries).

As such, I think factorial or n-choose-k would not be a great fit for the standard library. As you say, the formulas are quite simple to implement yourself if you need them (or to pull off npm).

1 Like

It is true that it would be fairly easy to create these functions ourselves but I thought they would be more used than you're claiming they would. If you think this isn't worthy of being added then I totally understand your points.