Created
December 10, 2018 12:59
-
-
Save NikitaGlukhi/51cb63bc3cf7afc7557d4e155baf34a9 to your computer and use it in GitHub Desktop.
Task 4 for cunstructor functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Calculator = function () { | |
const operators = { // Задаем набор методов | |
"+": (value1, value2) => { | |
return value1 + value2 | |
}, | |
"-": (value1, value2) => { | |
return value1 - value2 | |
} | |
}; | |
this.calculate = function (str) { | |
const values = str.split(' '); | |
const operand1 = +values[0]; | |
const operator = values[1]; | |
const operand2 = +values[2]; | |
if(!operators[operator] || isNaN(operand1) || isNaN(operand2)) { | |
return 'Something went wrong'; | |
} | |
return operators[operator](operand1, operand2); | |
}; | |
this.addMethod = function (newOperator, func) { | |
operators[newOperator] = func; // в данном случае newOperator - новый вводимый оператор, а func - какое действие при выполнение этого оператора совершается. | |
// Свойтсво newOperator взято в квадратные скобки из-за того, что является динамическим; | |
} | |
}; | |
const calculator = new Calculator; | |
calculator.addMethod("*", (value1, value2) => { | |
return value1 * value2; | |
}); | |
calculator.addMethod("/", (value1, value2) => { | |
return value1 / value2; | |
}); | |
calculator.addMethod("^", (value1, value2) => { | |
return Math.pow(value1, value2) // value1 - число, возводящееся в степень value2 | |
}); | |
const mul = calculator.calculate("3 * 2"); | |
const cleavage = calculator.calculate("264 / 3"); | |
const degree = calculator.calculate("12 ^ 3"); | |
alert(`Сумма: ${calculator.calculate('3 + 2')}`); | |
alert(`Разность: ${calculator.calculate("4 - 1")}`); | |
alert(`Произведение: ${mul}`); | |
alert(`Деление: ${cleavage}`); | |
alert(`Возведение в степень: ${degree}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment