remainder.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. var $TypeError = require('es-errors/type');
  3. var isNaN = require('../../helpers/isNaN');
  4. var isFinite = require('../../helpers/isFinite');
  5. var truncate = require('../truncate');
  6. // https://262.ecma-international.org/14.0/#sec-numeric-types-number-remainder
  7. module.exports = function NumberRemainder(n, d) {
  8. if (typeof n !== 'number' || typeof d !== 'number') {
  9. throw new $TypeError('Assertion failed: `n` and `d` arguments must be Numbers');
  10. }
  11. // If either operand is NaN, the result is NaN.
  12. // If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
  13. if (isNaN(n) || isNaN(d) || !isFinite(n) || d === 0) {
  14. return NaN;
  15. }
  16. // If the dividend is finite and the divisor is an infinity, the result equals the dividend.
  17. // If the dividend is a zero and the divisor is nonzero and finite, the result is the same as the dividend.
  18. if (!isFinite(d) || n === 0) {
  19. return n;
  20. }
  21. if (!isFinite(n) || !isFinite(d) || n === 0 || d === 0) {
  22. throw new $TypeError('Assertion failed: `n` and `d` arguments must be finite and nonzero');
  23. }
  24. var quotient = n / d;
  25. var q = truncate(quotient);
  26. var r = n - (d * q);
  27. if (r === 0 && n < 0) {
  28. return -0;
  29. }
  30. return r;
  31. };