I need to create a method GetCode returning a string with the source code of a constructor function for any class. For instance,
let code = GetCode (class CX {
constructor () {
this.x = 1
this.y = 1
this.fx ()
this.fy ()
}
fx () {}
fy () {}
})
should return some similar than this in the code variable:
`
this.x = 1
this.y = 1
this.fx ()
this.fy ()
`
For regular methods such as fx or fy a simple .toString invocation is enough. But when that is done on the constructor function, the returned string is the whole text of the class and not the inner source code of the function. I have tried to parse the string returned by CX.toString () to fetch exactly the fragment of text I need using tools such as JSCodeShift but the fingerprint is too heavy (5Mb).
I wonder if would be possible to devise a hack to get the string with the source code I need.
Other Example:
let code = GetCode (class CX {
constructor ({ min, max }) {
if (min < max) {
for (let x = min; x < max; x++) {
console.log (x)
}
}
this.min = min
this.max = max
}
fmin () { return this.min }
fmax () { return this.min }
})
So, I got the solution. Follow following steps -
toString().constructor part of the resulting string using regexp.pop() and shift() to remove unnecessary part of array.The below snippet explains it all -
console.log(getCode(class CX {
constructor () {
this.x = 1;
this.y = 1;
this.fx ();
this.fy ();
}
fx () {}
fy () {}
}));
console.log(getCode(class CX {
constructor ({ min, max }) {
if (min < max) {
for (let x = min; x < max; x++) {
console.log (x)
}
}
this.min = min
this.max = max
}
fmin () { return this.min }
fmax () { return this.min }
}));
function getCode(inputClass){
let regx = /constructor[\s\S]+?(?=}\n[A-Za-z\s\*]*\(\)[\s]*{)/g;
let code = inputClass.toString();
let arr = code.match(regx)[0].split("\n");
arr.pop();
arr.shift();
return arr.join("\n");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With