index.js 788 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. 'use strict';
  2. var isPlainObj = require('is-plain-obj');
  3. module.exports = function (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. opts = {compare: opts};
  11. }
  12. var deep = opts.deep;
  13. var seenInput = [];
  14. var seenOutput = [];
  15. var sortKeys = function (x) {
  16. var seenIndex = seenInput.indexOf(x);
  17. if (seenIndex !== -1) {
  18. return seenOutput[seenIndex];
  19. }
  20. var ret = {};
  21. var keys = Object.keys(x).sort(opts.compare);
  22. seenInput.push(x);
  23. seenOutput.push(ret);
  24. for (var i = 0; i < keys.length; i++) {
  25. var key = keys[i];
  26. var val = x[key];
  27. ret[key] = deep && isPlainObj(val) ? sortKeys(val) : val;
  28. }
  29. return ret;
  30. };
  31. return sortKeys(obj);
  32. };