1 | import isPlainObject from 'is-plain-obj';
|
2 |
|
3 | export default function sortKeys(object, options = {}) {
|
4 | if (!isPlainObject(object) && !Array.isArray(object)) {
|
5 | throw new TypeError('Expected a plain object or array');
|
6 | }
|
7 |
|
8 | const {deep, compare} = options;
|
9 | const seenInput = [];
|
10 | const seenOutput = [];
|
11 |
|
12 | const deepSortArray = array => {
|
13 | const seenIndex = seenInput.indexOf(array);
|
14 | if (seenIndex !== -1) {
|
15 | return seenOutput[seenIndex];
|
16 | }
|
17 |
|
18 | const result = [];
|
19 | seenInput.push(array);
|
20 | seenOutput.push(result);
|
21 |
|
22 | result.push(...array.map(item => {
|
23 | if (Array.isArray(item)) {
|
24 | return deepSortArray(item);
|
25 | }
|
26 |
|
27 | if (isPlainObject(item)) {
|
28 | return _sortKeys(item);
|
29 | }
|
30 |
|
31 | return item;
|
32 | }));
|
33 |
|
34 | return result;
|
35 | };
|
36 |
|
37 | const _sortKeys = object => {
|
38 | const seenIndex = seenInput.indexOf(object);
|
39 | if (seenIndex !== -1) {
|
40 | return seenOutput[seenIndex];
|
41 | }
|
42 |
|
43 | const result = {};
|
44 | const keys = Object.keys(object).sort(compare);
|
45 |
|
46 | seenInput.push(object);
|
47 | seenOutput.push(result);
|
48 |
|
49 | for (const key of keys) {
|
50 | const value = object[key];
|
51 | let newValue;
|
52 |
|
53 | if (deep && Array.isArray(value)) {
|
54 | newValue = deepSortArray(value);
|
55 | } else {
|
56 | newValue = deep && isPlainObject(value) ? _sortKeys(value) : value;
|
57 | }
|
58 |
|
59 | Object.defineProperty(result, key, {
|
60 | ...Object.getOwnPropertyDescriptor(object, key),
|
61 | value: newValue
|
62 | });
|
63 | }
|
64 |
|
65 | return result;
|
66 | };
|
67 |
|
68 | if (Array.isArray(object)) {
|
69 | return deep ? deepSortArray(object) : object.slice();
|
70 | }
|
71 |
|
72 | return _sortKeys(object);
|
73 | }
|