Chapter 6

Here are the solutions to the Exercises, for the Chapter 6, Literals and Destructuring chapter.

Exercise 1

 'use strict'​;
 
 const​ greet = ​function​(name, gender) {
 return​ ​`Hello, ​${gender === Symbol.​for​(​'female'​) ? ​'Ms.'​ : ​'Mr.'​}​ ​${name}​`​;
 };
 
 console.log(greet(​'Sara'​, Symbol.​for​(​'female'​))); ​//Hello, Ms. Sara
 console.log(greet(​'Tom'​, Symbol.​for​(​'male'​))); ​//Hello, Mr. Tom

Exercise 2

 'use strict'​;
 
 const​ stripMargin = ​function​(texts, ...expressions) {
 const​ exceptLast = expressions.map(​function​(expression, index) {
 return​ ​`​${texts[index]}${expression.toString().toUpperCase()}​`​;
  }).join(​''​);
 
 const​ result = ​`​${exceptLast}${texts[texts.length - 1]}​`​;
 
 return​ result.replace(​/​​[ ][ s]​​+​​(w)​​/g​, ​' $1'​).trim();
 };
 
 const​ name = ​'Jane'​;
 
 const​ processed = stripMargin​` This is for
  ​${name}​ and it needs to be
  delivered by December 24th.`​;
 
 
 console.log(processed);
 //This is for JANE and it needs to be delivered by December 24th.

Exercise 3

 'use strict'​;
 
 const​ beforeAndAfter = ​function​(number) {
 if​(number < 0) ​return​ [];
 if​(number === 0) ​return​ [1];
 
 return​ [number - 1, number + 1];
 };
 
 let​ before = 0;
 let​ after = 0;
 
 //Your code goes before =
 [before, after] = beforeAndAfter(7);
 console.log(​`​${before}​ and ​${after}​`​); ​//6 and 8
 
 [before, after] = beforeAndAfter(9);
 console.log(​`​${before}​ and ​${after}​`​); ​//8 and 10
 
 [before, after = 0] = beforeAndAfter(0);
 console.log(​`​${before}​ and ​${after}​`​); ​//0 and 1
 
 [before = 0, after = 0] = beforeAndAfter(-1);
 console.log(​`​${before}​ and ​${after}​`​); ​//0 and 0

Exercise 4

 'use strict'​;
 
 const​ purchaseItems = ​function​(essential1, essential2, ...optionals) {
  console.log(​`​${essential1}​, ​${essential2}​, ​${optionals.join(​', '​)}​`​);
 };
 
 const​ mustHaves = [​'bread'​, ​'milk'​];
 const​ also = [​'eggs'​, ​'donuts'​];
 const​ andAlso = [​'juice'​, ​'tea'​];
 
 //call purchaseItems so it prints
 //bread, milk, eggs, donuts, coffee, juice, tea
 purchaseItems(...mustHaves, ...[...also, ​'coffee'​, ...andAlso]);

Exercise 5

 'use strict'​;
 
 const​ getDetails = ​function​(
  {name, born: { year: birthYear }, graduated: {year}}) {
 return​ ​`​${name}​ born in the year ​${birthYear}​, graduated in ​${year}​.`​;
 };
 
 const​ details =
  getDetails({name: ​'Sara'​,
  born: { month: 1, day: 1, year: 2000 },
  graduated: { month: 5, day: 31, year: 2018 }});
 console.log(details);
 //Sara born in the year 2000, graduated in 2018.
..................Content has been hidden....................

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