最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Alternative to Math.max and Math.min for BigInt type in Javascript - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a comment  | 

2 Answers 2

Reset to default 16

how 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;
}
发布评论

评论列表(0)

  1. 暂无评论