Proposal: Math.add, Math.sub

# Ates Goral (6 years ago)

(Percolating a comment I made in a thread earlier.)

Math.add

Math.add = function (a, b) {
  return a + b;
};

A why:

With functional-style programming becoming more and more common with the advent of ES5 Array methods, the terse way to find the sum of items in an array can become even more terse with the introduction of Math.add:

const sum = array.reduce((a, b) => a + b);

// becomes:
const sum = array.reduce(Math.add);

Math.sub

Math.sub = function (a, b) {
  return a - b;
};

A [not-so-strong] why:

It's a common "LOL WTF JavaScript" refrain to point out that attempting to sort an array of numbers by using the default Array.prototype.sort results in an unexpected sort order unless a custom comparator is used. The presence of an out-of-the-box Math.sub could make the canonical "proper way to sort numbers" a bit terser:

array.sort((a, b) => a - b);

// becomes:
array.sort(Math.sub);

Ates

# Sam Ruby (6 years ago)

On Sat, May 11, 2019 at 7:38 PM Ates Goral <ates at magnetiq.com> wrote:

(Percolating a comment I made in a thread earlier.)

Math.add

Math.add = function (a, b) {
  return a + b;
};

What should Math.add('1', '2') produce?

  • Sam Ruby
# Vic99999 (6 years ago)

An HTML attachment was scrubbed... URL: esdiscuss/attachments/20190512/8d89daf0/attachment

# guest271314 (6 years ago)

Terse add code const add = a => eval(a.join`+`).

Would fix JavaScript floating point number precision issues and implement BigDecimal first.