Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
function makeCounter() {
let count = 0;

// ... your code ...
// ... seu código ...
}

let counter = makeCounter();

alert( counter() ); // 0
alert( counter() ); // 1

counter.set(10); // set the new count
counter.set(10); // define a nova contagem

alert( counter() ); // 10

counter.decrease(); // decrease the count by 1
counter.decrease(); // diminui a contagem em 1

alert( counter() ); // 10 (instead of 11)
alert( counter() ); // 10 (em vez de 11)
Original file line number Diff line number Diff line change
@@ -1,41 +1,41 @@
describe("counter", function() {

it("increases from call to call", function() {
it("aumenta a cada chamada", function() {

let counter = makeCounter();

assert.equal( counter(), 0 );
assert.equal( counter(), 1 );
assert.equal( counter(), 2 );
assert.equal( counter(), 0 );

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mudanças só de whitespace (remoção de espaços no fim das linhas) neste arquivo não fazem parte da tradução e aumentam a divergência com o upstream (en.javascript.info), gerando conflitos desnecessários em syncs futuros. Sugiro reverter essas linhas e manter só a tradução dos it(...).

assert.equal( counter(), 1 );
assert.equal( counter(), 2 );
});


describe("counter.set", function() {
it("sets the count", function() {
it("define a contagem", function() {

let counter = makeCounter();

counter.set(10);

assert.equal( counter(), 10 );
assert.equal( counter(), 11 );
assert.equal( counter(), 10 );
assert.equal( counter(), 11 );
});
});

describe("counter.decrease", function() {
it("decreases the count", function() {
it("diminui a contagem", function() {

let counter = makeCounter();

counter.set(10);

assert.equal( counter(), 10 );
assert.equal( counter(), 10 );

counter.decrease();

assert.equal( counter(), 10 );
assert.equal( counter(), 10 );

});
});

});
});
Original file line number Diff line number Diff line change
@@ -1,2 +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`.
A solução usa `count` na variável local, mas os métodos adicionais são escritos diretamente no `counter`. Eles compartilham o mesmo ambiente léxico externo e também conseguem acessar o `count` atual.
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ importance: 5

---

# Set and decrease for counter
# Define e diminui o contador

Modify the code of `makeCounter()` so that the counter can also decrease and set the number:
Modifique o código de `makeCounter()` para que o contador também possa diminuir e definir o número:

- `counter()` should return the next number (as before).
- `counter.set(value)` should set the counter to `value`.
- `counter.decrease()` should decrease the counter by 1.
- `counter()` deve retornar o próximo número (como antes).
- `counter.set(value)` deve definir o contador para `value`.
- `counter.decrease()` deve diminuir o contador em 1.

See the sandbox code for the complete usage example.
Veja o código do sandbox para o exemplo completo de uso.

P.S. You can use either a closure or the function property to keep the current count. Or write both variants.
P.S. Você pode usar tanto uma closure quanto a propriedade de função para manter a contagem atual. Ou escrever as duas variantes.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
function sum(a){
// Your code goes here.
// Seu código vai aqui.

}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@

1. For the whole thing to work *anyhow*, the result of `sum` must be function.
2. That function must keep in memory the current value between calls.
3. According to the task, the function must become the number when used in `==`. Functions are objects, so the conversion happens as described in the chapter <info:object-toprimitive>, and we can provide our own method that returns the number.
1. Para que a coisa toda funcione *de alguma forma*, o resultado de `sum` precisa ser uma função.
2. Essa função precisa guardar na memória o valor atual entre as chamadas.
3. De acordo com a tarefa, a função precisa se tornar o número quando usada com `==`. Funções são objetos, então a conversão acontece como descrito no capítulo <info:object-toprimitive>, e podemos fornecer nosso próprio método que retorna o número.

Now the code:
Agora o código:

```js demo run
function sum(a) {
Expand All @@ -28,28 +28,28 @@ alert( sum(6)(-1)(-2)(-3) ); // 0
alert( sum(0)(1)(2)(3)(4)(5) ); // 15
```

Please note that the `sum` function actually works only once. It returns function `f`.
Observe que a função `sum` na verdade só funciona uma vez. Ela retorna a função `f`.

Then, on each subsequent call, `f` adds its parameter to the sum `currentSum`, and returns itself.
Depois, em cada chamada subsequente, `f` soma seu parâmetro à soma `currentSum`, e retorna a si mesma.

**There is no recursion in the last line of `f`.**
**Não existe recursão na última linha de `f`.**

Here is what recursion looks like:
Veja como seria uma recursão:

```js
function f(b) {
currentSum += b;
return f(); // <-- recursive call
return f(); // <-- chamada recursiva
}
```

And in our case, we just return the function, without calling it:
E, no nosso caso, apenas retornamos a função, sem chamá-la:

```js
function f(b) {
currentSum += b;
return f; // <-- does not call itself, returns itself
return f; // <-- não chama a si mesma, retorna a si mesma
}
```

This `f` will be used in the next call, again return itself, as many times as needed. Then, when used as a number or a string -- the `toString` returns the `currentSum`. We could also use `Symbol.toPrimitive` or `valueOf` here for the conversion.
Esse `f` será usado na próxima chamada, de novo retornando a si mesma, quantas vezes forem necessárias. Então, quando usado como um número ou uma string -- o `toString` retorna o `currentSum`. Também poderíamos usar `Symbol.toPrimitive` ou `valueOf` aqui para a conversão.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concordância de gênero inconsistente: "Esse f será usado" (masc.) e "quando usado" vs "retornando a si mesma" (fem.). Sugestão: "Essa f será usada na próxima chamada, de novo retornando a si mesma... quando usada como um número" — ou manter tudo no masculino ("retornando a si mesmo").

Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ importance: 2

---

# Sum with an arbitrary amount of brackets
# Soma com uma quantidade arbitrária de parênteses

Write function `sum` that would work like this:
Escreva a função `sum` que funcione assim:

```js
sum(1)(2) == 3; // 1 + 2
Expand All @@ -14,4 +14,4 @@ sum(6)(-1)(-2)(-3) == 0
sum(0)(1)(2)(3)(4)(5) == 15
```

P.S. Hint: you may need to setup custom object to primitive conversion for your function.
P.S. Dica: você pode precisar configurar uma conversão personalizada de objeto para primitivo na sua função.
Loading