What steps should I follow to successfully implement a polymorphic method in JavaScript?

I am working on creating a sample

Can someone assist me with writing the updateStepData method, that will modify stepOneData if data is of type StepOneData and will modify stepTwoData if data is of type StepTwoData?

  updateStepData(data: StepOneData | StepTwoData): void {
     Object.keys(data).map(key => {
       // if (data instanceof StepOneData) {
          this.stepOneData[key] = data[key];
       // } 

       // if (data instanceof StepTwoData) {
          this.stepTwoData[key] = data[key];
       // } 
     });
  }

I have attempted to use the instanceof operator but it seems to not be effective for this scenario.

Answer №1

Upon inspecting your Step1Component, I came across this method:

onFormChanges(): void {
    this.stepOneForm.valueChanges
      .subscribe((data: StepOneData) => {

        this.registrationService.updateStepData(data);
      });
}

Here is a suggested modification:

onFormChanges(): void {
    this.stepOneForm.valueChanges
      .subscribe((data: StepOneData) => {

        const stepOneData = new StepOneData();

        stepOneData.firstName = data.firstName;
        stepOneData.lastName = data.lastName;      

        this.registrationService.updateStepData(stepOneData);
      });
}

The same modification can be applied to your Step2Component.

Now, you can utilize the 'instanceof' operator as seen in your code:

   if (data instanceof StepOneData) {
    this.stepOneData[key] = data[key];
  } 

  if (data instanceof StepTwoData) {
     this.stepTwoData[key] = data[key];
  } 

=========================

To enhance readability, consider adding constructors to your StepOneData and StepTwoData classes to initialize their properties like so:

export class StepTwoData {

  constructor(public city:string, public state:string){}

}

In your components:

 onFormChanges(): void {
    this.stepTwoForm.valueChanges
      .subscribe((data: StepTwoData) => {

        const stepTwoData = new StepTwoData(data.city, data.state);    

        this.registrationService.updateStepData(stepTwoData);
      });
}

==========================

UPDATE :

For better design, I recommend creating two separate methods for each type, such as "UpdateStepOneData" and "UpdateStepTwoData."

If there is shared logic between these methods, consolidate it into a method named "UpdateStepData":

UpdateStepOneData(data: StepOneData){

       // Custom Code specific to StepOneData

       UpdateStepData(...); // Shared Logic goes here

}

UpdateStepTwoData(data: StepTwoData){

       // Custom Code specific to StepTwoData

       UpdateStepData(...); // Shared Logic goes here

}

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

Adding Empty Space Following Error Message in Codeigniter

