Day 5: Template Literals (10 Days of Javascript)

Task:

The code in the editor has a tagged template literal that passes the area and perimeter of a rectangle to a tag function named sides. Recall that the first argument of a tag function is an array of string literals from the template, and the subsequent values are the template’s respective expression values.

Complete the function in the editor so that it does the following:

s = (P +-sqrt(P*P-16*A))/4

  1. Finds the initial values of s1 and s2 by plugging the area and perimeter values into the formula: where A is the rectangle’s area and P is its perimeter.
  2. Creates an array consisting of s1 and s2 and sorts it in ascending order.
  3. Returns the sorted array.


Solution :

 /* Determine the original side lengths and return an array:
 * - The first element is the length of the shorter side
 * - The second element is the length of the longer side
 * 
 * Parameter(s):
 * literals: The tagged template literal's array of strings.
 * expressions: The tagged template literal's array of expression values (i.e., [area, perimeter]).
 */
function sides(literals, ...expressions) {
   let s1=Math.floor((expressions[1]+Math.sqrt((expressions[1]*expressions[1]-(16*expressions[0]))))/4);
   let s2=Math.floor((expressions[1]-Math.sqrt((expressions[1]*expressions[1]-(16*expressions[0]))))/4);
   let arr=[s1,s2].sort();
   return arr;
}

Leave a Reply