Achieving inheritance in a streamlined and effective manner

What is the most effective approach to eliminate repetitive code?

let BaseErrorResponse = function(mes, rti, rsi, st) {
    return {
        "message": msg,
        "response_type_id": rti,
        "response_status_id": rsi,
        "status": st
    }
};


let InvalidParamResponse = function(mes, rti, rsi, st, ip) {
    return {
        "message": msg,
        "response_type_id": rti,
        "response_status_id": rsi,
        "status": st,
        "invalid_params": ip
    }
};


let SuccessResponse = function(msg, rti, rsi, st, data) {
    return {
        "message": null,
        "response_type_id": null,
        "response_status_id": null,
        "status": null,
        "data": {}
    }
};

Answer №1

If you want to combine objects, you can simply use the Object.assign() method:

let BaseError = function(message, typeId, statusId, statusCode) {
    return {
        "message": message,
        "type_id": typeId,
        "status_id": statusId,
        "status_code": statusCode
    }
};


let InvalidParameterError = function(message, typeId, statusId, statusCode, params) {
    return Object.assign(BaseError(message, typeId, statusId, statusCode), {
        "invalid_params": params
    });
};


let SuccessMessage = function(message, typeId, statusId, statusCode, resultData) {
    return Object.assign(BaseError(message, typeId, statusId, statusCode), {
        "data": {}
    });
};

Alternatively, you could consider converting these functions into actual constructors with inheritance relationships between them.

function BaseError(message, typeId, statusId, statusCode) {
    this.message = message;
    this.type_id = typeId;
    this.status_id = statusId;
    this.status_code = statusCode;
}

function InvalidParameterError(message, typeId, statusId, statusCode, params) {
    BaseError.call(this, message, typeId, statusId, statusCode);
    this.invalid_params = params;
}

InvalidParameterError.prototype = Object.create(BaseError.prototype);
InvalidParameterError.prototype.constructor = InvalidParameterError;

function SuccessMessage(message, typeId, statusId, statusCode, resultData) {
    BaseError.call(this, message, typeId, statusId, statusCode);
    this.data = resultData;
}

SuccessMessage.prototype = Object.create(BaseError.prototype);
SuccessMessage.prototype.constructor = SuccessMessage;

Answer №2

It appears that using ES2015 (also known as ES6) makes the class feature a suitable choice for your needs:

class BaseErrorResponse {
    constructor(mes, rti, rsi, st) {
        this.message = mes;
        this.response_type_id = rti;
        this.response_status_id = rsi;
        this.status = st;
    }
}

class InvalidParamResponse extends BaseErrorResponse {
    constructor(mes, rti, rsi, st, ip) {
        super(mes, rti, rsi, st);
        this.invalid_params = ip;
    }
}

class SuccessResponse extends BaseErrorResponse {
    constructor(msg, rti, rsi, st, data) {
        super(null, null, null, null); // Omitting values here seems unnecessary
        this.data = {};                // Shouldn't this be assigned to = data instead?
    }
}

Considering your response to my comment on the question, the corrected version of the last one would be:

class SuccessResponse extends BaseErrorResponse {
    constructor(msg, rti, rsi, st, data) {
        super(msg, rti, rsi, st);
        this.data = data;
    }
}

Answer №3

My preferred solution is a simpler approach:

const BaseErrorResponse = (message, requestId, responseId, status) => {
  return { message, requestId, responseId, status };
};

const InvalidParamResponse = (message, requestId, responseId, status, invalidParams) => {
  let response = BaseErrorResponse(message, requestId, responseId, status);
  response.invalidParams = invalidParams;
  return response;
};

const SuccessResponse = () => {
  let response = BaseErrorResponse(null, null, null, null);
  response.data = {};
  return response;
};

Answer №4

The code snippet provided by T.J. Crowder has been implemented successfully with great results.

'use strict';
class BaseErrorResponse {
    constructor(msg, rti, rsi, st) {
        this.message = msg;
        this.response_type_id = rti;
        this.response_status_id = rsi;
        this.status = st;
    }
}

class InvalidParamResponse extends BaseErrorResponse {
    constructor(mes, rti, rsi, st, ip) {
        super(mes, rti, rsi, st);
        this.invalid_params = ip;
    }
}

class SuccessResponse extends BaseErrorResponse {
    constructor(msg, rti, rsi, st, data) {
        super(msg, rti, rsi, st); // No need for null values here
        this.data = data;         // Correction: '=' instead of 'd'
    }
}


(()=> {
    let sr = new SuccessResponse('Message', 1, 2, 3, {name: 'vivek'});
    console.log(sr);
})();

OUTPUT:

test )

