AbstractEqualityComparison.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict';
  2. var ToNumber = require('./ToNumber');
  3. var ToPrimitive = require('./ToPrimitive');
  4. var Type = require('./Type');
  5. // https://ecma-international.org/ecma-262/6.0/#sec-abstract-equality-comparison
  6. module.exports = function AbstractEqualityComparison(x, y) {
  7. var xType = Type(x);
  8. var yType = Type(y);
  9. if (xType === yType) {
  10. return x === y; // ES6+ specified this shortcut anyways.
  11. }
  12. if (x == null && y == null) {
  13. return true;
  14. }
  15. if (xType === 'Number' && yType === 'String') {
  16. return AbstractEqualityComparison(x, ToNumber(y));
  17. }
  18. if (xType === 'String' && yType === 'Number') {
  19. return AbstractEqualityComparison(ToNumber(x), y);
  20. }
  21. if (xType === 'Boolean') {
  22. return AbstractEqualityComparison(ToNumber(x), y);
  23. }
  24. if (yType === 'Boolean') {
  25. return AbstractEqualityComparison(x, ToNumber(y));
  26. }
  27. if ((xType === 'String' || xType === 'Number' || xType === 'Symbol') && yType === 'Object') {
  28. return AbstractEqualityComparison(x, ToPrimitive(y));
  29. }
  30. if (xType === 'Object' && (yType === 'String' || yType === 'Number' || yType === 'Symbol')) {
  31. return AbstractEqualityComparison(ToPrimitive(x), y);
  32. }
  33. return false;
  34. };