Skip to content

Instantly share code, notes, and snippets.

@renatoargh
Created January 4, 2020 11:20
Show Gist options
  • Save renatoargh/482100a646dd166e7fb01727cc5b9063 to your computer and use it in GitHub Desktop.
Save renatoargh/482100a646dd166e7fb01727cc5b9063 to your computer and use it in GitHub Desktop.
const className = 'StateId'
const interfaceName = 'StateIdInterface'
const data = ` state: string;
value: string;
isActive: boolean;
toJSON(): { [key: string]: any };`
const members = data
.replace(/\n/g, '')
.split(';')
.filter(l => l)
.map(l => {
const [, name, type] = l.trim().match('(.*?):(.*)$')
return {
name: name.trim(),
type: type.trim()
}
})
const privateMembers = members
.filter(m => !m.name.endsWith('()'))
.map(m => `private _${m.name}: ${m.type};`)
.join('\n')
const constructorParameters = members
.filter(m => !m.name.endsWith('()'))
.map(m => `${m.name}: ${m.type}`)
.join(', ')
const constructorAssignments = members
.filter(m => !m.name.endsWith('()'))
.map(m => `this._${m.name} = ${m.name};`)
.join('\n')
const getters = members
.filter(m => !m.name.endsWith('()'))
.map(m => `get ${m.name}() { return this._${m.name} };`)
.join('\n\n')
const methodDeclarations = members
.filter(m => m.name.endsWith('()'))
.map(m => `${m.name}: ${m.type} { throw new Error('Not Implemented') };`)
.join('\n')
const clazz = `
export class ${className} implements ${interfaceName} {
${privateMembers}
constructor(${constructorParameters}) {
${constructorAssignments}
}
${getters}
${methodDeclarations}
}
`
console.log(clazz.trim())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment