Chapter 12
Here are the solutions to the Exercises , for the Chapter 12, Deep Dive into Metaprogramming chapter.
Exercise 1 'use strict' ; class Counter { constructor () { this .count = 0; } incrementBy(value) { this .count += value; return this .count; } decrementBy(value) { this .count -= value; return this .count; } } const call = function (counter, method, ...data) { const methodToCall = Reflect.get (counter, method); return Reflect.apply(methodToCall, counter, data); }; const counter = new Counter(); console.log(call(counter, 'incrementBy' , 10)); console.log(call(counter, 'decrementBy' , 7)); console.log(counter.count);
Exercise 2 target refers to sample propertyName refers to "foo" receiver refers to proxy Exercise 3
There’s a small twist in this exercise. At first thought, merely Proxy.revocable(instance, {}); appears to be sufficient. However, that approach will result in an incompatible type error when proxy.getYear() is called. The type of the proxy is not the same as the type of Date . To fix this we have to use the bind() method, like so:
'use strict' ; const createRevocableProxy = function (instance) { const handler = { get: function (target, propertyName ) { return Reflect.get (target, propertyName).bind(target); } }; const { proxy, revoke } = Proxy.revocable(instance, handler); setTimeout(revoke, 3000); return proxy; }; const proxy = createRevocableProxy(new Date()); const callGetYear = function () { try { console.log(1900 + proxy.getYear()); } catch (ex) { console.log(ex.message); } }; callGetYear(); setTimeout(callGetYear, 1000); setTimeout(callGetYear, 5000);
Exercise 4 'use strict' ; const createPlayMethodProxy = function (instance) { const handler = { get: function (target, propertyName) { if (propertyName.startsWith('play' )) { const activity = propertyName.substring(4); if (target.activities.includes(activity)) { return () => `I love to play ${activity}` ; } else { return () => `I don't play ${activity}` ; } } else { throw new Error(` ${propertyName} is not a function` ); } } }; return new Proxy(instance, handler); }; const proxy = createPlayMethodProxy({ activities: ['Football' , 'Tennis' ] }); console.log(proxy.playTennis()); console.log(proxy.playFootball()); console.log(proxy.playPolitics()); try { console.log(proxy.dance()); } catch (ex) { console.log(ex.message); }
Exercise 5 'use strict' ; const proxy = new Proxy(Set.prototype, { get: function (target, propertyName, receiver) { return receiver.has(propertyName); } }); Reflect.setPrototypeOf(Set.prototype, proxy); const fruits = new Set(['Apple' , 'Banana' , 'Orange' , 'Jack Fruit' ]); console.log(fruits.size); console.log(fruits.Apple); console.log(fruits.Banana); console.log(fruits.Orange); console.log(fruits['Jack Fruit' ]); console.log(fruits.Tomato);
Copyright © 2018, The Pragmatic Bookshelf.
..................Content has been hidden....................
You can't read the all page of ebook, please click
here login for view all page.