Tips for modifying a class to accept a range of parameters from diverse functions

In my current Typescript project, I have implemented a builder to create objects for various methods. I am striving to make the builder adaptable for all methods in order to streamline the process without creating additional classes.

At present, I have two functions with distinct variables that utilize the same builder to generate objects. However, due to the difference in variables, I am uncertain of how to pass them to the constructor or specify which variables should be used.

The following is my existing builder class:

export interface Constants {
  sheetId: number,
  lastRow: number,
  totalHeader: number
}
export interface Req {
  requests: Array<object>
}

export class Builder {

  private dataInit: Req;
  private dataProp: Constants;

  constructor(sheetId: number, totalRow?: number, totalHeader?: number) {
    this.dataInit = {
        requests: []
    };
    this.dataProp = {
        sheetId: sheetId,
        lastRow: totalRow ? totalRow : 0,
        totalHeader: totalHeader ? totalHeader : 0
    };               
  }

  testOne() {
    this.dataInit.requests.push(
      {
        dataOne: {
          sheetId: this.dataProp.sheetId,
          endRow: this.dataProp.lastRow
        }
      }
    )
    return this.dataInit;
  }

  testTwo() {
    this.dataInit.requests.push(
      {
        dataTwo: {
          update: {
            sheetId: this.dataProp.sheetId
          },
          change: {
            header: this.dataProp.totalHeader
          }
        }
      }
    )
    return this.dataInit;
  }

}

These are my functions:

function testOneData() {
  let sheet: number = 123;
  let rowTotal: number = 25;

  let dataObj = new Builder(sheet,rowTotal).testOne()

  console.log(JSON.stringify(dataObj))
}

function testTwoData() {
  let sheet: number = 123;
  let headerTotal: number = 2;

  let dataObj = new Builder(sheet,headerTotal).testTwo()

  console.log(JSON.stringify(dataObj))
}

testOneData()

My dilemma: While the first function works correctly, the second one returns a 0 in the header key. How can I modify the builder to accommodate both functions or enable it to handle multiple functions uniformly? Additionally, how can I determine the incoming variables within the builder?

Answer №1

If my understanding is correct, you are looking to pass arguments as a single object instead of a list.

Here's an example:

  constructor({
    sheetId,
    totalRow = 0,
    totalHeader = 0
  }: {
    sheetId: number,
    totalRow?: number,
    totalHeader?: number
  }) {
    this.dataInit = {
        requests: []
    };
    this.dataProp = {
        sheetId,
        lastRow: totalRow,
        totalHeader,
    };               
  }

Now, totalRow and totalHeader are accessed by their property names in the passed object, allowing flexibility in the order and optionality.

To use this constructor:

let dataObj = new Builder({sheetId: sheet, totalRow: rowTotal}).testOne()

Or

  let dataObj = new Builder({sheetId: sheet, totalHeader: headerTotal}).testTwo()

This will yield the correct results:

testOneData() // "{"requests":[{"dataOne":{"sheetId":123,"endRow":25}}]}" 
testTwoData() // "{"requests":[{"dataTwo":{"update":{"sheetId":123},"change":{"header":2}}}]}"

Check out this Typescript Playground for a live demo. Click "Run" on the top left to view the output in the console.


Note that if you do this:

New Builder(dataRequiredForTestOne).testTwo() // no problem

It will work fine and utilize default values. If this poses issues for your specific case, utilizing TypeScript generic parameters may be necessary, which could be addressed in a separate question.

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

Typescript issue when a value is possibly a function or null

I have defined a type called StateProps with the following properties type StateProps = { isPending: boolean, asyncFn: (...args: any[]) => void | null } To initialize, I set up an initialState variable where the asyncFn property is initially s ...

What is the proper way to specify the return value of a function that has dynamically generated keys?

I am working with a TypeScript (v5.5.4) function called test that takes a fieldsMap parameter and is supposed to return a specific type based on the keys and values of fieldsMap. However, I am struggling to define the return type accurately. Here's th ...

Verify that the elements in the input array are numerical values

My current challenge in PHP involves checking if the input variables are numbers within an array, where each number is separated by a space within a form. Unfortunately, using is_int and is_numeric is not effective in this case because the input is treate ...

