/
El tema de los closures es de lo más divertido en JavaScript, básicamente le estamos diciendo que recuerde un valor de una variable a la cual solo puede ser accedida mediante la función principal. Mediante el paradigma de la programación funcional podemos hacer esta magia y tener variables privadas bueno para algunos situaciones y no tan bueno para otras.
/
Ahora como bien sabrás, debajo del siguiente tendrás una explicación de la solución propuesta para este ejercicio por lo que haz scroll baja tu propio riesgo.
/
!dog driving
/
Explicación
Ahora sí, aquí la solución comentada
functioncreateCalculator(){// Primero declaramos nuestra variable privada// que tendrá un valor inicial de 0let total =0;// dentro del return devolvemos las funciones que modifican la variable privadareturn{add(value){// Para sumar, simplemente sumamos el valor al total// y retornamos el total total += value;return total;},subtract(value){// Lo mismo con la resta total -= value;return total;},multiply(value){// Lo mismo con la multiplicación y división total *= value;return total;},divide(value){ total /= value;return total;},// Al final una función para reiniciar el valor a 0clear(){ total =0;return total;},getTotal(){// Y el total por si se quiere guardar el valor en otra variable en cierto momentoreturn total;},};}
/
Así de fácil, ¿se te ocurre otra manera?. Este tema puede dar para mucho mucho más y es de lo más utilizado 💪
esta otra manera aunque basicamente es lo mismo pero mas simple de leer.
exportfunctioncreateCalculator(){let total =0return{'add':(x)=> total += x,'subtract':(x)=> total -= x,'multiply':(x)=> total *= x,'divide':(x)=> total /= x,'clear':()=> total =0,'getTotal':()=> total
}}
Le quedó súper, sobre todo con le uso de las arrow functions, sin embargo, le sugiero usar value en vez de x, queda más limpio el código.
Alerta spoiler, dejo mi aporte:
Una forma de realizar el ejercicio bastante sencilla.
exportfunctioncreateCalculator(){let result =0;constadd=(a)=> result += a;constsubtract=(a)=> result -= a;constmultiply=(a)=> result *= a;constdivide=(a)=> result /= a;constclear=()=> result =0;constgetTotal=()=> result;return{ add, subtract, clear, multiply, divide, getTotal
}}
Cual es el valor value? puse una x en los parametros de la funcion y dentro de la funcion puse un console.log(typeof x) para saber que tipo de dato era pero me sale undefined, en la solucion sale un tal value pero no esta definido o declarado en ningun lado, es un dato por defecto?, vi la solucion y es clara la logica o el algoritmo pero de donde sale el dato value? o donde esta definido ?
Sería bueno que coloques tu code para entenderte mejor
Me costó un poco retornar, ya que no recordaba que las funciones son OBJETOS y se tienen que retornar entre { }.
exportfunctioncreateCalculator(){let total =0;functionadd(num){return total += num;}functionsubtract(num){return total -= num;}functionmultiply(num){return total *= num;}functiondivide(num){return total /= num;}functionclear(){return total =0;}functiongetTotal(){return total;}return{ add, subtract, multiply, divide, clear, getTotal };}
Comparto mi solución utilizando lo aprendido en la clase anterior
.
.
.
.
.
.
.
.
.
exportfunctioncreateCalculator(){let valor =0return{add:function(suma){return valor+=suma
},subtract:function(resta){return valor-=resta
},multiply:function(multiplo){return valor*=multiplo
},divide:function(divisor){return valor/=divisor
},clear:function(){ valor =0return valor
},getTotal:function(){return valor
}}}
exportfunctioncreateCalculator(){let total =0;return{add:(num)=> total += num,substract:(num)=> total -= num,multiply:(num)=> total *= num,divide:(num)=> total /= num,clear:()=> total =0,getTotal:()=> total,}}
Esta es mi solución:
.
.
.
.
.
.
functioncreateCalculator(){let total =0;const operation ={add:(number)=>{return total += number },substract:(number)=>{return total -= number },multiply:(number)=>{return total *= number },divide:(number)=>{return total /= number },clear:()=>{return total =0},getTotal:()=>{return total }}return operation
}
Reto cumplido
Excelente solución
Hay veces que modificando el codigo la web da errores y se pierde todo!!!!!
Hola Compañero, te comparto el como lo realizo y para evitarme ese tipo de problemas:
Me cree un repo en git y lo tengo clonado en mi local que es donde voy realizando las practicas, una vez que lo termino y veo que en mi consola me funciona, paso a probar al Playground una vez que todo Ok en el Playground, procedo a dejar mi solucion aqui en los comentarios...
exportfunctioncreateCalculator(){// Tu código aquí 👈let total =0;functionadd(val){ total += val;return total;}functionsubtract(val){ total -= val;return total;}functionmultiply(val){ total *= val;return total;}functiondivide(val){ total /= val;return total;}functionclear(){ total =0;return total;}functiongetTotal(){return total;}return{ add, subtract, clear, multiply, divide, getTotal };}exportfunctioncreateCalculator2(){let total =0;return{add:(num)=>(total += num),subtract:(num)=>(total -= num),multiply:(num)=>(total *= num),divide:(num)=>(total /= num),clear:()=>(total =0),getTotal:()=> total,};}const calculator =createCalculator();calculator.add(10);const calculator2 =createCalculator();calculator2.add(10);calculator2.subtract(-10);const calculator3 =createCalculator();calculator3.add(10);calculator3.subtract(-10);calculator3.clear();console.log(calculator.getTotal());console.log(calculator2.getTotal());console.log(calculator3.getTotal());
Solución!
.
.
.
.
.
.
.
.
.
.
let total =0;return{add:function(num){ total += num;return total;},subtract:function(num){ total -= num;return total;},multiply:function(num){ total *= num;return total;},divide:function(num){ total /= num;return total;},clear:function(){ total =0;return total;},getTotal:function(){return total;}};
mi aporte... aunque me costo entender que debia devolver un objeto 😅
exportfunctioncreateCalculator(){// Tu código aquí 👈let total =0;//se retorna un valor con propiedades que contienen funcionesreturn({add:(num)=>{return total = total + num;},subtract:(num)=>{return total -= num;},multiply:(num)=>{return total *= num;},divide:(num)=>{return total /= num;},clear:(num)=>{return total =0;},getTotal:(num)=>{return total;}});}
Mi solución:
👀
👀
👀
👀
👀
👀
exportfunctioncreateCalculator(){let value =0;return{add(input){ value += input
return value
},subtract(input){ value -= input
return value
},multiply(input){ value *= input
return value
},divide(input){ value /= input
return value
},clear(){ value =0return value
},getTotal(){return value
}}}
exportfunctioncreateCalculator(){// Tu código aquí 👈let total =0;constadd=(value)=> total += value;constsubtract=(value)=> total -= value;constmultiply=(value)=> total *= value;constdivide=(value)=> total /= value;constclear=()=> total =0;constgetTotal=()=> total;return{ add, subtract, multiply, divide, clear, getTotal
}}
.
.
.
.
.
.
exportfunctioncreateCalculator(){let total =0;constadd=(number)=> total+= number;constsubtract=(number)=> total -= number;constmultiply=(number)=> total *= number;constdivide=(number)=> total /= number;constclear=()=> total =0;constgetTotal=()=> total;return{ add, subtract, multiply, divide, clear, getTotal }}