Alternative To Math.max And Math.min For Bigint Type In Javascript
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 (
Solution 1:
how about
constbigIntMax = (...args) => args.reduce((m, e) => e > m ? e : m);
constbigIntMin = (...args) => args.reduce((m, e) => e < m ? e : m);
also if you want both then
constbigIntMinAndMax = (...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),
);
Solution 2:
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):
functionbigint_min(...args){
if (args.length < 1){ throw'Min of empty list'; }
m = args[0];
args.forEach(a=>{if (a < m) {m = a}});
return m;
}
functionbigint_max(...args){
if (args.length < 1){ throw'Max of empty list'; }
m = args[0];
args.forEach(a=>{if (a > m) {m = a}});
return m;
}
Post a Comment for "Alternative To Math.max And Math.min For Bigint Type In Javascript"