Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get source code of a JavaScript class constructor

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 }
})
like image 401
Javier Vélez Avatar asked May 07 '26 18:05

Javier Vélez


1 Answers

So, I got the solution. Follow following steps -

  1. Get the Class and convert it to string using toString().
  2. Get the constructor part of the resulting string using regexp.
  3. Break the substring into array. Perform pop() and shift() to remove unnecessary part of array.
  4. Finally, join the array as a string.

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");
}
like image 154
Praneet Dixit Avatar answered May 09 '26 07:05

Praneet Dixit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!