I've been puzzling the last few days on trying to solve a problem in Javascript (typescript), and I'm unable to come to a solution that I feel comfortable with. So here is my scenario:
You have a class, that has a public function.. this public function will be called many thousands of times so performance is paramount. However, that function must be able to perform a dynamic task without the use of if statements or switching. For an example...
class foo {
constructor() {
}
doWork1() {
return 1 + 1;
}
doWork2() {
return 5 + 5;
}
}
Now any class MUST be able to call an agnostic doWork function, but without knowing if it should call doWork1, or doWork2. I have looked into mapping the functions to an enumerable, however performance tests show that to be a horrible approach, though it is scalable.
Therefore, the best solution I have come up with to date is thus:
class foo {
public doWork:Function;
constructor(fnFlag) {
if(fnFlag === 1) {
this.doWork = this.doWork1;
} else if (fnFlag === 2) {
this.doWork = this.doWork2;
}
}
doWork1() {
return 1 + 1;
}
doWork2() {
return 5 + 5;
}
}
In the code above, the public function doWork can be called by any class and will always point to the function it is initialised with. However, something just isn't sitting right with me and I don't feel like this is the best approach. I was contemplating passing the function in the constructor and assigning it there?
Any thoughts or advice on a pattern to solve an issue such as this would be most appreciated. Thanks.
Aucun commentaire:
Enregistrer un commentaire