Combining switch statements from various classes

Is there a way to merge switch statements from two different classes, both with the same function name, into one without manually overriding the function or copying and pasting code?

Class A:

protected casesHandler(): void
    {
        switch (case){
            case 0:
                break;
            default:
                super.caseHandler();
        }
    }

Class B:

protected casesHandler(): void
    {
        switch (case){
            case 1:
                break;
            default:
                super.caseHandler();
        }
    }

desired outcome:

protected casesHandler(): void
    {
        switch (case){
            case 0:
                break;
            case 1:
                break;
            default:
                super.caseHandler();
        }
    }

attempting to avoid:

protected casesHandler(): void
    {
        switch (case){
            case 0:
                break;
            default:
                super.caseHandler();
        }

        switch (case){
            case 1:
                break;
            default:
                super.caseHandler();
        }
    }

Answer №1

There is no clear method to achieve that task, and even if a workaround was possible, it would not result in clean code.

An alternative approach could be to encapsulate this logic within a basic function and then import it as needed:

export const handleCases = (val: number): void => {
  switch (val) {
    case 0:
      // code
    case 1:
      // code
    default:
      // code
  }
}

Answer №2

Comparing these functions, it is evident that they are not alike. The presence of super in super.caseHandler() indicates that it is fixed to a particular parent class. Therefore, the behavior of default varies in each of the casesHandler methods, making it perfectly acceptable to override the casesHandler.

To facilitate this, one could establish abstractions following a defined convention:

protected casesHandler(): boolean {
    switch (case) {
        case 0:
            break;
        default:
            return false;
    }

    return true;
}

protected casesWithDefaultHandler(): void
    const isCaseSolved = this.casesHandler();

    if (!isCaseSolved)
        super.caseHandler();
}

This structure allows for the combination of multiple casesHandler functions.

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 it possible to utilize both body-parser and Formidable simultaneously?

I've been working on a problem for a few days now, but I'm having trouble understanding certain aspects of it. My website is built using NodeJS and ExpressJS, with form handling done through body-parser. var adName = req.body.adName; var adMess ...

Adding an object to a document's property array based on a condition in MongoDB using Mongoose

I have a situation where I need to push an object with a date property into an array of objects stored in a MongoDB document. However, I only want to push the object if an object with the same date doesn't already exist in the array. I've been e ...

Guide to Chrome's Document Object Model and JavaScript Reference

Does Chrome have a Javascript/DOM Reference page similar to the Mozilla Developer Network? I am curious about other websites that provide detailed information on Chrome's specific interpretations of web standards. ...

Retrieve the input field's value with Selenium, verify its accuracy, and proceed to log a message to the console

Hey there! I'm facing a challenge while working with Selenium Webdriver, specifically Chrome Webdriver and writing tests in JavaScript. The problem is in a section of the code where I can't seem to grab the value typed into an input field using t ...

Apply CSS styling (or class) to each element of a React array of objects within a Component

One issue I'm facing involves adding specific properties to every object in an array based on another value within that same object. One such property is the background color. To illustrate, consider an array of objects: let myObj = { name: "myO ...

Reformat a JSON file and save as a new file

I have a lengthy list of one-level JSON data similar to the example below: json-old.json [ {"stock": "abc", "volume": "45434", "price": "31", "date": "10/12/12"}, {"stock": "abc", "volume": "45435", "price": "30", "date": "10/13/12"}, {"stock": "xyz", "vo ...

When incorporating <Suspense> in Next.js, the button's interaction was unexpectedly lost

'use client' import React, { Suspense } from "react"; const AsyncComponent = async () => { const data = await new Promise((r) => { setTimeout(() => { r('Detail'); }, 3000) }) as string; return <div>{d ...

Tips for detecting when multiple image sources have finished loading in an *ngFor loop

I have an array of image URLs that are displayed in a repetitive manner using the *ngFor directive in my HTML code. The technology stack used for this project includes Ionic 4 and Angular 10. <div *ngFor="let url of imagesToLoad; let i = index&quo ...

On smaller screens, the top placement of right sidebar links is necessary

Our website layout is organized into 3 main sections: the top part contains the main menu, followed by the main content and a sidebar specific to each page. The main content and sidebar are structured using bootstrap col-* classes. On small screens, I en ...

Oops! The Element Type provided is not valid - it should be a string

I have a desire to transition from using Victory Native to Victory Native XL. However, I am encountering an error message saying Render Error Element type is invalid. import * as React from "react"; import { View } from "react-native"; ...

Trigger an event within a linked component

I've been working on a connected component where I'm attempting to dispatch the clear action from. Here's a snippet of the code: import {createElement} from 'react'; import reduce from 'lodash/fp/reduce'; import {connect ...

Choosing based on conditions within a function

I am currently working with an object that contains orders from a restaurant. var obj = { orders: [ null, { date: "2018-07-09 10:07:18", orderVerified : true, item: [ { name ...

Using data fetched from PHP in HTML via jQuery post: A step-by-step guide

I have created a function in jQuery that uses $.post to send data to a PHP file. The query in the PHP file is working fine and returning the data back successfully. JavaScript code: function send_agenda_data(cidade_data){ var data = {'cidade_dat ...

When attempting to use nodejs's collection.find() method with MongoDB, no response is received

I have been struggling to develop a node.js script that can retrieve only the records with a specific string key-value pair from a MongoDB collection containing around 30,000 documents. When I run this query on my MongoDB server, it gives me the exact res ...

Unlocking the full potential of parsing messages using google protobuf-js

Currently, I am developing a front-end application using Angular5+ that utilizes google-protobuf JS and WebSocket for backend communication. Within my .proto files, I have defined 2 objects: a Request object. a Notification object. I have created a han ...

Can the table be automatically updated on page reload?

My goal is to populate a table using $.ajax(), but the content is not showing up when the page first loads. Is there something missing in my implementation of the $.ajax() function? Here's the HTML structure: <div class="row"> <div clas ...

Investigating High Energy Usage on Vue.js Websites: Identifying the Root Causes

My Vue.js application has grown to be quite large with over 80 .vue components. Users have been complaining about their phone batteries draining quickly and Safari displaying a "This webpage is using significant energy..." warning. I have tried investigat ...

The act of exporting an enum from a user-defined TypeScript path leads to the error message "Module not

I have set up a custom path as explained in this particular discussion. "baseUrl": ".", "paths": { "@library/*": [ "./src/myFolder/*" ], } Within this module, I am exporting an Enum. export enum EN ...

I can't seem to retrieve my email using the code provided. The second console statement is not displaying any information. Why might this be happening?

I've been struggling to retrieve the email entered in a form and print it in the console. Despite my code compiling without errors, the email is not being fetched. My goal is to utilize nodemailer for sending registration emails, but I'm encounte ...

Is it possible for JavaScript to interface with MySQL databases?

Is it possible to establish a connection between JavaScript and MySQL? If yes, what is the process? ...