AbstractRelationalComparison.js 1.5 KB

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