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?