vendredi 6 mai 2022

Create class with dynamic name and properties (vanilla JS)

I'm trying to solve this challenge:

You are asked to implement the builder design pattern for rendering simple chunks of code.

Sample use of the builder you are asked to create:

let ob = new ObjectBuilder('Person')
ob.addField('name').addField('age');
console.log(ob.toString());

The expected output of the above code is:

class Person {
  constructor(name, age) {
   this.name = name;
   this.age = age;
  }
}

My challenge is how to implement a builder for creating dynamic classes!


class ObjectBuilder {
    constructor(className) {
        // todo
    }

    addField(name) {
        // todo
        // reminder: we want a fluent interface
    }

    toString() {
        // todo
    }
}

How to implement ObjectBuilder?

Aucun commentaire:

Enregistrer un commentaire