base256-archive
Version:
Simple archive format that produces a base256-encoded string.
46 lines (45 loc) • 1.44 kB
JavaScript
/* IMPORT */
import Base256 from 'base256-encoding';
import { IDENTITY, TYPE_ARRAY, TYPE_OBJECT } from './constants.js';
/* HELPERS */
const Helpers = {
/* API */
getDivider: (packed) => {
if (packed === TYPE_ARRAY || packed === TYPE_OBJECT)
return;
const match = /\n-+\n/.exec(packed);
const divider = match?.[0];
if (!divider)
throw new Error('Malformed archive, divider not found');
return divider;
},
getObject: (packed, divider, decode = true) => {
const decoder = decode ? (value) => Base256.decodeStr(value) : IDENTITY;
const sections = divider ? packed.split(divider) : [packed];
const type = sections[0];
const values = sections.slice(1);
if (type === TYPE_ARRAY) {
return values.map(decoder);
}
else {
const object = {};
for (let i = 0, l = values.length; i < l; i += 2) {
const key = Base256.decodeStr(values[i]);
const value = decoder(values[i + 1]);
object[key] = value;
}
return object;
}
}
};
/* MAIN */
const Unpacker = {
/* API */
unpack: (packed, options) => {
const divider = Helpers.getDivider(packed);
const object = Helpers.getObject(packed, divider, options?.decode);
return object;
}
};
/* EXPORT */
export default Unpacker;