proxy
This commit is contained in:
parent
726f08a179
commit
852b9bf581
20 changed files with 1074 additions and 20 deletions
19
10-misc/01-proxy/02-array-negative/solution.md
Normal file
19
10-misc/01-proxy/02-array-negative/solution.md
Normal file
|
@ -0,0 +1,19 @@
|
|||
|
||||
```js run
|
||||
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
|
||||
prop = +prop + target.length;
|
||||
}
|
||||
return Reflect.get(target, prop, receiver);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
alert(array[-1]); // 3
|
||||
alert(array[-2]); // 2
|
||||
```
|
33
10-misc/01-proxy/02-array-negative/task.md
Normal file
33
10-misc/01-proxy/02-array-negative/task.md
Normal file
|
@ -0,0 +1,33 @@
|
|||
|
||||
# Accessing array[-1]
|
||||
|
||||
In some languages, we can access array elements using negative indexes, counted from the end.
|
||||
|
||||
Like this:
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
In other words, `array[-N]` is the same as `array[array.length - N]`.
|
||||
|
||||
Create a proxy to implement that behavior.
|
||||
|
||||
That's how it should work:
|
||||
|
||||
```js
|
||||
let array = [1, 2, 3];
|
||||
|
||||
array = new Proxy(array, {
|
||||
/* your code */
|
||||
});
|
||||
|
||||
alert( array[-1] ); // 3
|
||||
alert( array[-2] ); // 2
|
||||
|
||||
// Other array functionality should be kept "as is"
|
||||
```
|
Loading…
Add table
Add a link
Reference in a new issue