Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- {
- "Person": {
- "firstName": "string",
- "lastName": "string",
- "location": "Location"
- },
- "Location": {
- "country": "string",
- "region": "string",
- "city": "string",
- "address": "string"
- }
- }
- */
- generateClass('Person', {
- firstName: 'string',
- lastName: 'string',
- location: 'Location'
- });
- function generateClass(className, classProps) {
- const props = Object.entries(classProps);
- const privatePropLines = generatePrivatePropsLines(props);
- const constructorLines = generateConstructorLines(className);
- const getSetLines = generateGetSetLines(props);
- const classLines = generateClassLines(className, privatePropLines, constructorLines, getSetLines);
- const classText = generateTextFromLines(classLines);
- return classText;
- }
- function generatePrivatePropsLines(props) {
- return [
- ...props.map(([name, type]) => generatePrivatePropLine(name, type)),
- ''
- ];
- }
- function generatePrivatePropLine(name, type) {
- type = type || 'unknown';
- return `private _${name}: ${type};`;
- }
- function generateConstructorLines(className) {
- return [
- `constructor(init: Partial<${className}> = {}) {`,
- '\tObject.assign(this, init});',
- '}',
- ''
- ];
- }
- function generateGetSetLines(props) {
- const lines = [];
- for (const [name, type] of props) {
- lines.push(
- ...generateGetLines(name, type),
- ...generateSetLines(name, type),
- ''
- );
- }
- return lines;
- }
- function generateGetLines(name, type) {
- return [
- `get ${name}(): ${type} {`,
- `\treturn this._${name};`,
- '}'
- ];
- }
- function generateSetLines(name, type) {
- return [
- `set ${name}(value: ${type}) {\n`,
- `\tthis._${name} = value;`,
- '}'
- ];
- }
- function generateClassLines(className, privatePropLines, constructorLines, getSetLines) {
- return [
- `export class ${className} {`,
- '',
- ...privatePropLines.map(x => `\t${x}`),
- ...constructorLines.map(x => `\t${x}`),
- ...getSetLines.map(x => `\t${x}`),
- '}'
- ];
- }
- function replaceTabs(line) {
- return line.replace(/\t/, ' ');
- }
- function generateTextFromLines(lines) {
- return lines.map(x => replaceTabs(x)).join('\n');
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement