Skip to content

Instantly share code, notes, and snippets.

@ancms2600
Created March 24, 2019 04:29
Show Gist options
  • Save ancms2600/dae4565370d7972ebd0c9845c5da42b4 to your computer and use it in GitHub Desktop.
Save ancms2600/dae4565370d7972ebd0c9845c5da42b4 to your computer and use it in GitHub Desktop.
[Compact JSON] Serializer - Inspired by Kibana's table params stored in URI hash
/*
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
*/
'use strict';
(exports => {
const RX_IDENTIFIER = /^[a-z_$\\][a-zA-Z0-9$_\\.]{0,511}$/;
const is = v => null != v;
const empty = o => (undefined === o ||
(Array.isArray(o) && 0 === o.length) ||
(null != o && 'object' === typeof o && 0 === Object.keys(o).length));
const toPairs = o => Object.keys(o).map(k=>[k,o[k]]);
const RX_DOT = /\./;
exports.Serializer = {
serialize(o) {
if (empty(o)) return '';
if (null === o) return 'N';
if (true === o) return 'T';
if (false === o) return 'F';
if (Number.isNaN(o)) return 'Na';
if (Number.POSITIVE_INFINITY === o) return 'Ip';
if (Number.NEGATIVE_INFINITY === o) return 'In';
if ('number' === typeof o) return ''+ o;
if ('string' === typeof o) {
if (RX_IDENTIFIER.test(o[0])) return o;
return JSON.stringify(o);
}
if (Array.isArray(o))
return '['+ o.map(exports.Serializer.serialize).join(',') +']';
if ('object' == typeof o)
return '{'+ toPairs(o).filter(kv=>!empty(kv[1])).map(kv=>
kv.map(exports.Serializer.serialize).join(':'))
.join(',') +'}';
},
deserialize(s) {
if ('string' !== typeof s || '' === s.trim()) return undefined;
let match;
const RX = /(T)|(F)|(Na)|(N)|(Ip)|(In)|([+\-.0-9][.0-9e\-]{0,19})|"(?:()"|(.{0,99}?[^\\])")|([a-z_$\\][a-zA-Z0-9$_\\.]{0,511})|(\{)|(\[)|(\})|(\])|(,)|(:)/g;
const stack = [];
let c, k;
const put = v => {
if (Array.isArray(c)) c.push(v);
else if (null != c && 'object' === typeof c) {
if (null == k) k = v;
else {
c[k] = v;
k = null;
}
}
else c = v;
return v;
};
const push = v => {
stack.push(c);
c = v;
};
const pop = v =>
c = stack.pop();
while (is(match = RX.exec(s))) { // for each match
const [,isTrue,isFalse,
isNaN,isNull,isInfinity,isNegInfinity,isNumber,
isEmptyString,isQuotedString,isStringIdentifier,
isObjectOpen,isArrayOpen,isObjectClose,isArrayClose,
/*isObjectOrArrayDelim,isObjectKVDelim*/] = match;
if (isNull) put(null);
else if (isTrue) put(true);
else if (isFalse) put(false);
else if (isNaN) put(Number.NaN);
else if (isInfinity) put(Infinity);
else if (isNegInfinity) put(Number.NEGATIVE_INFINITY);
else if (isNumber) put(RX_DOT.test(isNumber) ? parseFloat(isNumber) : parseInt(isNumber, 10));
else if (isEmptyString) put('');
else if (isQuotedString) put(JSON.parse(`"${isQuotedString.replace(/\\"/g, '"')}"`));
else if (isStringIdentifier) put(JSON.parse(`"${isStringIdentifier}"`));
else if (isObjectOpen) push(put({}));
else if (isArrayOpen) push(put([]));
else if (isObjectClose || isArrayClose) pop();
// else if (isObjectOrArrayDelim || isObjectKVDelim) continue;
}
return 0 === stack.length ? c : stack[0];
},
};
})(typeof exports === 'undefined' ? window : exports); // browser compatible
const assert = require('chai').assert;
const { Serializer } = require('../../../../shared/public/components/serializer');
describe('Serializer', () => {
it('serialize', async () => {
const TESTS = [
'', '',
[], '',
{}, '',
null, 'N',
true, 'T',
false, 'F',
Number.NaN, 'Na',
Infinity, 'Ip',
Number.POSITIVE_INFINITY, 'Ip',
Number.NEGATIVE_INFINITY, 'In',
0, '0',
12, '12',
3.45, '3.45',
-6.7, '-6.7',
+1.23e-4, '0.000123',
-1.23e-4, '-0.000123',
'aBc10', 'aBc10',
'_aBc10', '_aBc10',
'$a', '$a',
'_a', '_a',
'_', '_',
'$', '$',
'abc.def.ghi', 'abc.def.ghi',
'G', '"G"',
'\t', '"\\t"',
'\\t', '\\t',
[1,2,3], '[1,2,3]',
{a:'b',c:4}, '{a:b,c:4}',
{a:1,b:2,c:undefined,d:null,e:[]}, '{a:1,b:2,d:N}',
];
for (let i=0; i<TESTS.length; i+=2) {
const input = TESTS[i];
const expected = TESTS[i+1];
const output = Serializer.serialize(input);
console.log(`test#${i/2}`, { input, output });
assert.deepEqual(output, expected);
}
});
it('deserialize', async () => {
const TESTS = [
'', undefined,
'N', null,
'T', true,
'F', false,
'Na', Number.NaN,
'Ip', Infinity,
'In', Number.NEGATIVE_INFINITY,
'0', 0,
'.12', 0.12,
'12', 12,
'3.45', 3.45,
'-6.7', -6.7,
'0.000123', +1.23e-4,
'-0.000123', -1.23e-4,
'+1.23e-4', 0.000123,
'-1.23e-4', -0.000123,
'aBc10', 'aBc10',
'_aBc10', '_aBc10',
'$a', '$a',
'_a', '_a',
'_', '_',
'$', '$',
'abc.def.ghi', 'abc.def.ghi',
'"G"', 'G',
'"\\t"', '\t',
'\\t', '\t',
'[1,2,3', [1,2,3],
'{a:b,c:4', {a:'b',c:4},
'{a:b,c:d,e:f,g:h', {a:"b",c:"d",e:"f",g:"h"},
'{x{a:T,b:F,c:N,d:hi', {x:{a:true,b:false,c:null,d:'hi'}},
'{x{a:T,b:F,c:N,d.e:hi}f:0,"G":1', {x:{a:true,b:false,c:null,'d.e':'hi'},f:0,G:1},
'{a:0', {a:0},
'{table{report{columns[ip,patch_count,severity,vuln_count,patch_published,patch_title],groups[os]',
{table:{report:{columns:["ip","patch_count","severity","vuln_count","patch_published","patch_title"],groups:["os"]}}},
];
for (let i=0; i<TESTS.length; i+=2) {
const input = TESTS[i];
const expected = TESTS[i+1];
const output = Serializer.deserialize(input);
console.log(`test#${i/2}`, JSON.stringify({ input, output }));
assert.deepEqual(output, expected);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment