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