Estoy tratando de implementar una declaración de cambio alternativa usando un objeto de mapa y las funciones que se supone que deben llamarse de acuerdo con la condición se están llamando mientras declaro el mapa.
Aquí hay un código simplificado de lo que implementé.
someMethodName(someParams, otherParams) { const verifyThis = callExternalApi(someParams); const customSwitch = { oneValue: this.doThis(otherParams), anotherValue: this.doThat(otherParams), }; const possibleValues = ["oneValue", "anotherValue"]; if (possibleValues.includes(verifyThis)) return customSwitch[verifyThis]; return this.defaultCase(otherParams); }Puse un archivo console.log en los métodos a llamar y descubrí que se están llamando a todos, supuestamente mientras declaro customSwitch, y luego uno de los métodos se está llamando al pasar por la cláusula if.
¿Cómo soluciono esto para evitar llamar a mis métodos?
Utilice un objeto cuyos valores sean funciones que, cuando se llamen, invoquen a las otras funciones:
const customSwitch = { oneValue: () => this.doThis(otherParams), anotherValue: () => this.doThat(otherParams), };e invocar al volver haciendo
return customSwitch[verifyThis]();