AbstractEqualityComparison.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. var StrictEqualityComparison = require('./StrictEqualityComparison');
  3. var StringToBigInt = require('./StringToBigInt');
  4. var ToNumber = require('./ToNumber');
  5. var ToPrimitive = require('./ToPrimitive');
  6. var Type = require('./Type');
  7. var isNaN = require('../helpers/isNaN');
  8. // https://262.ecma-international.org/11.0/#sec-abstract-equality-comparison
  9. module.exports = function AbstractEqualityComparison(x, y) {
  10. var xType = Type(x);
  11. var yType = Type(y);
  12. if (xType === yType) {
  13. return StrictEqualityComparison(x, y);
  14. }
  15. if (x == null && y == null) {
  16. return true;
  17. }
  18. if (xType === 'Number' && yType === 'String') {
  19. return AbstractEqualityComparison(x, ToNumber(y));
  20. }
  21. if (xType === 'String' && yType === 'Number') {
  22. return AbstractEqualityComparison(ToNumber(x), y);
  23. }
  24. if (xType === 'BigInt' && yType === 'String') {
  25. var n = StringToBigInt(y);
  26. if (isNaN(n)) {
  27. return false;
  28. }
  29. return AbstractEqualityComparison(x, n);
  30. }
  31. if (xType === 'String' && yType === 'BigInt') {
  32. return AbstractEqualityComparison(y, x);
  33. }
  34. if (xType === 'Boolean') {
  35. return AbstractEqualityComparison(ToNumber(x), y);
  36. }
  37. if (yType === 'Boolean') {
  38. return AbstractEqualityComparison(x, ToNumber(y));
  39. }
  40. if ((xType === 'String' || xType === 'Number' || xType === 'BigInt' || xType === 'Symbol') && yType === 'Object') {
  41. return AbstractEqualityComparison(x, ToPrimitive(y));
  42. }
  43. if (xType === 'Object' && (yType === 'String' || yType === 'Number' || yType === 'BigInt' || yType === 'Symbol')) {
  44. return AbstractEqualityComparison(ToPrimitive(x), y);
  45. }
  46. if ((xType === 'BigInt' && yType === 'Number') || (xType === 'Number' && yType === 'BigInt')) {
  47. if (isNaN(x) || isNaN(y) || x === Infinity || y === Infinity || x === -Infinity || y === -Infinity) {
  48. return false;
  49. }
  50. return x == y; // eslint-disable-line eqeqeq
  51. }
  52. return false;
  53. };