Home > OS >  Function parameter in constructor
Function parameter in constructor

Time:05-11

I have a class which takes as a parameter a function which conforms to an interface. The class later calls this function with a given input.

In the interface an input is always required, but other parameters are also allowed, though optional. I want to provide these extra paramters when creating an instance - how should I do this?

I have considered adding an args parameter in the constructor which will be applied to the function call, but this seems ugly and detaches the parameters from the function. I also considered creating an intermediate function which takes the single input parameter and passes it on to the function with args, but again this seems messy - I'd like to encapsulate everything inside the class and provide all configuration of the resulting instance when it is constructed.

interface IThingAction {
    (input: string, ...args: any[]): boolean;
}

let printInput: IThingAction = (input: string) => {
    console.log(input);
}

let repeatInput: IThingAction = (input: string, iterations: number) => {
    for (var i = 0; i < iterations, i  ) {
        console.log(input);
    }
}

class Thing {
    action: IThingAction;

    constructor(action: IThingAction) {
        this.action = action;
    }

    doAction(input: string): boolean {
        return this.action(input);
    }
}

let speaker = new Thing(printInput);
let echoer = new Thing(repeatInput); // I'd like to provide extra parameters here, e.g. (3)

speaker.doAction('hello');
// hello
echoer.doAction('-o');
// -o
// -o
// -o

CodePudding user response:

One of solution is to change the repeatInput becomes a function creator like below:

type IThingAction =  (input: string) => boolean;

const makeRepeatInput = (iterations: number): IThingAction => (input) => {
    for (var i = 0; i < iterations; i  ) {
        console.log(input);
    }
}

let echoer = new Thing(makeRepeatInput(3));
  • Related