What is the best way to integrate properties subsets into your classes?

In my code, I am working with 3 classes ...

class1 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.toClass2 = function() {
      // TODO: return this as an instance of class2;
      // the conversion would remove the unwanted 'b' property
    }
    this.toClass3 = function() {
      // TODO: return this as an instance of class3;
      // the conversion would remove the unwanted 'a' property
    }
  }
}

class2 {
  constructor(a, c) {
    this.a = a;
    this.c = c;
  }
}

class3 {
  constructor(b, c) {
    this.b = b;
    this.c = c;
  }
}

The following statements are accurate ...

  • It is possible for class1 to extend class2
  • It is also possible for class1 to extend class3
  • However, class1 cannot simultaneously extend class2 and class3 due to JavaScript's lack of support for multiple inheritance. This would result in the derived class having 4 properties instead of the desired 3.

  • Class2 is a subset of class1's properties

  • Class3 is a subset of class1's properties

QUERY: How can I effectively implement these classes in JavaScript or TypeScript to ensure that the toClass2 and toClass3 conversion methods operate correctly? Are there any specific design patterns that could be utilized for this scenario? Thank you

Answer №1

There are multiple strategies you can employ to achieve the desired outcome, but it seems like you have presented a simplified example and the ideal approach would vary based on a more comprehensive understanding of your task.

In principle, considering your demonstration, here are a few potential methods worth pondering:

(1) The straightforward method (code in playground):

class A {
    private a: any;
    private b: any;
    private c: any;

    constructor(a: any, b: any, c: any) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    toB(): B {
        return new B(this.a, this.c);
    }
}

class B {
    private a: any;
    private c: any;

    constructor(a: any, c: any) {
        this.a = a;
        this.c = c;
    }
}

(and same with class C)

(2) Utilizing interfaces:

interface InterfaceBase {
    c: any;
}

interface InterfaceB extends InterfaceBase {
    a: any;
}

interface InterfaceC extends InterfaceBase {
    b: any;
}

interface InterfaceA extends InterfaceB, InterfaceC {
    a: any;
}

You could apply the same technique as in the previous solution (code in playground):

class B implements InterfaceB {
    a: any;
    c: any;

    constructor(a: any, c: any) {
        this.a = a;
        this.c = c;
    }
}

class A implements InterfaceA {
    a: any;
    b: any;
    c: any;

    constructor(a: any, b: any, c: any) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    toB(): InterfaceB {
        return new B(this.a, this.c);
    }

    toC(): InterfaceC {
        return new C(this.b, this.c);
    }
}

Alternatively, you can implement a single class that can transform itself (code in playground):

class MyClass implements InterfaceA {
    a: any;
    b: any;
    c: any;

    constructor(meta: InterfaceA) {
        this.a = meta.a;
        this.b = meta.b;
        this.c = meta.c;
    }

    asB(): InterfaceB {
        return this as InterfaceB;
    }

    asC(): InterfaceC {
        return this as InterfaceC;
    }
}

(3) Another option is to incorporate builder pattern, provided it aligns well with your scenario.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to utilize the child component's method?

I am looking to access a child component's method from the parent in Vue.js. To achieve this, I plan on using $refs. Code Example: <template> <div>Parent!</div> </template> Script: <script> Vue.component('c ...

Importing external components from the parent directory in Next.js is a seamless process

I am trying to import react components from an external directory called common into the web-static directory while using nextjs. However, I keep encountering an error that says: Module not found: Can't resolve 'react' in '/Users/jakub ...

Converting Objects to Arrays with Angular Observables

After searching extensively on SO for answers regarding item conversions in Javascript/Angular, I couldn't find a solution that addresses my specific problem. When retrieving data from Firestore as an object with potential duplicates, I need to perfor ...

Authorization missing in Select2 Ajax request