I am encountering an issue with my code where there is a blank space appearing after the error message. Here is the code snippet that is causing the problem: <script> const successNotification = window.createNotification({ theme: 'error&a ...

Angular Alert: Issue Resolving All Parameters

I recently updated my Ionic / Angular app to Ionic 3 / Angular 4 and encountered an issue with a couple of base classes I use for my pages... @Injectable() export abstract class BasePage { constructor( userMessageService: UserMessageService, logge ...

Get an array of objects sorted based on numerical values, ignoring strings

After developing a utility function to sort an array of objects based on either ascending or descending order, I encountered an issue when sorting string properties. For example, if "age" is passed as the second argument, the ordering works correctly. Ho ...

Place the input field and submit button side by side horizontally

How can I align my submit button next to the input text in a single row, with the submit button on the right side of the input text? This is my code: <div class="mt-12"> <input id="grid-text" ...

Managing the grouping of values from an HTML form by key becomes a challenge when input fields can be dynamically added or removed

One interesting feature in my form is the ability to add and remove rows dynamically by clicking on a button. When multiple invoicerow elements are present, I want to group all results together for better organization. However, the array structure in the p ...

Keep sending ajax request until the page is closed

Is it possible to resend an ajax request continuously using pure javascript without any framework? Here is an example of how I am currently attempting to do it: xmlhttp=new XMLHttpRequest(); xmlhttp.open("POST","demo_post2.asp",true); xmlhttp.setRequest ...

Tips for inserting JSON information in JavaScript

I am working with a JSON file that contains data in the following format: { "rigidBodies": [ { "name": "ball1.png", "imagePath": "ball1.png", "origin": {"x": 0, "y": 0}, "polygons": [ [ ...

Restrict user input to only numerical values in an input field using jQuery

Is there a way to create an input field that only accepts integer numbers? Even after using regular expressions, the decimal part of the value still shows up. Here's the function I've tried: $(document).on("input", "input", function(e) { t ...

Steps for importing vuetify/lib alongside the vuetify loader in the A-La-Carte system

When utilizing the A-La-Carte system in vuetify with vuetify-loader, I encountered a TypeScript error while trying to import vuetify/lib. I am unsure of what mistake I might be making here and would appreciate some assistance with importing this. I was re ...

How can I implement a button that dynamically updates the id parameter in slide.filter in order to display various elements from an array in a REACT application?

I am attempting to create a text carousel that displays data from an array one at a time. I have stored the data in an array and now I want to implement a button that allows me to navigate through the array entries. However, I am facing issues finding a so ...

Exploring alternative methods of iterating over the values in a key-value pair within an AngularJS framework

My key-value pair consists of a long list of file names stored in the variable $ctrl.displayData- 143:"/this/is/a/very/long/fil22↵/this/is/a/very/long/file/path.php↵anotherone.php↵newfilel123.php" When I use ng-repeat to display these file names, t ...

During the installation process of the Angular App on a Windows operating system, the Cypress App encountered a download error while running the command "npm install

Encountering an issue when running "npm install" for Angular App on Windows while behind a corporate proxy with proper settings. The error message is as follows: npm i > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f09389 ...

An error is anticipated when () is added, but surprisingly, I still encounter an error as well. This issue arises in React-Native and Typescript

I am still relatively new to React-Native, but I have been using React-Native, TypeScript, and integrating it with Firebase. An unusual error has occurred, which is visible in the screenshot below. However, when checking in VSC, the error seems to be non-e ...

How to Incorporate Routes as Subroutes in Express.js

I am currently working on constructing a modular express.js server with a well-organized structure. I have experimented with using routes similar to components in React. index.js var syncsingle = require('./XYZ/syncsingle'); app.get('/sync ...

Is it possible to merge createStackNavigator with createBottomTabNavigator for enhanced navigation functionality

Current Situation : My app currently has three tabs for navigation (School, Admin, Family); I am now facing a challenge as I want to add additional screens that do not require tabs for navigation. These screens will be accessed using this.props.navigati ...

Tips for successfully passing a key to a React functional component within a .map() iteration?

I recently encountered a common issue with React that requires a 'key' prop for each child element when using the .map() method. In an attempt to address this, I created a key within a functional component like so... export default function Func ...

Tips for managing Angular modules post-splitting and publishing on npm

Currently, I am in the process of developing an Angular application. To ensure reusability and prevent duplication of components and services in another application, I have divided the app into modules and deployed them on a private npm and git server. No ...

Finding a resolution to the Angular 6 error proves to be challenging as

Error occurred in style.scss file during compilation: Module build failed: Error: ENOENT: no such file or directory, scandir 'C:\Users\arsalan.akhtar\Documents\KEweb\node_modules\node-sass\vendor' at Object. ...

Rearrange the order of items in the fancybox gallery

Typically, fancybox displays items in the gallery based on the order they are added in the HTML code. Is there a way to customize the order of items when they are opened in the popup, while keeping the original order when displayed on the page? The solut ...

Getting a blank request body error while receiving data from an Angular 4 application in Express

My express route is indicating that the body of the request being sent is empty, according to req.body. The main node file looks like this - var express = require('express'); var bluebird = require('bluebird') const bodyParser = requ ...