add.js 875 B

123456789101112131415161718192021222324252627282930313233343536
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $TypeError = GetIntrinsic('%TypeError%');
  4. var isFinite = require('../../helpers/isFinite');
  5. var isNaN = require('../../helpers/isNaN');
  6. var Type = require('../Type');
  7. // https://262.ecma-international.org/12.0/#sec-numeric-types-number-add
  8. module.exports = function NumberAdd(x, y) {
  9. if (Type(x) !== 'Number' || Type(y) !== 'Number') {
  10. throw new $TypeError('Assertion failed: `x` and `y` arguments must be Numbers');
  11. }
  12. if (isNaN(x) || isNaN(y) || (x === Infinity && y === -Infinity) || (x === -Infinity && y === Infinity)) {
  13. return NaN;
  14. }
  15. if (!isFinite(x)) {
  16. return x;
  17. }
  18. if (!isFinite(y)) {
  19. return y;
  20. }
  21. if (x === y && x === 0) { // both zeroes
  22. return Infinity / x === -Infinity && Infinity / y === -Infinity ? -0 : +0;
  23. }
  24. // shortcut for the actual spec mechanics
  25. return x + y;
  26. };