This commit is contained in:
Ilya Kantor 2017-03-21 17:14:05 +03:00
parent ab9ab64bd5
commit 97c8f22bbb
289 changed files with 195 additions and 172 deletions

View file

@ -0,0 +1,13 @@
function makeCounter() {
let count = 0;
function counter() {
return count++;
}
counter.set = value => count = value;
counter.decrease = () => count--;
return counter;
}

View file

@ -0,0 +1,18 @@
function makeCounter() {
let count = 0;
// ... your code ...
}
let counter = makeCounter();
alert( counter() ); // 0
alert( counter() ); // 1
counter.set(10); // set the new count
alert( counter() ); // 10
counter.decrease(); // decrease the count by 1
alert( counter() ); // 10 (instead of 11)

View file

@ -0,0 +1,41 @@
describe("counter", function() {
it("increases from call to call", function() {
let counter = makeCounter();
assert.equal( counter(), 0 );
assert.equal( counter(), 1 );
assert.equal( counter(), 2 );
});
describe("counter.set", function() {
it("sets the count", function() {
let counter = makeCounter();
counter.set(10);
assert.equal( counter(), 10 );
assert.equal( counter(), 11 );
});
});
describe("counter.decrease", function() {
it("decreases the count", function() {
let counter = makeCounter();
counter.set(10);
assert.equal( counter(), 10 );
counter.decrease();
assert.equal( counter(), 10 );
});
});
});

View file

@ -0,0 +1,2 @@
The solution uses `count` in the local variable, but addition methods are written right into the `counter`. They share the same outer lexical environment and also can access the current `count`.

View file

@ -0,0 +1,15 @@
importance: 5
---
# Set and decrease for counter
Modify the code of `makeCounter()` so that the counter can also decrease and set the number:
- `counter()` should return the next number (as before).
- `counter.set(value)` should set the `count` to `value`.
- `counter.decrease(value)` should decrease the `count` by 1.
See the sandbox code for the complete usage example.
P.S. You can use either a closure or the function property to keep the current count. Or write both variants.