Skip to content

Commit e41a71d

Browse files
authored
Merge pull request #422 from danilolmc/update-proxy-reflect
Proxy and Reflect
2 parents c3e18a3 + 4f35590 commit e41a71d

File tree

7 files changed

+331
-345
lines changed

7 files changed

+331
-345
lines changed

1-js/99-js-misc/01-proxy/01-error-nonexisting/solution.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ function wrap(target) {
1010
if (prop in target) {
1111
return Reflect.get(target, prop, receiver);
1212
} else {
13-
throw new ReferenceError(`Property doesn't exist: "${prop}"`)
13+
throw new ReferenceError(`A propriedade não existe: "${prop}"`)
1414
}
1515
}
1616
});
@@ -19,5 +19,5 @@ function wrap(target) {
1919
user = wrap(user);
2020

2121
alert(user.name); // John
22-
alert(user.age); // ReferenceError: Property doesn't exist: "age"
22+
alert(user.age); // ReferenceError: A propriedade não existe: "age"
2323
```
Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
# Error on reading non-existent property
1+
# Erro ao ler propriedade inexistente
22

3-
Usually, an attempt to read a non-existent property returns `undefined`.
3+
Normalmente, uma tentativa de ler uma propriedade inexistente retorna `undefined`.
44

5-
Create a proxy that throws an error for an attempt to read of a non-existent property instead.
5+
Crie um proxy que lança um erro numa tentativa de ler uma propriedade inexistente.
66

7-
That can help to detect programming mistakes early.
7+
Isso pode ajudar a detectar erros de programação antecipadamente.
88

9-
Write a function `wrap(target)` that takes an object `target` and return a proxy that adds this functionality aspect.
9+
Escreva uma função `wrap(target)` que recebe um objeto `target` e retorna um proxy que adiciona esse aspecto funcional
1010

11-
That's how it should work:
11+
É assim que deve funcionar:
1212

1313
```js
1414
let user = {
@@ -18,7 +18,7 @@ let user = {
1818
function wrap(target) {
1919
return new Proxy(target, {
2020
*!*
21-
/* your code */
21+
/* seu código */
2222
*/!*
2323
});
2424
}
@@ -27,6 +27,6 @@ user = wrap(user);
2727

2828
alert(user.name); // John
2929
*!*
30-
alert(user.age); // ReferenceError: Property doesn't exist: "age"
30+
alert(user.age); // ReferenceError: A propriedade não existe: "age"
3131
*/!*
3232
```

1-js/99-js-misc/01-proxy/02-array-negative/solution.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ let array = [1, 2, 3];
55
array = new Proxy(array, {
66
get(target, prop, receiver) {
77
if (prop < 0) {
8-
// even if we access it like arr[1]
9-
// prop is a string, so need to convert it to number
8+
// mesmo se acessarmos como arr[1]
9+
// prop é uma string, então é necessário convertê-la para um número.
1010
prop = +prop + target.length;
1111
}
1212
return Reflect.get(target, prop, receiver);
Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
11

2-
# Accessing array[-1]
2+
# Acessando array[-1]
33

4-
In some programming languages, we can access array elements using negative indexes, counted from the end.
4+
Em algumas linguagens de programação, podemos acessar elementos de um array usando índices negativos, contados a partir do final.
55

6-
Like this:
6+
Assim:
77

88
```js
99
let array = [1, 2, 3];
1010

11-
array[-1]; // 3, the last element
12-
array[-2]; // 2, one step from the end
13-
array[-3]; // 1, two steps from the end
11+
array[-1]; // 3, o último elemento
12+
array[-2]; // 2, uma posição a partir da última
13+
array[-3]; // 1, duas posições a partir da última
1414
```
1515

16-
In other words, `array[-N]` is the same as `array[array.length - N]`.
16+
Em outras palavras, `array[-N]` é o mesmo que `array[array.length - N]`.
1717

18-
Create a proxy to implement that behavior.
18+
Crie um proxy para implementar esse comportamento.
1919

20-
That's how it should work:
20+
É assim que deve funcionar:
2121

2222
```js
2323
let array = [1, 2, 3];
2424

2525
array = new Proxy(array, {
26-
/* your code */
26+
/* seu código */
2727
});
2828

2929
alert( array[-1] ); // 3
3030
alert( array[-2] ); // 2
3131

32-
// Other array functionality should be kept "as is"
32+
// Outras funcionalidades do array devem ser mantidas "como estão".
3333
```

1-js/99-js-misc/01-proxy/03-observable/solution.md

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,26 @@
1-
The solution consists of two parts:
1+
A solução consiste em duas partes:
22

3-
1. Whenever `.observe(handler)` is called, we need to remember the handler somewhere, to be able to call it later. We can store handlers right in the object, using our symbol as the property key.
4-
2. We need a proxy with `set` trap to call handlers in case of any change.
3+
1. Sempre que `.observe(handler)` for chamado, precisamos lembrar handler em algum lugar, para ser possível chamá-lo mais tarde. Podemos armazenar os handlers diretamente no objeto, usando nosso symbol como chave da propriedade.
4+
2. Precisamos de um proxy com uma armadilha (trap) `set` para chamar os handlers no caso de alguma mudança.
55

66
```js run
77
let handlers = Symbol('handlers');
88

99
function makeObservable(target) {
10-
// 1. Initialize handlers store
10+
// 1. Inicializa o armazenamento de manipuladores
1111
target[handlers] = [];
1212

13-
// Store the handler function in array for future calls
13+
// Armazena a função handler no array para futuras chamadas
1414
target.observe = function(handler) {
1515
this[handlers].push(handler);
1616
};
1717

18-
// 2. Create a proxy to handle changes
18+
// 2. Cria um proxy para lidar com as mudanças
1919
return new Proxy(target, {
2020
set(target, property, value, receiver) {
21-
let success = Reflect.set(...arguments); // forward the operation to object
22-
if (success) { // if there were no error while setting the property
23-
// call all handlers
21+
let success = Reflect.set(...arguments); // Encaminha a operação para o objeto
22+
if (success) { // Se não houve erro ao definir a propriedade
23+
// chama rodos os handlers
2424
target[handlers].forEach(handler => handler(property, value));
2525
}
2626
return success;
Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11

22
# Observable
33

4-
Create a function `makeObservable(target)` that "makes the object observable" by returning a proxy.
4+
Crie uma função makeObservable(target) que "torna o objeto observável" ao retornar um proxy.
55

6-
Here's how it should work:
6+
Aqui está como deveria funcionar:
77

88
```js run
99
function makeObservable(target) {
10-
/* your code */
10+
/* seu código */
1111
}
1212

1313
let user = {};
@@ -17,11 +17,11 @@ user.observe((key, value) => {
1717
alert(`SET ${key}=${value}`);
1818
});
1919

20-
user.name = "John"; // alerts: SET name=John
20+
user.name = "John"; // alerta: SET name=John
2121
```
2222

23-
In other words, an object returned by `makeObservable` is just like the original one, but also has the method `observe(handler)` that sets `handler` function to be called on any property change.
23+
Em outras palavras, um objeto retornado por `makeObservable` é exatamente como o original, mas também possui o método `observe(handler)` que define a função `handler` para ser chamada em qualquer alteração de propriedade.
2424

25-
Whenever a property changes, `handler(key, value)` is called with the name and value of the property.
25+
Sempre que uma propriedade muda, `handler(key, value)` é chamado com o nome e o valor da propriedade.
2626

27-
P.S. In this task, please only take care about writing to a property. Other operations can be implemented in a similar way.
27+
P.S. Nesta tarefa, preocupe-se apenas com a escrita em uma propriedade. Outras operações podem ser implementadas de maneira semelhante.

0 commit comments

Comments
 (0)