Skip to content

Commit edf7335

Browse files
authored
Merge pull request #451 from joaquinelio/leproso
Proxy and Reflect
2 parents da25759 + 5d16607 commit edf7335

File tree

7 files changed

+330
-330
lines changed

7 files changed

+330
-330
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(`La propiedad no 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: La propiedad no 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+
# Error al leer una propiedad no existente
22

3-
Usually, an attempt to read a non-existent property returns `undefined`.
3+
Usualmente, el intento de leer una propiedad que no existe devuelve `undefined`.
44

5-
Create a proxy that throws an error for an attempt to read of a non-existent property instead.
5+
Crea en su lugar un proxy que arroje un error por intentar leer una propiedad no existente.
66

7-
That can help to detect programming mistakes early.
7+
Esto puede ayudar a detectar equivocaciones en la programación en forma temprana.
88

9-
Write a function `wrap(target)` that takes an object `target` and return a proxy that adds this functionality aspect.
9+
Escribe una función `wrap(target)` que tome un objeto `target` y devuelva un proxy que agregue este aspecto de funcionalidad.
1010

11-
That's how it should work:
11+
Así es como debe 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+
/* tu 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: La propiedad no 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+
// incluso aunque la accedamos como arr[1]
9+
// prop es un string, así que necesitamos convertirla a number
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+
# Accediendo a array[-1]
33

4-
In some programming languages, we can access array elements using negative indexes, counted from the end.
4+
En algunos lenguajes de programación podemos acceder a los arrays usando índices negativos, contando desde el final.
55

6-
Like this:
6+
Como esto:
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, el último elemento
12+
array[-2]; // 2, el penúltimo elemento, uno antes del final
13+
array[-3]; // 1, el antepenúltimo elemento, dos antes el final
1414
```
1515

16-
In other words, `array[-N]` is the same as `array[array.length - N]`.
16+
En otras palabras, `array[-N]` es lo mismo que `array[array.length - N]`.
1717

18-
Create a proxy to implement that behavior.
18+
Crea un proxy para implementar tal comportamiento.
1919

20-
That's how it should work:
20+
Así es como debe funcionar:
2121

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

2525
array = new Proxy(array, {
26-
/* your code */
26+
/* tu 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+
// el resto de la funcionalidad debe mantenerse igual.
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+
La solución consiste de dos 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. Cuando `.observe(handler)` es llamado, necesitamos recordar el manejador 'handler' en algún lugar para poder llamarlo después. Podemos almacenar los manejadores directamente en el objeto, usando nuestro symbol como clave de la propiedad.
4+
2. Necesitamos un proxy con la trampa `set` que llame a los manejadores en caso de cualquier cambio.
55

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

99
function makeObservable(target) {
10-
// 1. Initialize handlers store
10+
// 1. Inicializa el almacén de manejadores
1111
target[handlers] = [];
1212

13-
// Store the handler function in array for future calls
13+
// Almacena la función manejadora en el array para llamadas futuras
1414
target.observe = function(handler) {
1515
this[handlers].push(handler);
1616
};
1717

18-
// 2. Create a proxy to handle changes
18+
// 2. Crea un proxy para manejar cambios
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); // reenvía la operación al objeto
22+
if (success) { // si no hay errores al establecer la propiedad
23+
// llama a todos los manejadores
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+
Crea una función `makeObservable(target)` que "haga el objeto observable" devolviendo un proxy.
55

6-
Here's how it should work:
6+
Así es como debe funcionar:
77

88
```js run
99
function makeObservable(target) {
10-
/* your code */
10+
/* tu 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+
En otras palabras, un objeto devuelto por `makeObservable` es como el original pero que también tiene el método `observe(handler)` que establece una función `handler` que será llamada en cualquier cambio de propiedad.
2424

25-
Whenever a property changes, `handler(key, value)` is called with the name and value of the property.
25+
cada vez que una propiedad cambie, `handler(key, value)` es llamado con el nombre y el valor de la propiedad.
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.D. En esta tarea, solo toma en cuenta la escritura de una propiedad. Otras operaciones pueden ser implementadas de manera similar.

0 commit comments

Comments
 (0)