index.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 'use strict';
  2. const isPlainObj = require('is-plain-obj');
  3. module.exports = (obj, opts) => {
  4. if (!isPlainObj(obj)) {
  5. throw new TypeError('Expected a plain object');
  6. }
  7. opts = opts || {};
  8. // DEPRECATED
  9. if (typeof opts === 'function') {
  10. throw new TypeError('Specify the compare function as an option instead');
  11. }
  12. const deep = opts.deep;
  13. const seenInput = [];
  14. const seenOutput = [];
  15. const sortKeys = x => {
  16. const seenIndex = seenInput.indexOf(x);
  17. if (seenIndex !== -1) {
  18. return seenOutput[seenIndex];
  19. }
  20. const ret = {};
  21. const keys = Object.keys(x).sort(opts.compare);
  22. seenInput.push(x);
  23. seenOutput.push(ret);
  24. for (let i = 0; i < keys.length; i++) {
  25. const key = keys[i];
  26. const val = x[key];
  27. if (deep && Array.isArray(val)) {
  28. const retArr = [];
  29. for (let j = 0; j < val.length; j++) {
  30. retArr[j] = isPlainObj(val[j]) ? sortKeys(val[j]) : val[j];
  31. }
  32. ret[key] = retArr;
  33. continue;
  34. }
  35. ret[key] = deep && isPlainObj(val) ? sortKeys(val) : val;
  36. }
  37. return ret;
  38. };
  39. return sortKeys(obj);
  40. };