Skip to content

Instantly share code, notes, and snippets.

@GerBawn
Created March 5, 2021 12:40
Show Gist options
  • Save GerBawn/77ffeae9b9b2c4a865c3be278c6a50e8 to your computer and use it in GitHub Desktop.
Save GerBawn/77ffeae9b9b2c4a865c3be278c6a50e8 to your computer and use it in GitHub Desktop.
可序列化函数的序列化方法
const arrayFunctionRegExp = /^\s*\([\w\s,]*\)\s*=>/; //箭头函数
const commonFunctionRegExp = /^\s*function\s*\(/; //普通的以function xxx()定义的函数
function serialize(obj) {
return JSON.stringify(obj, (key, value) => {
if (typeof value === "function") {
let str = value + "";
if (!commonFunctionRegExp.test(str) && !arrayFunctionRegExp.test(str)) {
str = `function ${str}`;
}
return str;
}
return value;
});
}
function parse(str) {
let obj;
try {
obj = JSON.parse(str, (key, value) => {
if (/^function/.test(value) || arrayFunctionRegExp.test(value)) {
return eval(`(function(){ return ${value};})()`);
}
return value;
});
} catch (err) {}
return obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment