Skip to content

Instantly share code, notes, and snippets.

@drom
Last active April 19, 2021 21:46
Show Gist options
  • Save drom/86facb54fe0875b0e63bb7598df06310 to your computer and use it in GitHub Desktop.
Save drom/86facb54fe0875b0e63bb7598df06310 to your computer and use it in GitHub Desktop.
restructure json file format
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const glob = require('glob');
const tag = {
key: '\u001b[36m',
boolean: '\u001b[33m',
number: '\u001b[35m',
string: '\u001b[32m',
function: '\u001b[33m',
reset: '\u001b[0m'
};
const ess = /["'`\n\r]/g;
const eso = {
'"': '\\"',
'\n': '\\n',
'\r': '\\r',
'\'': '\\\'',
'`': '\\`'
};
const esf = chr => eso[chr];
const escape = str => str.replace(ess, esf);
const stylize = (text, type, options) =>
(options && options.ansi)
? tag[type] + text + tag.reset
: text;
const indent = txt => {
const arr = txt.split('\n');
if (arr.length === 1) {
return ' ' + txt;
}
const res = arr.map(function(e) {
if (e === '') {
return e;
}
return ' ' + e;
});
return res.join('\n');
};
const stringify = (value, options) => {
let res;
const qt = '"';
if (value === undefined) return 'undefined';
if (value === null) return 'null';
if (value === true) return stylize('true', 'boolean', options);
if (value === false) return stylize('false', 'boolean', options);
const type = Object.prototype.toString.call(value);
switch (typeof value) {
case 'boolean':
return stylize(value, 'boolean', options);
case 'number':
return stylize(value.toString(), 'number', options);
case 'string':
return stylize(qt + escape(value) + qt, 'string', options);
case 'function':
return stylize(qt + value.toString() + qt, 'function', options);
case 'object':
switch (type) {
case '[object Array]':
if (value.every(e => (typeof e === 'number'))) {
return '[' + value.join(', ') + ']';
}
res = value.map(function(e) {
return (stringify(e, options));
});
if (res.length < 2) {
return '[' + res.join(', ') + ']';
}
return '[\n' + indent(res.join(',\n')) + '\n]';
default:
res = Object.keys(value).reduce(function(acc, key) {
if (value[key] === undefined) {
return acc;
}
return acc.concat(qt + key + qt + ': ' + stringify(value[key], options));
}, []);
if (res.length <= (options.propsPerLine || 2)) {
return '{' + res.join(', ') + '}';
}
return '{\n' + indent(res.join(',\n')) + '\n}';
}
default:
return type;
}
};
glob('./libraries/*/*/cells/*/*.lib.json', async (er, files) => {
let f1total = 0;
let f3total = 0;
for (const file of files) {
const f1 = await fs.promises.readFile(file);
const f2 = JSON.parse(f1);
const f3 = stringify(f2, {
propsPerLine: 1
});
// console.log(f3);
f1total += f1.length;
f3total += f3.length;
console.log(f1.length + ' -> ' + f3.length + ' = ' + (100 * f3.length / f1.length) + ' %');
}
console.log(f1total + ' -> ' + f3total + ' = ' + (100 * f3total / f1total) + ' %');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment