Skip to content

Proxy and Reflect #261

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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
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
14 changes: 7 additions & 7 deletions 1-js/99-js-misc/01-proxy/01-error-nonexisting/task.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
# Error on reading non-existent property
# Errore in lettura di una proprietà non esistente

Usually, an attempt to read a non-existent property returns `undefined`.
Solitamente, un tentativo di accesso ad una proprietà non esistente ritorna `undefined`.

Create a proxy that throws an error for an attempt to read of a non-existent property instead.
Create un proxy che generi un errore ad ogni tentativo di accesso ad una proprietà non esistente.

That can help to detect programming mistakes early.
Questo può aiutare a trovare errori di programmazione in anticipo.

Write a function `wrap(target)` that takes an object `target` and return a proxy that adds this functionality aspect.
Scrivete una funzione `wrap(target)` che prende un oggetto `target` e ne ritorna un proxy con la funzionalità appena descritta.

That's how it should work:
Ecco come dovrebbe funzionare:

```js
let user = {
Expand All @@ -18,7 +18,7 @@ let user = {
function wrap(target) {
return new Proxy(target, {
*!*
/* your code */
/* il vostro codice */
*/!*
});
}
Expand Down
4 changes: 2 additions & 2 deletions 1-js/99-js-misc/01-proxy/02-array-negative/solution.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ let array = [1, 2, 3];
array = new Proxy(array, {
get(target, prop, receiver) {
if (prop < 0) {
// even if we access it like arr[1]
// prop is a string, so need to convert it to number
// anche se vi accediamo come arr[1]
// prop è una stringa, quindi dobbiamo convertirla a number
prop = +prop + target.length;
}
return Reflect.get(target, prop, receiver);
Expand Down
22 changes: 11 additions & 11 deletions 1-js/99-js-misc/01-proxy/02-array-negative/task.md
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@

# Accessing array[-1]
# Accesso ad un array[-1]

In some programming languages, we can access array elements using negative indexes, counted from the end.
In alcuni linguaggi di programmazione, possiamo accedere agli elementi dell'array utilizzando indici negativi, che iniziano il conteggio dalla coda dell'array.

Like this:
Come nell'esempio:

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

array[-1]; // 3, the last element
array[-2]; // 2, one step from the end
array[-3]; // 1, two steps from the end
array[-1]; // 3, l'ultimo elemento
array[-2]; // 2, il penultimo elemento
array[-3]; // 1, il terzultimo elemento
```

In other words, `array[-N]` is the same as `array[array.length - N]`.
In altre parole, `array[-N]` equivale a `array[array.length - N]`.

Create a proxy to implement that behavior.
Create un proxy che implementa questa funzionalità.

That's how it should work:
Ecco come dovrebbe funzionare:

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

array = new Proxy(array, {
/* your code */
/* il vostro codice */
});

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

// Other array functionality should be kept "as is"
// Le altre funzionalità dell'array devono rimanere inalterate
```
18 changes: 9 additions & 9 deletions 1-js/99-js-misc/01-proxy/03-observable/solution.md
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
The solution consists of two parts:
La soluzione consiste di due parti:

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.
2. We need a proxy with `set` trap to call handlers in case of any change.
1. Quando `.observe(handler)` viene invocato, dobbiamo memorizzare l'handler da qualche parte, per poter essere in grado di invocarlo più tardi. Possiamo memorizzare gli handler nell'oggetto, utilizzando un symbol come chiave della proprietà.
2. Abbiamo bisogno di un proxy con la trappola `set` per poter invocare gli handlers in caso di cambiamenti.

```js run
let handlers = Symbol('handlers');

function makeObservable(target) {
// 1. Initialize handlers store
// 1. Inizializziamo lo store per gli handlers
target[handlers] = [];

// Store the handler function in array for future calls
// Memorizziamo l'handler nell'array per poterlo invocare successivamente
target.observe = function(handler) {
this[handlers].push(handler);
};

// 2. Create a proxy to handle changes
// 2. Creiamo un proxy per gestire le modifiche
return new Proxy(target, {
set(target, property, value, receiver) {
let success = Reflect.set(...arguments); // forward the operation to object
if (success) { // if there were no error while setting the property
// call all handlers
let success = Reflect.set(...arguments); // inoltriamo l'operazione all'oggetto
if (success) { // se non è stato generato alcun errore durante il cambiamento della proprietà
// invochiamo tutti gli handlers
target[handlers].forEach(handler => handler(property, value));
}
return success;
Expand Down
12 changes: 6 additions & 6 deletions 1-js/99-js-misc/01-proxy/03-observable/task.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@

# Observable

Create a function `makeObservable(target)` that "makes the object observable" by returning a proxy.
Create una funzione `makeObservable(target)` che "rende l'oggetto osservabile" ritornandone un proxy.

Here's how it should work:
Ecco come dovrebbe funzionare:

```js run
function makeObservable(target) {
/* your code */
/* il vostro codice */
}

let user = {};
Expand All @@ -20,8 +20,8 @@ user.observe((key, value) => {
user.name = "John"; // alerts: SET name=John
```

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.
In altre parole, un oggetto ritornato da `makeObservable` equivale a quello originale, ma possiede il metodo `observe(handler)` che imposta la funzione `handler` per essere invocata quando una qualsiasi proprietà cambia.

Whenever a property changes, `handler(key, value)` is called with the name and value of the property.
Quando una proprietà verrà modificata, `handler(key, value)` verrà invocato con il nome ed il valore della proprietà.

P.S. In this task, please only take care about writing to a property. Other operations can be implemented in a similar way.
P.S. In questo task, gestite solamente la scrittura della proprietà. Le altre operazioni possono essere implementate in maniera simile.
Loading