SortIndexedProperties.js 1.6 KB

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