up
This commit is contained in:
parent
d7d25f4d8b
commit
20784e7f26
48 changed files with 302 additions and 397 deletions
|
@ -1,18 +1,14 @@
|
|||
Да, возможны.
|
||||
Yes, it's possible.
|
||||
|
||||
Они должны возвращать одинаковый объект. При этом если функция возвращает объект, то `this` не используется.
|
||||
If a function returns an object then `new` returns it instead of `this`.
|
||||
|
||||
Например, они могут вернуть один и тот же объект `obj`, определённый снаружи:
|
||||
So thay can, for instance, return the same externally defined object `obj`:
|
||||
|
||||
```js run no-beautify
|
||||
var obj = {};
|
||||
let obj = {};
|
||||
|
||||
function A() { return obj; }
|
||||
function B() { return obj; }
|
||||
|
||||
var a = new A;
|
||||
var b = new B;
|
||||
|
||||
alert( a == b ); // true
|
||||
alert( new A() == new B() ); // true
|
||||
```
|
||||
|
||||
|
|
|
@ -2,9 +2,9 @@ importance: 2
|
|||
|
||||
---
|
||||
|
||||
# Две функции один объект
|
||||
# Two functions -- one object
|
||||
|
||||
Возможны ли такие функции `A` и `B` в примере ниже, что соответствующие объекты `a,b` равны (см. код ниже)?
|
||||
Is it possible to create functions `A` and `B` such as `new A()==new B()`?
|
||||
|
||||
```js no-beautify
|
||||
function A() { ... }
|
||||
|
@ -16,4 +16,4 @@ var b = new B;
|
|||
alert( a == b ); // true
|
||||
```
|
||||
|
||||
Если да -- приведите пример кода с такими функциями.
|
||||
If it is, then provide an example of their code.
|
||||
|
|
|
@ -1,25 +1,25 @@
|
|||
sinon.stub(window, "prompt")
|
||||
|
||||
prompt.onCall(0).returns("2");
|
||||
prompt.onCall(1).returns("3");
|
||||
|
||||
describe("calculator", function() {
|
||||
var calculator;
|
||||
let calculator;
|
||||
before(function() {
|
||||
sinon.stub(window, "prompt")
|
||||
|
||||
prompt.onCall(0).returns("2");
|
||||
prompt.onCall(1).returns("3");
|
||||
|
||||
calculator = new Calculator();
|
||||
calculator.read();
|
||||
});
|
||||
|
||||
it("при вводе 2 и 3 сумма равна 5", function() {
|
||||
it("when 2 and 3 are entered, the sum is 5", function() {
|
||||
assert.equal(calculator.sum(), 5);
|
||||
});
|
||||
|
||||
it("при вводе 2 и 3 произведение равно 6", function() {
|
||||
it("when 2 and 3 are entered, the product is 6", function() {
|
||||
assert.equal(calculator.mul(), 6);
|
||||
});
|
||||
|
||||
after(function() {
|
||||
prompt.restore();
|
||||
});
|
||||
});
|
||||
|
||||
after(function() {
|
||||
prompt.restore();
|
||||
});
|
|
@ -17,10 +17,9 @@ function Calculator() {
|
|||
};
|
||||
}
|
||||
|
||||
var calculator = new Calculator();
|
||||
let calculator = new Calculator();
|
||||
calculator.read();
|
||||
|
||||
alert( "Сумма=" + calculator.sum() );
|
||||
alert( "Произведение=" + calculator.mul() );
|
||||
alert( "Sum=" + calculator.sum() );
|
||||
alert( "Mul=" + calculator.mul() );
|
||||
```
|
||||
|
||||
|
|
|
@ -2,23 +2,22 @@ importance: 5
|
|||
|
||||
---
|
||||
|
||||
# Создать Calculator при помощи конструктора
|
||||
# Create new Calculator
|
||||
|
||||
Напишите *функцию-конструктор* `Calculator`, которая создает объект с тремя методами:
|
||||
Create a constructor function `Calculator` that creates objects with 3 methods:
|
||||
|
||||
- Метод `read()` запрашивает два значения при помощи `prompt` и запоминает их в свойствах объекта.
|
||||
- Метод `sum()` возвращает сумму запомненных свойств.
|
||||
- Метод `mul()` возвращает произведение запомненных свойств.
|
||||
- `read()` asks for two values using `prompt` and remembers them in object properties.
|
||||
- `sum()` returns the sum of these properties.
|
||||
- `mul()` returns the multiplication product of these properties.
|
||||
|
||||
Пример использования:
|
||||
For instance:
|
||||
|
||||
```js
|
||||
var calculator = new Calculator();
|
||||
let calculator = new Calculator();
|
||||
calculator.read();
|
||||
|
||||
alert( "Сумма=" + calculator.sum() );
|
||||
alert( "Произведение=" + calculator.mul() );
|
||||
alert( "Sum=" + calculator.sum() );
|
||||
alert( "Mul=" + calculator.mul() );
|
||||
```
|
||||
|
||||
[demo]
|
||||
|
||||
|
|
|
@ -2,7 +2,7 @@ function Accumulator(startingValue) {
|
|||
this.value = startingValue;
|
||||
|
||||
this.read = function() {
|
||||
this.value += +prompt('Сколько добавлять будем?', 0);
|
||||
this.value += +prompt('How much to add?', 0);
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,8 +1,4 @@
|
|||
describe("Accumulator(1)", function() {
|
||||
var accumulator;
|
||||
before(function() {
|
||||
accumulator = new Accumulator(1);
|
||||
});
|
||||
describe("Accumulator", function() {
|
||||
|
||||
beforeEach(function() {
|
||||
sinon.stub(window, "prompt")
|
||||
|
@ -12,26 +8,23 @@ describe("Accumulator(1)", function() {
|
|||
prompt.restore();
|
||||
});
|
||||
|
||||
it("начальное значение 1", function() {
|
||||
it("initial value is the argument of the constructor", function() {
|
||||
let accumulator = new Accumulator(1);
|
||||
|
||||
assert.equal(accumulator.value, 1);
|
||||
});
|
||||
|
||||
it("после ввода 0 значение 1", function() {
|
||||
it("after reading 0, the value is 1", function() {
|
||||
let accumulator = new Accumulator(1);
|
||||
prompt.returns("0");
|
||||
accumulator.read();
|
||||
assert.equal(accumulator.value, 1);
|
||||
});
|
||||
|
||||
it("после ввода 1 значение 2", function() {
|
||||
it("after reading 1, the value is 2", function() {
|
||||
let accumulator = new Accumulator(1);
|
||||
prompt.returns("1");
|
||||
accumulator.read();
|
||||
assert.equal(accumulator.value, 2);
|
||||
});
|
||||
|
||||
it("после ввода 2 значение 4", function() {
|
||||
prompt.returns("2");
|
||||
accumulator.read();
|
||||
assert.equal(accumulator.value, 4);
|
||||
});
|
||||
|
||||
});
|
||||
});
|
||||
|
|
|
@ -5,14 +5,13 @@ function Accumulator(startingValue) {
|
|||
this.value = startingValue;
|
||||
|
||||
this.read = function() {
|
||||
this.value += +prompt('Сколько добавлять будем?', 0);
|
||||
this.value += +prompt('How much to add?', 0);
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
var accumulator = new Accumulator(1);
|
||||
let accumulator = new Accumulator(1);
|
||||
accumulator.read();
|
||||
accumulator.read();
|
||||
alert( accumulator.value );
|
||||
alert(accumulator.value);
|
||||
```
|
||||
|
||||
|
|
|
@ -2,26 +2,24 @@ importance: 5
|
|||
|
||||
---
|
||||
|
||||
# Создать Accumulator при помощи конструктора
|
||||
# Create new Accumulator
|
||||
|
||||
Напишите *функцию-конструктор* `Accumulator(startingValue)`.
|
||||
Объекты, которые она создает, должны хранить текущую сумму и прибавлять к ней то, что вводит посетитель.
|
||||
Create a constructor function `Accumulator(startingValue)`.
|
||||
|
||||
Более формально, объект должен:
|
||||
Object that it creates should:
|
||||
|
||||
- Хранить текущее значение в своём свойстве `value`. Начальное значение свойства `value` ставится конструктором равным `startingValue`.
|
||||
- Метод `read()` вызывает `prompt`, принимает число и прибавляет его к свойству `value`.
|
||||
- Store the "current value" in the property `value`. The starting value is set to the argument of the constructor `startingValue`.
|
||||
- The `read()` method should use `prompt` to read a new number and add it to `value`.
|
||||
|
||||
Таким образом, свойство `value` является текущей суммой всего, что ввел посетитель при вызовах метода `read()`, с учетом начального значения `startingValue`.
|
||||
In other words, the `value` property is the sum of all user-entered values with the initial value `startingValue`.
|
||||
|
||||
Ниже вы можете посмотреть работу кода:
|
||||
Here's the demo of the code:
|
||||
|
||||
```js
|
||||
var accumulator = new Accumulator(1); // начальное значение 1
|
||||
accumulator.read(); // прибавит ввод prompt к текущему значению
|
||||
accumulator.read(); // прибавит ввод prompt к текущему значению
|
||||
alert( accumulator.value ); // выведет текущее значение
|
||||
let accumulator = new Accumulator(1); // initial value 1
|
||||
accumulator.read(); // adds the user-entered value
|
||||
accumulator.read(); // adds the user-entered value
|
||||
alert(accumulator.value); // shows the sum of these values
|
||||
```
|
||||
|
||||
[demo]
|
||||
|
||||
|
|
|
@ -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