Modify the data values and reconstruct the JSON structure using Python

I'm facing a situation where I need to work with the following json data: data = { "app": [ { "ida": 10, "configur": { "config": [ { "active": "true", "tol": ...

Assistance required in creating a numerical list from an array of objects

I'm currently facing an issue with creating a numbered list from an array of objects. Below, you'll find the code containing the objects. You need to add the necessary TS code to display the atom names along with their weights in a numbered list ...

"Encountered a problem with Next JS API while trying to fetch data from the app directory

import { NextResponse } from "next/server"; export async function POST(request: Request) { const data = await request.json(); console.log(data); return NextResponse.json({ foo: "boo" }); } next version = "next": &quo ...

What impact does the sequence of array initialization have in an embedded system?

In my coding assignment, I am tasked with manipulating user input that includes a hexadecimal memory address and a word or phrase up to 16 characters long. Each character in the input string following the memory address is converted to a hexadecimal value, ...

What's the best way to use the keyboard's enter key to mark my to-do list

I'm looking to update my todo list functionality so that pressing enter adds a new todo item, instead of having to click the button. <h1 style="text-align:center">Todo List</h1> <div class="container"> ...

Develop a customized interface for exporting styled components

I am struggling to figure out how to export an interface that includes both the built-in Styled Components props (such as as) and my custom properties. Scenario I have created a styled component named CustomTypography which allows for adding typographic s ...

How to display a nested array in TypeScript following a specific structure

Can anyone assist with printing the variable below in the specified format? Data export const shop_items: Inventory:{ Toys{ Balls: { BallId: 001uy, BallName: Soccerball, SignedBy: David_Beckham, }, ...

What is the best way to display the JSON data?

<!DOCTYPE HTML> <html> <head> <title></title> <link href="/bundles/hoaxpartner/css/style.css" type="text/css" rel="stylesheet" /> </head> <body> <div id="header">Backbone</div> &l ...

comparing the performance of C++ arrays with std::vector and std::array

After conducting a comparison between different methods of allocating a 1d-array or 2d-array, I discovered that using the new operator is more efficient. It seems that std::array and std::vector are objects that are generic and safe but might consume more ...

The latest version of jQuery is causing issues with my code

When retrieving HTML from my database using a jQuery AJAX request, I encounter an issue with parsing if there is a single quote (') in the content. Regular quotes (") work without any problems. For example, in my database, I have: style=font-family ...

Exploring the inner workings of a JSON with Ajax and PHP

I'm working on a project that involves a JSON file called items.json. My goal is to create a search box where users can input either the name of an item or its category, and see live search results as they type. Here's what I’m aiming for: If ...

The automatic filtering feature does not kick in when the sorting is changed

I've been working on an app that features a video database, allowing users to filter videos by category and sort them by rating. https://i.sstatic.net/cESZT.png Currently, the filtering system works fine once the options are changed. However, there ...

"Enhancing User Experience with Hover States in Nested React Menus

I have created a nested menu in the following code. My goal is to dynamically add a selected class name to the Nav.Item element when hovering, and remove it only when another Nav.Item is hovered over. I was able to achieve this using the onMouseOver event. ...

Using NestJS to pass request and response parameters

I have a function in my services set up like this: ` @Injectable() export class AppService { getVerifyToken(req: Request, res: Response) { try { let accessToken = process.env.ACCES_TOKEN_FB; let token = req.query["hub.verify_t ...

Error encountered when converting JSON to Object with com.fasterxml.jackson.databind.JsonMappingException

I have received the following JSON data from an API : { "list": { "responsibility": { "rolename" : "Regional Operation Director", "organizationLevelValues":"32R", "otherCMDLevelValues":"MGT," }, "responsibility": { ...

The <div> element is not displaying the JSON response when using Ajax

I have created a basic login form and I am attempting to validate it using an AJAX call. The validation process is successful, but the issue arises when the correct email or password is entered. Instead of displaying the JSON success or error message in a ...

Problem with timing in token interceptor and authentication guard due to injected service

Currently, I am facing an issue where I need to retrieve URLs for the auth service hosted on AWS by reading a config.json file. In order to accomplish this, I created a config service that reads the config file and added it as a provider in app.module. Eve ...