Skip to content
New issue

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

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

[WIP]-Segment 1 #20

Open
wants to merge 2 commits into
base: segment-1
Choose a base branch
from
Open
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
70 changes: 66 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,20 @@
watchedObject.a.b[0].c = true;
//=> 'Object changed: 2'
*/
function onChange() {}
function onChange() {
// eslint-disable-next-line
const object = {
foo: false,
a: {
b: [
{
c: false,
},
],
},
};
// let proxy = new Proxy(object, handler);
}

/* Q2: Use ES6 Proxy to implement the following function
Call a method on an iterable to call it on all items of the iterable
Expand Down Expand Up @@ -60,7 +73,24 @@ const proxyIterable = () => {};
console.log(obj2.bar);
//=> [TypeError] Unknown property: bar
*/
function knownProp() {}
function knownProp(arg) {
const obj = arg;
const handler = {
get: (target, key) => {
if (key in target) {
return Reflect.get(target, key);
}
return new TypeError('Unknown property');
},
set: (target, key, value) => {
// eslint-disable-next-line
target[key] = value;
},
};
// eslint-disable-next-line
const proxy = new Proxy(obj, handler);
return proxy;
}

/* Q4: Use ES6 Proxy to support negative index in array (*)

Expand All @@ -69,7 +99,28 @@ function knownProp() {}
console.log(unicorn[-1]);
//=> 'rainbow' (gets the 1st element from last)
*/
function negativeIndex() {}
function negativeIndex(arr) {
if (!Array.isArray(arr)) {
throw new TypeError('Only arrays are supported');
}
const handler = {
// eslint-disable-next-line
get: (target, key) => {
if (key < 0) {
const test = Number(3 + Number(key));
return Reflect.get(target, test);
}
return Reflect.get(target, key);
// let x = Number(key);
},
set: (target, key, value) => {
// eslint-disable-next-line
target[key] = value;
},
};
const proxy = new Proxy(arr, handler);
return proxy;
}

/* Q5: Use ES6 Proxy to get a default property if a non-existing
property is accessed.
Expand All @@ -78,7 +129,18 @@ function negativeIndex() {}
myObj.foo // bar
myObj.xyz // default
*/
function setDefaultProperty() {}
function setDefaultProperty(obj, def) {
const handler = {
get: (target, key) => {
if (key in target) {
return Reflect.get(target, key);
}
return def;
},
};
const proxy = new Proxy(obj, handler);
return proxy;
}

/* Q6: Use ES6 Proxy to hide private properties of an object.
See test cases for further info.
Expand Down