In Javascript: Math.max and Math.min do not work for BigInt types.
For example:
> Math.max(1n, 2n)
Thrown:
TypeError: Cannot convert a BigInt value to a number
at Math.max (<anonymous>)
>
Is there a built in function that performs these operations on BigInts?
In Javascript: Math.max and Math.min do not work for BigInt types.
For example:
> Math.max(1n, 2n)
Thrown:
TypeError: Cannot convert a BigInt value to a number
at Math.max (<anonymous>)
>
Is there a built in function that performs these operations on BigInts?
Share Improve this question asked Apr 20, 2020 at 13:36 LexLex 2,0962 gold badges20 silver badges31 bronze badges2 Answers
Reset to default 16how about
const bigIntMax = (...args) => args.reduce((m, e) => e > m ? e : m);
const bigIntMin = (...args) => args.reduce((m, e) => e < m ? e : m);
also if you want both then
const bigIntMinAndMax = (...args) => {
return args.reduce(([min,max], e) => {
return [
e < min ? e : min,
e > max ? e : max,
];
}, [args[0], args[0]]);
};
const [min, max] = bigIntMinAndMax(
BigInt(40),
BigInt(50),
BigInt(30),
BigInt(10),
BigInt(20),
);
After some googleing it looks like the answer is no, Javascript has no builtin functions for this.
Here is an implementation of min and max for bigints that matches the signature of the built in ones, except that it throws errors for empty lists (instead of returning +/-Infinity, as BigInt can't represent infinity):
function bigint_min(...args){
if (args.length < 1){ throw 'Min of empty list'; }
m = args[0];
args.forEach(a=>{if (a < m) {m = a}});
return m;
}
function bigint_max(...args){
if (args.length < 1){ throw 'Max of empty list'; }
m = args[0];
args.forEach(a=>{if (a > m) {m = a}});
return m;
}