SortIndexedProperties.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var callBound = require('call-bind/callBound');
  4. var $TypeError = GetIntrinsic('%TypeError%');
  5. var DeletePropertyOrThrow = require('./DeletePropertyOrThrow');
  6. var Get = require('./Get');
  7. var HasProperty = require('./HasProperty');
  8. var IsIntegralNumber = require('./IsIntegralNumber');
  9. var Set = require('./Set');
  10. var ToString = require('./ToString');
  11. var Type = require('./Type');
  12. var isAbstractClosure = require('../helpers/isAbstractClosure');
  13. var $push = callBound('Array.prototype.push');
  14. var $sort = callBound('Array.prototype.sort');
  15. // https://ecma-international.org/ecma-262/13.0/#sec-sortindexedproperties
  16. module.exports = function SortIndexedProperties(obj, len, SortCompare) {
  17. if (Type(obj) !== 'Object') {
  18. throw new $TypeError('Assertion failed: Type(obj) is not Object');
  19. }
  20. if (!IsIntegralNumber(len) || len < 0) {
  21. throw new $TypeError('Assertion failed: `len` must be an integer >= 0');
  22. }
  23. if (!isAbstractClosure(SortCompare) || SortCompare.length !== 2) {
  24. throw new $TypeError('Assertion failed: `SortCompare` must be an abstract closure taking 2 arguments');
  25. }
  26. var items = []; // step 1
  27. var k = 0; // step 2
  28. while (k < len) { // step 3
  29. var Pk = ToString(k);
  30. var kPresent = HasProperty(obj, Pk);
  31. if (kPresent) {
  32. var kValue = Get(obj, Pk);
  33. $push(items, kValue);
  34. }
  35. k += 1;
  36. }
  37. var itemCount = items.length; // step 4
  38. $sort(items, SortCompare); // step 5
  39. var j = 0; // step 6
  40. while (j < itemCount) { // step 7
  41. Set(obj, ToString(j), items[j], true);
  42. j += 1;
  43. }
  44. while (j < len) { // step 8
  45. DeletePropertyOrThrow(obj, ToString(j));
  46. j += 1;
  47. }
  48. return obj; // step 9
  49. };