CompareArrayElements.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. 'use strict';
  2. var $TypeError = require('es-errors/type');
  3. var Call = require('./Call');
  4. var IsLessThan = require('./IsLessThan');
  5. var ToNumber = require('./ToNumber');
  6. var ToString = require('./ToString');
  7. var isNaN = require('../helpers/isNaN');
  8. // https://262.ecma-international.org/14.0/#sec-comparearrayelements
  9. module.exports = function CompareArrayElements(x, y, compareFn) {
  10. if (typeof compareFn !== 'function' && typeof compareFn !== 'undefined') {
  11. throw new $TypeError('Assertion failed: `compareFn` must be a function or undefined');
  12. }
  13. if (typeof x === 'undefined' && typeof y === 'undefined') {
  14. return 0; // step 1
  15. }
  16. if (typeof x === 'undefined') {
  17. return 1; // step 2
  18. }
  19. if (typeof y === 'undefined') {
  20. return -1; // step 3
  21. }
  22. if (typeof compareFn !== 'undefined') { // step 4
  23. var v = ToNumber(Call(compareFn, void undefined, [x, y])); // step 4.a
  24. if (isNaN(v)) {
  25. return 0; // step 4.b
  26. }
  27. return v; // step 4.c
  28. }
  29. var xString = ToString(x); // step 5
  30. var yString = ToString(y); // step 6
  31. var xSmaller = IsLessThan(xString, yString, true); // step 7
  32. if (xSmaller) {
  33. return -1; // step 8
  34. }
  35. var ySmaller = IsLessThan(yString, xString, true); // step 9
  36. if (ySmaller) {
  37. return 1; // step 10
  38. }
  39. return 0; // step 11
  40. };