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

Pass a parameter to an AJAX request in order to retrieve data from a JSON file that is limited to a specific

I am working with a JSON file named example.json, structured as follows: { "User1": [{ "Age":21, "Dogs":5, "Cats":0 }], "User2": [{ "Age":19, "Dogs":2, "Cats":1 }] "User3 ...

exploring the depths of nested objects and utilizing the 'for in

My issue involves receiving a json response from an API that includes objects within objects. It looks something like this: {Object}->{results}->{manyObjects} When I execute the following code: var list = data.results.list; for(val in list){ ...

How do prototype, the $.extend method, and the concept of "return this" all connect with each other?

I've been assigned a legacy project, and I find myself puzzled by the purpose of this code. define(['jquery', 'components/BaseComponent', 'bootstrap'], function( $, BaseComponent, bootstrap ) { 'use strict&a ...

Inquiry about how TypeScript handles object property references when passed into functions

As a newcomer to TypeScript, I am exploring the creation of a range slider with dual handles using D3.js. I have developed a simple class for managing the slider objects: export class VerticalRangeSlider{ private sliderContainer: d3.Selection<SVGG ...

Which is the optimal choice: subscribing from within a subscription or incorporating rxjs concat with tap?

After storing data in the backend, I proceed to retrieve all reserved data for that specific item. It is crucial that the data retrieval happens only after the reservation process to ensure its inclusion. Presented with two possible solutions, I am cont ...

Invoke a function from a different vue.js component using the this.$refs property

I'm facing an issue with triggering a sibling element. What I've tried so far <b-img @click="callFileLoader"/> <b-file type="file" ref="fileUploader"></b-file> ... methods:{ callFileLoader () { this.$refs.fileUploader.c ...

Rails not receiving JSON data

I am attempting a straightforward ajax call in Rails 4, but encountering issues with retrieving the json response. Below is the script I'm working with: $(document).on "submit", "form[name=upvote-form]", -> form = $(this) $.post "/vote", $(th ...

Execute a series of promises sequentially, ensuring that each subsequent promise is only run after the previous one has been resolved

I am in the process of creating a script that will execute all found .sql files within a designated folder one by one. The objective is to halt the execution if any one of the scripts fails. The structure of my folders is as follows (and I initiate the scr ...

React Native application fails to return any values from an asynchronous operation in App function

Completely new to React Native, this is my first attempt at coding. I'm struggling with returning jsx from my App() function due to an asynchronous operation within it. Here's the code that I believe clearly demonstrates my issue: import React fr ...

Alter the color of a single character using JQuery, all while keeping the HTML tags unchanged

I'm currently working on iterating through the DOM using JQuery in order to change the color of every occurrence of the letter m. Here is what I have so far: $(document).ready(function(){ var m = "<span style='color: red;'>m</span& ...

What is the most efficient way to retrieve the key at a specific index within a JavaScript map object?

If I have the map object shown below: const items = new Map([['item1','A'], ['item2','B'], ['item3', 'C']]) I am trying to retrieve the key at index 2. Is there a method other than using a for ...

I'm receiving a typeerror when trying to access the uid property of null, even though I don't have any asynchronous code and the users are logged

I am currently working on developing a user profile edit page that redirects users to their unique profile after logging in. However, I keep encountering an error that says Uncaught (in promise) TypeError: Cannot read properties of null (reading 'uid& ...

Error TS2339 encountered in ngx-uploader: There is no property called 'lastModifiedDate' on the type 'File'

An issue has arisen in the code at node_modules/ngx-uploader/src/ngx-uploader/classes/ngx-uploader.class.ts(112,32): error TS2339: Property 'lastModifiedDate' is not found on type 'File'. Encountered this error while updating my An ...

Tips for combining or adding duplicated values in a Javascript array

I am facing a problem with an array object that looks like this: [ {"item_id":1,"name":"DOTA 2 Backpack","image":"XXX","qty":1,"original_price":1450000,"total_price":1450000}, {"item_id":2,"name":"Mobile Legend Backpack","image":"XXX","qty":1,"origin ...

What is the process for activating an event when a window undergoes a change?

I created a window using the window.open method to display a form. Once the user submits the form, they are redirected to a page called success.html. Is there a way to trigger an event after success.html finishes loading? I attempted the following approach ...

Transfer a csv file from a static webpage to an S3 bucket

Looking to create a webpage for uploading csv files to an S3 bucket? I recently followed a tutorial on the AWS website that might be helpful. Check it out here. I made some modifications to accept filename parameters in my method, and everything seems to ...

Display the current position of the caret in a field that cannot be edited

Can a virtual caret be displayed between two letter boundaries in HTML/CSS/JavaScript, for example in a regular div without using contenteditable=true? Imagine having the following: <div>Hello world</div> If I were to click between the "w" a ...

Refreshing a jsp page without the need to reload the content

On my jsp page, I am displaying the contents of a constantly changing table. This means that users have to refresh the page every time they want to see updated information. Is there a way for me to update the content dynamically without requiring users t ...

Struggling to find a solution for changing the color of a select box when an option is chosen

Here's an example of the HTML I'm working with: <select onclick="colorchanger()"> <option name="white" value="0">--Select--</option> <option name="red" value="1">Work</option> <option name="green" value="2" ...

Guide to verifying the property value following mocking a function: Dealing with Assertion Errors in Mocha

Based on a recommendation from a discussion on this link, I decided to mock the readFileSync function and then mocked my outer function. Now, my goal is to verify whether the variable's value has been set as expected. file.js const fs1 = require ...