Chapter 11

Here are the solutions to the Exercises, for the Chapter 11, Exploring Metaprogramming chapter.

Exercise 1

 'use strict'​;
 
 const​ printProperties = ​function​(obj) {
 for​(​const​ property ​of​ Object.getOwnPropertyNames(obj)) {
  console.log(​`​${property}​ is ​${obj[property]}​`​);
  }
 };
 
 printProperties({language: ​'JavaScript'​, typing: ​'dynamic'​});
 printProperties(
  {tool: ​'Redux'​, language: ​'JavaScript'​, purpose: ​'transpiler'​, });

Exercise 2

 'use strict'​;
 
 Number.prototype.percent = ​function​() {
 if​(​this​ >= 1) {
 throw​ ​new​ Error(​'value should be less than 1'​);
  }
 
 return​ ​`​${​this​ * 100}​%`​;
 };
 
 const​ value1 = 0.35;
 const​ value2 = 0.91;
 
 console.log(value1.percent()); ​//35%
 console.log(value2.percent()); ​//91%
 
 try​ {
 const​ value3 = 44;
  console.log(value3.percent());
 } ​catch​(ex) {
  console.log(ex.message); ​// value should be less than 1
 }

Exercise 3

 'use strict'​;
 
 Object.defineProperties(Number.prototype, {
  integerPart: {
  get: ​function​() {
 return​ ​this​.toString().split(​'.'​)[0];
  }
  },
  fractionalPart: {
  get: ​function​() { ​return​ ​this​.toString().split(​'.'​)[1] || 0; }
  }
 });
 
 
 const​ printParts = ​function​(number) {
  console.log(
 `whole: ​${number.integerPart}​ decimal: ​${number.fractionalPart}​`​);
 };
 
 printParts(22.12); ​//whole: 22 decimal: 12
 printParts(.14); ​//whole: 0 decimal: 14
 printParts(-23.19); ​//whole: -23 decimal: 19
 printParts(42); ​//whole: 42 decimal: 0

Exercise 4

 'use strict'​;
 
 Set.prototype.combine = ​function​(otherSet) {
 const​ copyOfSet = ​new​ Set(​this​);
 
 for​(​const​ element ​of​ otherSet) {
  copyOfSet.add(element);
  }
 
 return​ copyOfSet;
 };
 
 const​ names1 = ​new​ Set([​'Tom'​, ​'Sara'​, ​'Brad'​, ​'Kim'​]);
 const​ names2 = ​new​ Set([​'Mike'​, ​'Kate'​]);
 
 const​ combinedNames = names1.combine(names2);
 
 console.log(names1.size);
 console.log(names2.size);
 console.log(combinedNames.size);
 console.log(combinedNames);

Exercise 5

instance.methodName = function... instead of ClassName.prototype.methodName = function....

Adding a method to an instance instead of to the class’s prototype has a few benefits:

  • It’s less intrusive and less risky.
  • You can limit the scope of your change.
  • You avoid the risk of replacing an existing method.
  • It’s useful to create a test double when doing automated testing—replace the method with a stub or a mock to facilitate ease of testing a function that depends on the function that was replaced.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset