stuff.
This commit is contained in:
76
src/inc/trigger/lib/serialize.mjs
Normal file
76
src/inc/trigger/lib/serialize.mjs
Normal file
@@ -0,0 +1,76 @@
|
||||
export default new class serialize {
|
||||
FUNCFLAG = "_$$ND_FUNC$$_";
|
||||
CIRCULARFLAG = "_$$ND_CC$$_";
|
||||
KEYPATHSEPARATOR = "_$$.$$_";
|
||||
|
||||
getKeyPath(obj, path) {
|
||||
let currentObj = obj;
|
||||
path.split(this.KEYPATHSEPARATOR).forEach((p, index) => {
|
||||
if (index)
|
||||
currentObj = currentObj[p];
|
||||
});
|
||||
return currentObj;
|
||||
}
|
||||
serialize(obj, outputObj, cache, path) {
|
||||
path = path || "$";
|
||||
cache = cache || {};
|
||||
cache[path] = obj;
|
||||
outputObj = outputObj || {};
|
||||
|
||||
if(Array.isArray(obj))
|
||||
return JSON.stringify(obj);
|
||||
|
||||
for(let key in obj) {
|
||||
if(obj.hasOwnProperty(key)) {
|
||||
if(Array.isArray(obj[key]))
|
||||
outputObj[key] = obj[key];
|
||||
else if(typeof obj[key] === "object" && obj[key] !== null) {
|
||||
let found = false;
|
||||
for(let subKey in cache) {
|
||||
if (cache.hasOwnProperty(subKey)) {
|
||||
if (cache[subKey] === obj[key]) {
|
||||
outputObj[key] = this.CIRCULARFLAG + subKey;
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!found)
|
||||
outputObj[key] = this.serialize(obj[key], outputObj[key], cache, path + this.KEYPATHSEPARATOR + key);
|
||||
}
|
||||
else if(typeof obj[key] === "function")
|
||||
outputObj[key] = this.FUNCFLAG + obj[key].toString();
|
||||
else
|
||||
outputObj[key] = obj[key];
|
||||
}
|
||||
}
|
||||
return (path === "$") ? JSON.stringify(outputObj) : outputObj;
|
||||
}
|
||||
unserialize(obj, originObj) {
|
||||
let isIndex;
|
||||
if (typeof obj === "string") {
|
||||
obj = JSON.parse(obj);
|
||||
isIndex = true;
|
||||
}
|
||||
originObj = originObj || obj;
|
||||
|
||||
let circularTasks = [];
|
||||
for(let key in obj) {
|
||||
if(obj.hasOwnProperty(key)) {
|
||||
if(typeof obj[key] === "object")
|
||||
obj[key] = this.unserialize(obj[key], originObj);
|
||||
else if(typeof obj[key] === "string") {
|
||||
if(obj[key].indexOf(this.FUNCFLAG) === 0)
|
||||
obj[key] = eval("(" + obj[key].substring(this.FUNCFLAG.length) + ")");
|
||||
else if(obj[key].indexOf(this.CIRCULARFLAG) === 0) {
|
||||
obj[key] = obj[key].substring(this.CIRCULARFLAG.length);
|
||||
circularTasks.push({obj: obj, key: key});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isIndex)
|
||||
circularTasks.forEach(task => task.obj[task.key] = this.getKeyPath(originObj, task.obj[task.key]));
|
||||
return obj;
|
||||
}
|
||||
};
|
Reference in New Issue
Block a user