1

is there a way to serialize source code p.e. functions into a functionless list of statements?

function foo() {
   console.log("foo");
}

function moo(value) {
   [...Array(value)].forEach(_=> {foo()});
}

moo(3);

leads to

// moo(3);
console.log("foo"); // foo()
console.log("foo"); // foo()
console.log("foo"); // foo()
inselberg
  • 549
  • 3
  • 13
  • 27
  • `fn.toString()` will serialise a function and you can re-construct it given that 1. `fn` is a straight up function, not, say a serialised one. 2. There are no external dependencies (e.g., values captured by closure) 3. `toString()` is not overwritten 4. it's not a native implementation – VLAZ Mar 17 '21 at 06:59
  • Why do you need this? What is the problem you're trying to solve? There are *a lot* of edge cases when you start to try and manipulate JS constructs as just code. There is no 1:1 mapping in all cases. You might have greater success using other techniques but we need to know what the goal is. – VLAZ Mar 17 '21 at 07:02
  • Finding/counting repeating code segments in a large (minified) code base in order to optimize core functions. A more code like append than pe clincjs does. – inselberg Mar 17 '21 at 07:35
  • Does this answer your question? [How can I serialize a function in JavaScript?](https://stackoverflow.com/questions/7395686/how-can-i-serialize-a-function-in-javascript) – Adam Mar 23 '21 at 05:35
  • No. As explained bellow. – inselberg Mar 23 '21 at 10:16

1 Answers1

-1

You can actually serialize a function by converting it to string (.toString())

function foo() {
   console.log("foo");
}

function moo(value) {
   [...Array(value)].forEach(_=> {foo()});
}

moo(3);

const stringFunction = moo.toString();

console.log({stringFunction})

const deserializedFunction = new Function('return ' + stringFunction.toString())()

Btw, there's no native way to do that like PHP serialize, deserialize functions.

Adam
  • 6,447
  • 1
  • 12
  • 23
  • Doesn't work with all functions, for example `parseInt` or `flip(foo)` will give you something that you cannot deseralise. – VLAZ Mar 17 '21 at 07:00
  • 1
    I'm not sure if that's what OP wants to serialize but it works with their provided functions. – Adam Mar 17 '21 at 07:02
  • Adam, exactly it s about getting a simplifyed order of execution statement list. That's why i quoted "serialized". – inselberg Mar 17 '21 at 07:38
  • how do you serialize native functions? – savram Apr 20 '22 at 18:34