CompareArrayElements.js 1.3 KB

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