up
This commit is contained in:
parent
d7d25f4d8b
commit
20784e7f26
48 changed files with 302 additions and 397 deletions
|
@ -1,17 +1,13 @@
|
|||
function Calculator() {
|
||||
|
||||
var methods = {
|
||||
"-": function(a, b) {
|
||||
return a - b;
|
||||
},
|
||||
"+": function(a, b) {
|
||||
return a + b;
|
||||
}
|
||||
let methods = {
|
||||
"-": (a, b) => a - b,
|
||||
"+": (a, b) => a + b
|
||||
};
|
||||
|
||||
this.calculate = function(str) {
|
||||
|
||||
var split = str.split(' '),
|
||||
let split = str.split(' '),
|
||||
a = +split[0],
|
||||
op = split[1],
|
||||
b = +split[2]
|
||||
|
|
|
@ -1,26 +1,25 @@
|
|||
var calculator;
|
||||
before(function() {
|
||||
calculator = new Calculator;
|
||||
});
|
||||
describe("Calculator", function() {
|
||||
let calculator;
|
||||
|
||||
it("calculate(12 + 34) = 46", function() {
|
||||
assert.equal(calculator.calculate("12 + 34"), 46);
|
||||
});
|
||||
|
||||
it("calculate(34 - 12) = 22", function() {
|
||||
assert.equal(calculator.calculate("34 - 12"), 22);
|
||||
});
|
||||
|
||||
it("добавили умножение: calculate(2 * 3) = 6", function() {
|
||||
calculator.addMethod("*", function(a, b) {
|
||||
return a * b;
|
||||
before(function() {
|
||||
calculator = new Calculator;
|
||||
});
|
||||
assert.equal(calculator.calculate("2 * 3"), 6);
|
||||
});
|
||||
|
||||
it("добавили возведение в степень: calculate(2 ** 3) = 8", function() {
|
||||
calculator.addMethod("**", function(a, b) {
|
||||
return Math.pow(a, b);
|
||||
it("calculate(12 + 34) = 46", function() {
|
||||
assert.equal(calculator.calculate("12 + 34"), 46);
|
||||
});
|
||||
assert.equal(calculator.calculate("2 ** 3"), 8);
|
||||
});
|
||||
|
||||
it("calculate(34 - 12) = 22", function() {
|
||||
assert.equal(calculator.calculate("34 - 12"), 22);
|
||||
});
|
||||
|
||||
it("add multiplication: calculate(2 * 3) = 6", function() {
|
||||
calculator.addMethod("*", (a, b) => a * b);
|
||||
assert.equal(calculator.calculate("2 * 3"), 6);
|
||||
});
|
||||
|
||||
it("add power: calculate(2 ** 3) = 8", function() {
|
||||
calculator.addMethod("**", (a, b) => a ** b);
|
||||
assert.equal(calculator.calculate("2 ** 3"), 8);
|
||||
});
|
||||
});
|
||||
|
|
|
@ -1,52 +1,3 @@
|
|||
|
||||
|
||||
```js run
|
||||
function Calculator() {
|
||||
|
||||
var methods = {
|
||||
"-": function(a, b) {
|
||||
return a - b;
|
||||
},
|
||||
"+": function(a, b) {
|
||||
return a + b;
|
||||
}
|
||||
};
|
||||
|
||||
this.calculate = function(str) {
|
||||
|
||||
var split = str.split(' '),
|
||||
a = +split[0],
|
||||
op = split[1],
|
||||
b = +split[2]
|
||||
|
||||
if (!methods[op] || isNaN(a) || isNaN(b)) {
|
||||
return NaN;
|
||||
}
|
||||
|
||||
return methods[op](+a, +b);
|
||||
}
|
||||
|
||||
this.addMethod = function(name, func) {
|
||||
methods[name] = func;
|
||||
};
|
||||
}
|
||||
|
||||
var calc = new Calculator;
|
||||
|
||||
calc.addMethod("*", function(a, b) {
|
||||
return a * b;
|
||||
});
|
||||
calc.addMethod("/", function(a, b) {
|
||||
return a / b;
|
||||
});
|
||||
calc.addMethod("**", function(a, b) {
|
||||
return Math.pow(a, b);
|
||||
});
|
||||
|
||||
var result = calc.calculate("2 ** 3");
|
||||
alert( result ); // 8
|
||||
```
|
||||
|
||||
- Обратите внимание на хранение методов. Они просто добавляются к внутреннему объекту.
|
||||
- Все проверки и преобразование к числу производятся в методе `calculate`. В дальнейшем он может быть расширен для поддержки более сложных выражений.
|
||||
|
||||
- Please note how methods are stored. They are simply added to the internal object.
|
||||
- All tests and numeric conversions are done in the `calculate` method. In future it may be extended to support more complex expressions.
|
||||
|
|
|
@ -2,41 +2,35 @@ importance: 5
|
|||
|
||||
---
|
||||
|
||||
# Создайте калькулятор
|
||||
# Create an extendable calculator
|
||||
|
||||
Напишите конструктор `Calculator`, который создаёт расширяемые объекты-калькуляторы.
|
||||
Create a constructor function `Calculator` that creates "extendable" calculator objects.
|
||||
|
||||
Эта задача состоит из двух частей, которые можно решать одна за другой.
|
||||
The task consists of two parts.
|
||||
|
||||
1. Первый шаг задачи: вызов `calculate(str)` принимает строку, например "1 + 2", с жёстко заданным форматом "ЧИСЛО операция ЧИСЛО" (по одному пробелу вокруг операции), и возвращает результат. Понимает плюс `+` и минус `-`.
|
||||
1. First, implement the method `calculate(str)` that takes a string like `"1 + 2"` in the format "NUMBER operator NUMBER" (space-delimited) and returns the result. Should understand plus `+` and minus `-`.
|
||||
|
||||
Пример использования:
|
||||
Usage example:
|
||||
|
||||
```js
|
||||
var calc = new Calculator;
|
||||
let calc = new Calculator;
|
||||
|
||||
alert( calc.calculate("3 + 7") ); // 10
|
||||
```
|
||||
2. Второй шаг -- добавить калькулятору метод `addMethod(name, func)`, который учит калькулятор новой операции. Он получает имя операции `name` и функцию от двух аргументов `func(a,b)`, которая должна её реализовывать.
|
||||
2. Then add the method `addOperator(name, func)` that teaches the calculator a new operation. It takes the operator `name` and the two-argument function `func(a,b)` that implements it.
|
||||
|
||||
Например, добавим операции умножить `*`, поделить `/` и возвести в степень `**`:
|
||||
For instance, let's add the multiplication `*`, division `/` and power `**`:
|
||||
|
||||
```js
|
||||
var powerCalc = new Calculator;
|
||||
powerCalc.addMethod("*", function(a, b) {
|
||||
return a * b;
|
||||
});
|
||||
powerCalc.addMethod("/", function(a, b) {
|
||||
return a / b;
|
||||
});
|
||||
powerCalc.addMethod("**", function(a, b) {
|
||||
return Math.pow(a, b);
|
||||
});
|
||||
let powerCalc = new Calculator;
|
||||
powerCalc.addMethod("*", (a, b) => a * b);
|
||||
powerCalc.addMethod("/", (a, b) => a / b);
|
||||
powerCalc.addMethod("**", (a, b) => a ** b);
|
||||
|
||||
var result = powerCalc.calculate("2 ** 3");
|
||||
let result = powerCalc.calculate("2 ** 3");
|
||||
alert( result ); // 8
|
||||
```
|
||||
|
||||
- Поддержка скобок и сложных математических выражений в этой задаче не требуется.
|
||||
- Числа и операции могут состоять из нескольких символов. Между ними ровно один пробел.
|
||||
- Предусмотрите обработку ошибок. Какая она должна быть - решите сами.
|
||||
- No brackets or complex expressions in this task.
|
||||
- The numbers and the operator are delimited with exactly one space.
|
||||
- There may be error handling if you'd like to add it.
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue