AbstractRelationalComparison.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $Number = GetIntrinsic('%Number%');
  4. var $TypeError = require('es-errors/type');
  5. var $isNaN = require('../helpers/isNaN');
  6. var $isFinite = require('../helpers/isFinite');
  7. var IsStringPrefix = require('./IsStringPrefix');
  8. var ToNumber = require('./ToNumber');
  9. var ToPrimitive = require('./ToPrimitive');
  10. // https://262.ecma-international.org/9.0/#sec-abstract-relational-comparison
  11. module.exports = function AbstractRelationalComparison(x, y, LeftFirst) {
  12. if (typeof LeftFirst !== 'boolean') {
  13. throw new $TypeError('Assertion failed: LeftFirst argument must be a Boolean');
  14. }
  15. var px;
  16. var py;
  17. if (LeftFirst) {
  18. px = ToPrimitive(x, $Number);
  19. py = ToPrimitive(y, $Number);
  20. } else {
  21. py = ToPrimitive(y, $Number);
  22. px = ToPrimitive(x, $Number);
  23. }
  24. if (typeof px === 'string' && typeof py === 'string') {
  25. if (IsStringPrefix(py, px)) {
  26. return false;
  27. }
  28. if (IsStringPrefix(px, py)) {
  29. return true;
  30. }
  31. return px < py; // both strings, neither a prefix of the other. shortcut for steps 3 c-f
  32. }
  33. var nx = ToNumber(px);
  34. var ny = ToNumber(py);
  35. if ($isNaN(nx) || $isNaN(ny)) {
  36. return undefined;
  37. }
  38. if ($isFinite(nx) && $isFinite(ny) && nx === ny) {
  39. return false;
  40. }
  41. if (nx === Infinity) {
  42. return false;
  43. }
  44. if (ny === Infinity) {
  45. return true;
  46. }
  47. if (ny === -Infinity) {
  48. return false;
  49. }
  50. if (nx === -Infinity) {
  51. return true;
  52. }
  53. return nx < ny; // by now, these are both nonzero, finite, and not equal
  54. };