@@ -90,6 +90,86 @@ console.log(contractorEmployee.calculatePay());
9090
9191/**-----DIFICULTAD EXTRA-----*/
9292
93- // Pendiente
93+ // Interface para la operaciones
94+ class Operation {
95+ execute ( a , b ) {
96+ throw new Error ( 'Método no implementado' )
97+ }
98+ }
99+
100+ // Suma
101+ class Addition extends Operation {
102+ execute ( a , b ) {
103+ return a + b ;
104+ }
105+ }
106+
107+ // Resta
108+ class Subtraction extends Operation {
109+ execute ( a , b ) {
110+ return a - b ;
111+ }
112+ }
113+
114+ // Multiplicación
115+ class Multiplication extends Operation {
116+ execute ( a , b ) {
117+ return a * b ;
118+ }
119+ }
120+
121+ // Division
122+ class Division extends Operation {
123+ execute ( a , b ) {
124+ if ( b === 0 ) {
125+ throw new Error ( 'Nose puede dividir entre 0' ) ;
126+ }
127+ return a / b ;
128+ }
129+ }
130+
131+
132+ // Clase Calculadora
133+ class Calculator {
134+ constructor ( ) {
135+ this . operations = { } ;
136+ }
137+
138+ addOperation ( nombre , operación ) {
139+ this . operations [ nombre ] = operación ;
140+ }
141+
142+ calculate ( nombre , a , b ) {
143+ if ( ! this . operations [ nombre ] ) {
144+ throw new Error ( `Operación ${ nombre } no es valida` ) ;
145+ }
146+ return this . operations [ nombre ] . execute ( a , b ) ;
147+ }
148+ }
149+
150+
151+ //Creando la instancia de la calculadora
152+ const calculator = new Calculator ( ) ;
153+ calculator . addOperation ( 'add' , new Addition ( ) ) ;
154+ calculator . addOperation ( 'subtract' , new Subtraction ( ) ) ;
155+ calculator . addOperation ( 'multiply' , new Multiplication ( ) ) ;
156+ calculator . addOperation ( 'divide' , new Division ( ) ) ;
157+
158+ // Test de opresiones básicas
159+ console . log ( 'Suma' , calculator . calculate ( 'add' , 5 , 4 ) ) ;
160+ console . log ( 'Resta' , calculator . calculate ( 'subtract' , 9 , 6 ) ) ;
161+ console . log ( 'Multiplicación' , calculator . calculate ( 'multiply' , 3 , 7 ) ) ;
162+ console . log ( 'Division' , calculator . calculate ( 'divide' , 8 , 2 ) ) ;
163+
164+ // Agregamos la potencia
165+ class Power extends Operation {
166+ execute ( a , b ) {
167+ return a ** b ;
168+ }
169+ }
170+
171+ // Agregamos la operación de potencia
172+ calculator . addOperation ( 'power' , new Power ( ) ) ;
173+ console . log ( 'Potencia' , calculator . calculate ( 'power' , 2 , 5 ) ) ;
94174
95175/**-----DIFICULTAD EXTRA-----*/
0 commit comments