Merge pull request #745 from Juris-M/simpler-stable-stringify
Simplification of stableStringify()
This commit is contained in:
commit
8ff108cbdf
1 changed files with 11 additions and 32 deletions
|
@ -202,39 +202,18 @@ function resetDB() {
|
|||
* Equivalent to JSON.stringify, except that object properties are stringified
|
||||
* in a sorted order.
|
||||
*/
|
||||
function stableStringify(obj, level, label) {
|
||||
if (!level) level = 0;
|
||||
let indent = '\t'.repeat(level);
|
||||
|
||||
if (label) label = JSON.stringify('' + label) + ': ';
|
||||
else label = '';
|
||||
|
||||
if (typeof obj == 'function' || obj === undefined) return null;
|
||||
|
||||
if (typeof obj != 'object' || obj === null) return indent + label + JSON.stringify(obj);
|
||||
|
||||
if (Array.isArray(obj)) {
|
||||
let str = indent + label + '[';
|
||||
for (let i=0; i<obj.length; i++) {
|
||||
let json = stableStringify(obj[i], level + 1);
|
||||
if (json === null) json = indent + '\tnull'; // function
|
||||
str += '\n' + json + (i < obj.length-1 ? ',' : '');
|
||||
function stableStringify(obj) {
|
||||
return JSON.stringify(obj, function(k, v) {
|
||||
if (v && typeof v == "object" && !Array.isArray(v)) {
|
||||
let o = {},
|
||||
keys = Object.keys(v).sort();
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
o[keys[i]] = v[keys[i]];
|
||||
}
|
||||
return o;
|
||||
}
|
||||
return str + (obj.length ? '\n' + indent : '') + ']';
|
||||
}
|
||||
|
||||
let keys = Object.keys(obj).sort(),
|
||||
empty = true,
|
||||
str = indent + label + '{';
|
||||
for (let i=0; i<keys.length; i++) {
|
||||
let json = stableStringify(obj[keys[i]], level + 1, keys[i]);
|
||||
if (json === null) continue; // function
|
||||
|
||||
empty = false;
|
||||
str += '\n' + json + (i < keys.length-1 ? ',' : '');
|
||||
}
|
||||
|
||||
return str + (!empty ? '\n' + indent : '') + '}';
|
||||
return v;
|
||||
}, "\t");
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
Loading…
Reference in a new issue