AbstractRelationalComparison.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 IsStringPrefix = require('./IsStringPrefix');
  7. var StringToBigInt = require('./StringToBigInt');
  8. var ToNumeric = require('./ToNumeric');
  9. var ToPrimitive = require('./ToPrimitive');
  10. var Type = require('./Type');
  11. var BigIntLessThan = require('./BigInt/lessThan');
  12. var NumberLessThan = require('./Number/lessThan');
  13. // https://262.ecma-international.org/9.0/#sec-abstract-relational-comparison
  14. // eslint-disable-next-line max-statements, max-lines-per-function
  15. module.exports = function AbstractRelationalComparison(x, y, LeftFirst) {
  16. if (typeof LeftFirst !== 'boolean') {
  17. throw new $TypeError('Assertion failed: LeftFirst argument must be a Boolean');
  18. }
  19. var px;
  20. var py;
  21. if (LeftFirst) {
  22. px = ToPrimitive(x, $Number);
  23. py = ToPrimitive(y, $Number);
  24. } else {
  25. py = ToPrimitive(y, $Number);
  26. px = ToPrimitive(x, $Number);
  27. }
  28. if (typeof px === 'string' && typeof py === 'string') {
  29. if (IsStringPrefix(py, px)) {
  30. return false;
  31. }
  32. if (IsStringPrefix(px, py)) {
  33. return true;
  34. }
  35. return px < py; // both strings, neither a prefix of the other. shortcut for steps 3 c-f
  36. }
  37. var pxType = Type(px);
  38. var pyType = Type(py);
  39. var nx;
  40. var ny;
  41. if (pxType === 'BigInt' && pyType === 'String') {
  42. ny = StringToBigInt(py);
  43. if ($isNaN(ny)) {
  44. return void undefined;
  45. }
  46. return BigIntLessThan(px, ny);
  47. }
  48. if (pxType === 'String' && pyType === 'BigInt') {
  49. nx = StringToBigInt(px);
  50. if ($isNaN(nx)) {
  51. return void undefined;
  52. }
  53. return BigIntLessThan(nx, py);
  54. }
  55. nx = ToNumeric(px);
  56. ny = ToNumeric(py);
  57. var nxType = Type(nx);
  58. if (nxType === Type(ny)) {
  59. return nxType === 'Number' ? NumberLessThan(nx, ny) : BigIntLessThan(nx, ny);
  60. }
  61. if ($isNaN(nx) || $isNaN(ny)) {
  62. return void undefined;
  63. }
  64. if (nx === -Infinity || ny === Infinity) {
  65. return true;
  66. }
  67. if (nx === Infinity || ny === -Infinity) {
  68. return false;
  69. }
  70. return nx < ny; // by now, these are both nonzero, finite, and not equal
  71. };