Encountering an issue while attempting a get request to a secure endpoint that requires an Auth token. Despite fetching the token asynchronously from chrome.storage, it fails to be included in the ajax request and results in a 401 error ("Authorization hea ...

What is preventing me from generating a string for transform:translate within Angular.js?

Attempting a new approach here $scope.graph.transform = "transform: translate(" + $scope.graph.width + "," + $scope.graph.height + ");"; Despite my efforts <h3>transform: <span ng-bind="grap ...

What steps should I take to customize WebStorm so that it no longer automatically imports the entire Typescript paths?

Recently, I noticed a change in WebStorm after an update that affected how paths were imported in my files. Initially, when typing @Component and letting WebStorm automatically import the path, it would use the following format: import { Component } from ...

Utilize React JS to serialize form data for submission via a POST request

I have a simple form where users input text and it triggers an AJAX request to create a new comment. var CommentForm = React.createClass({ propTypes: { // ... // ... }, handleFormSubmit: function(e) { e.preventDefault(); var compo ...

unable to respond when clicking an angularjs link

I'm facing an issue where I can't get a link to respond to click events in AngularJS. When I click on the anchor link, nothing happens. Here is a snippet of the AngularJS script: <script data-require="<a href="/cdn-cgi/l/email-protection" ...

Store in database and forward to a different web address

I have created an interactive quiz using jQuery. I need to add a specific feature at the end of the quiz. if (answered_questions === total_questions) { save the user's score to the database; redirect to specified URL; } The redirect_url is ...

The enigmatic dance of Angular and its hidden passcodes

Recently, I've been diving into learning Angular 2 and I'm exploring ways to safeguard the data in my application. I'm curious about how one can prevent data from being accessed on the front end of the app. Could serving the angular app thr ...

The children's className attribute can impact the parent element

As I work on creating a card object, I envision it with the className .card that is styled in CSS as follows: .card img{position:absolute; width:150px; height:160px} I want only the images inside my div to overlap each other while not affecting the divs ...

Transforming text colors dynamically using Vue.js

Here is an Angular code snippet: <div [style.color]="'#' + prod.id.substring(0,6)"> <small>{{ prod.id }}</small> </div> Now I want to create a similar code using vue.js. ...

The issue of receiving a 500 error when making a POST request in node.js

I have created my own unique REST API that utilizes an NLP API internally. I need to post data on their URL, but unfortunately I am encountering an error that is causing my API to return a 500 error to the frontend. Below is a snippet of my server.js code ...

Starting http-server in the background using an npm script

Is there a way to run http-server in the background using an npm script, allowing another npm script, like a Mocha test with jsdom, to make HTTP requests to http-server? To install the http-server package, use: npm install http-server --save-dev In your ...

Game Mapping Techniques: Utilizing Spatial Data Structures

In order to efficiently store and retrieve intersecting rectangles, I am currently working on implementing a spatial data structure in JavaScript. My initial approach involves using a Quad Tree to narrow down the search space. However, for dynamic objects ...

When filling options within an optgroup in a selectbox, the data for each option may override one another

UPDATE: I made a change in my code: $('select[name=productSelect]').setOptions(["All products|ALL", "Products visible to all|VISIBLETOALL=1"]); I updated it to: $('select[name=productSelect]').prepend(["All products|ALL", "Product ...

Receiving an item in place of a true/false indicator

I wrote an asynchronous function that validates the permission status on a device. Here is the function: checkPermission = async () => { const allowed = await requestNotifications(['alert', 'sound']).then((res) => { if ...

Encountering a Lint No Nested Ternary Error while utilizing the ternary operator

Is there a way to prevent the occurrence of the "no nested ternary" error in TypeScript? disablePortal options={ // eslint-disable-next-line no-nested-ternary units=== "mm&quo ...

What is the best way to calculate the sum of table data with a specific class using jQuery?

If I had a table like this: <table class="table questions"> <tr> <td class="someClass">Some data</td> <td class="someOtherclass">Some data</td> </tr> <tr> <td class="s ...

What is the reason behind Angular 2's choice to implement the .ts file extension?

What is the significance of using the .ts file extension in Angular 2? ...