Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Function object, NFE#204

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Closed
odsantos wants to merge2 commits intojavascript-tutorial:masterfromodsantos:function-object-nfe
Closed
Show file tree
Hide file tree
Changes fromall 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
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
function makeCounter() {
let count = 0;

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

let counter = makeCounter();

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

counter.set(10); //set the new count
counter.set(10); //inicializa 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)
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
describe("counter", function() {

it("increases from call to call", function() {
it("aumenta de chamada em chamada", function() {

let counter = makeCounter();

Expand All@@ -11,7 +11,7 @@ describe("counter", function() {


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

let counter = makeCounter();

Expand All@@ -23,7 +23,7 @@ describe("counter", function() {
});

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

let counter = makeCounter();

Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff 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 métodos para a adição são escritos precisamente dentro de`counter`.Eles partilham o mesmo ambiente léxico exterior e podem também podem aceder à `count` corrente.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,14 @@ importance: 5

---

#Set and decrease for counter
#Inicializa 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()`de forma a que o contador também possa ser diminuído e inicializado a um numero:

- `counter()`should return the next number (as before).
- `counter.set(value)`should set the `count`to `value`.
- `counter.decrease()`should decrease the `count`by 1.
- `counter()`deve retornar o próximo numero (como anteriormente).
- `counter.set(value)`deve inicializar o `count`a `value`.
- `counter.decrease()`deve diminuir o `count`em 1.

See the sandbox code for the complete usage example.
Veja o código na sandbox para um exemplo prático completo.

P.S.You can use either a closureor the function property to keep the current count. Or write both variants.
P.S.Você pode usar quer uma closurecomo uma propriedade de função para guardar a contagem corrente. Ou escrever ambas as variantes.
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
function sum(a){
//Your code goes here.
//O seu código vai aqui.

}

Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff 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 tudo funcione *de qualquer jeito*, o resultado de `sum`tem de ser uma função.
2.Essa função tem de guardar na memória o valor corrente entre as chamadas.
3.De acordo com a tarefa, a função tem de se tornar no numero quando for usada em`==`.Funções são objetos, portanto a conversão se faz como descrito no capítulo <info:object-toprimitive>,e nós podemos fornecer o nosso próprio método para retornar o numero.

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
```

Pleasenotethat the`sum` function actually works only once. It returns function `f`.
Por favor,noteque a função`sum`, na verdade, apenas trabalha uma vez. Ela retorna a função `f`.

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

**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:
Aqui está como se parece a 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, nós apenas retornamos a função, sem a chamar:

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

This `f`will be used in the next call, again return itself, as many times as needed. Then, when used as a number or astring --the `toString`returns the `currentSum`.We could also use `Symbol.toPrimitive`or `valueOf`here for the conversion.
Esta `f`será usada na próxima chamada, retornando novamente ela mesma, tantas vezes quantas necessárias. Assim, quando usada como um numero ou umastring --o `toString`retorna a `currentSum`.Nós poderíamos também usar `Symbol.toPrimitive`ou `valueOf`aqui para a conversão.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,9 +2,9 @@ importance: 2

---

#Sum with an arbitrary amount of brackets
#Soma com um numero arbitrário de parênteses

Write function`sum`that would work like this:
Escreva uma função`sum`que trabalhe 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.Sugestão: você pode necessitar de configurar uma conversão personalizada de objeto para primitivo para a sua função.
Loading

[8]ページ先頭

©2009-2025 Movatter.jp