node js-class-test.js 
SuccessResponse {
  message: 'Message',
  response_type_id: 1,
  response_status_id: 2,
  status: 3,
  data: { name: 'vivek' } }

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

refusing to display the pop-up in a separate window

Hi there, I'm having an issue with a link that's supposed to open in a pop-up but is instead opening in a new tab. I'd like it to open in a proper pop-up window. <button class="button button1" onclick=" window.open('te ...

problem of keeping behat/selenium browser open after execution

I am attempting to execute the behat/selenium test with Chrome browser by running the following feature scenario. I would like to keep the browser window open instead of closing the Chrome immediately. Even though I have implemented the iWaitForSeconds ste ...

Adding several <div> elements with the correct indices

I need help with a dynamic form that requires users to select a state before revealing the corresponding cities within that state. <form method="post"> <div class="summary"> <div class="trip"> <select name="State" class="s ...

Store the text area content as a JSON object

What is the best way to store the content of a textarea in JSON format? I am currently working on a project where I have a textarea element and I need to save its value into a JavaScript object. Everything is functioning correctly except when 'enter ...

PHP code to display "ed elements that do not adjust height"

A php script is being utilized to scan a directory and populate a gallery with all the images. Within the <div id="content"> tag, the function <?php create_gallery("path"); ?> loads all the images. The issue arises when the height of the <d ...

Is it possible to pass an external function to the RxJs subscribe function?

Upon examining the RxJS subscribe method, I noticed that: subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription; So, I decided to create an example initialization function like this: private ...

Using Javascript and Node.js to send a JSON request

While browsing through this particular question, I came across a method in node.js to distinguish between html requests and json requests: app.get('/route', function (req, res) { if (req.is('json')) res.json(data); else if (req ...

Implement a query string feature using a drop-down list

I need help with implementing a drop-down list within a form on my website. <form id="myForm"> <select> <option>ABC</option> <option>xyz</option> </select> </form> When a user select ...

What exactly are Node.js core files?

I recently set up my Node.js application directory and noticed a presence of several core.* files. I am curious about their purpose - can these files be safely removed? The setup involves installing Node.js alongside Apache using mod_proxy to host one of ...

Preserve the existing value and then check it against the updated value of a variable within JavaScript

I utilized an API that supplies me with information in JSON format, retrieved the price of a specific currency, and presented it on a screen using JavaScript. I encapsulated this process within a function that dynamically updates the information at set int ...

Ways to efficiently manage session control without repeating it in each route

I'm currently working on a Node.js application using express. I've been checking the session in every route, but now I'm looking for a way to separate this check from my routes. Any suggestions? Below is an example of one of my routes: app ...

Ways to address the issue of "$ is not a function"

Whenever I attempt to upload an image, this error message pops up: $ is not a function The source of the error can be found here: $(document).height(); ...

Is there a way to retrieve the form name within my directive?

In my code, I am able to retrieve the ngModel name, but now I am looking for a way to also capture the form's name that contains the element with the "validacion" directive. It is crucial for me to programmatically obtain the form's name where t ...

What is the best way to prevent a directory from being included in the Webpack bundle?

Issue: Despite configuring my Webpack settings in webpack.config.js to exclude files from the ./src/Portfolio directory, all files are being bundled by Webpack. Code Snippet: Webpack.config.js const path = require('path'); module.exports = { ...

Retrieve PDF from Controller using jQuery AJAX request

While searching for solutions on how to create a PDF using a controller in EvoPDF, I noticed that none of the examples addressed the scenario where the controller is called via jQuery AJAX. In my application, I have a simple jQuery function that sends dat ...

The communication hub in a Vue.js application

I'm currently developing a Vue single-page project and I have implemented an empty Vue instance as a central event bus. However, I've encountered an issue when trying to fire an event. eventbus.js import vue from 'Vue' export default ...

Is EmailJS Secure Enough for Your Data?

Is EmailJS security something to worry about? I am concerned about the security implications of storing email account information in plaintext within my app.js file. Is there a risk that someone could easily access my email username and password by inspec ...

Implementing dynamic page loading with ajax on your Wordpress website

I'm currently facing an issue with loading pages in WordPress using ajax. I am trying to implement animated page transitions by putting the page content into a div that I will animate into view. However, my current logic only works correctly about 50% ...

Invoke a Java script function for Regular Expression validation failure in ASP.NET

I have a <asp:RegularExpressionValidator> that validates a text box, and I also have a JavaScript function that prevents entering non-numerical values in the textbox. When I use the expression validator alone, it works fine. However, as soon as I add ...

Learn the steps to merging all yarn files using gulp

After successfully setting up yarn and getting the hang of how it functions, I've also started to grasp the basics of gulp. I was relieved to find out how to install version 4 and avoid those deprecated errors that came with the default version. As o ...