Skip to content

Instantly share code, notes, and snippets.

@dyatlov
Created June 23, 2016 11:13
Show Gist options
  • Save dyatlov/35a9cf315f84b26139986378615b7fb5 to your computer and use it in GitHub Desktop.
Save dyatlov/35a9cf315f84b26139986378615b7fb5 to your computer and use it in GitHub Desktop.
Save json objects compactly in memory. Save just unique key names and values
'use strict';
class JsonArch
{
constructor(){
this.storage = {keys: [], values: {}};
this.objs = [];
}
add_recursive(obj, storage){
let o = {};
let idx, mkey;
Object.keys(obj).forEach(key=>{
if ((idx=this.storage.keys.indexOf(key)) === -1)
this.storage.keys.push(key);
mkey = idx === -1 ? this.storage.keys.length-1 : idx;
if (!storage[mkey])
storage[mkey] = [];
if (obj[key] == null || typeof obj[key] !== 'object')
{
if ((idx=storage[mkey].indexOf(obj[key])) === -1)
storage[mkey].push(obj[key]);
o[mkey] = idx === -1 ? storage[mkey].length-1 : idx;
}
else
o[mkey] = this.add_recursive(obj[key], storage[mkey]);
});
return o;
}
add(obj){
this.objs.push(this.add_recursive(obj, this.storage.values));
}
extract_recursive(obj, storage){
let o = {};
Object.keys(obj).forEach(key=>{
if (typeof obj[key] !== 'object')
o[this.storage.keys[key]] = storage[key][obj[key]];
else
o[this.storage.keys[key]] = this.extract_recursive(obj[key],
storage[key]);
});
return o;
}
extract(){
let objs = [];
this.objs.forEach(o=>{
objs.push(this.extract_recursive(o, this.storage.values));
});
return objs;
}
}
module.exports = JsonArch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment