I have a Typescript project in which I am creating a builder to form all the objects of the different methods.
I'm trying to adapt the same builder for all methods so as not to clutter the process with classes.
Currently I have two functions with different variables that call the same builder to create each one its object, but since the variables are different I don't know how to pass them to the constructor or how to tell it which variables to take.
This is my current 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 problem: Right now the first function worked, but the second one returns a 0 in the header key. How can I adapt the builder for both functions or make it generic to implement more functions? How can I know from the builder what variables are coming to me?