简体   繁体   中英

Generate JS class file from Object

I am working on a js tool which will generate Js class file (myclass.js) from an object, for example:

myObj = { width: 0,
  height: 0,
  getWidth: [Function],
  getHeight: [Function] }

I want to generate a js file myClass.js that contains the class:

 class MyClass {

   constructor (width, height) {
    this.width = width;
    this.height = height;
  } 
  getWidth () { return this.width ; }
 getHeight () { return this.height; }

}

I think about myObj.construct.toString() that return all code of class, but it works just when "myObj" is an instance of the class, in my case "MyObj" will generated dynamically.

You have to traverse all keys of myObj and generate + concatenate the code yourself based on each value present there. A rough spaghetti-written implementation would look like:

function objectToClassString(obj = {}, className = 'MyClass') {

  const opener = `class ${className} {`
  const closer = '}'
  const indent = (str: string) => str.replace(/^(.*)/gm, '  $1')

  const ctorArgs = [] // array of `{ argName }` objects
  const getterMethods = [] // array of `{ methodName, property }` objects

  for (const key in obj) {
    const value = obj[key]
    if (Array.isArray(value) && value[0] === Function) {
      getterMethods.push({ methodName: key, property: key.replace(/^get(.)/, (_, letter) => letter.toLowerCase()) })
    } else {
      ctorArgs.push({ argName: key })
    }
  }

  const ctorOpener = `constructor(${ctorArgs.map(data => data.argName).join(', ')}) {`
  const ctorContent = ctorArgs.map(data => `this.${data.argName} = ${data.argName};`).join('\n')
  const ctorCloser = '}'
  const ctor = [ctorOpener, indent(ctorContent), ctorCloser].join('\n')

  const methods = getterMethods
    .map(data => `${data.methodName}() { return this.${data.property}; }`)
    .join('\n')

  const classContent = [
    opener,
    indent(ctor),
    indent(methods),
    closer
  ].join('\n')

  return classContent

}

Usage:

const code = objectToClassString({
  width: 0,
  height: 0,
  getWidth: [Function],
  getHeight: [Function]
})

console.log(code)

Output:

class MyClass {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
  getWidth() { return this.width; }
  getHeight() { return this.height; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM