Created
April 10, 2020 12:52
-
-
Save bng44270/0120a68b45b3274475bcbed083c38a3b to your computer and use it in GitHub Desktop.
Serialize Functions in JavaScript
This file contains 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
/* | |
Define/Run serialized functions in JavaScript | |
Define serialized function: | |
var serialF = SerDef(function(a,b) { | |
return { | |
sum : a + b, | |
avg : (a + b)/2 | |
}; | |
}); | |
Contents of this Serialized function: | |
{ | |
args : ["a","b"], | |
code : "return {sum : a + b,avg : (a + b)/2};" | |
} | |
Running serialized function: | |
var serialResult = SerRun(serialF)(10,20); | |
Function output: | |
{ sum : 30, avg : 15 } | |
*/ | |
var SerDef = function(target) { | |
if (typeof target != 'function') throw new TypeError; | |
return { | |
args : target.toString().replace(/[ \t]*\n[ \t]*/g,'').replace(/^function\(([^)]+)\).*$/,'$1').split(','), | |
code : target.toString().replace(/[ \t]*\n[ \t]*/g,'').replace(/^function[ \t]*\([^)]+\)[ \t]*{[ \t]*(.*)[ \t]*}[ \t]*$/,'$1').trim() | |
}; | |
}; | |
var SerRun = function(source) { | |
if (Object.keys(source).indexOf('args') == -1 || Object.keys(source).indexOf('code') == -1) throw new SyntaxError; | |
if (typeof source.args != 'object' || typeof source.code != 'string') throw new TypeError; | |
eval('function newFunction(' + source.args.join(',') + ') { ' + source.code + '}'); | |
return newFunction; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment