Created
March 5, 2021 12:40
-
-
Save GerBawn/77ffeae9b9b2c4a865c3be278c6a50e8 to your computer and use it in GitHub Desktop.
可序列化函数的序列化方法
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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