IsLooselyEqual.js 1.7 KB

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