10 Days Of JavaScript

Day 4: Classes Solution

Hello Friends in this article i am gone to share Hackerrank 10 days of javascript solutions with you. | Day 4: Classes Solution.


Also visit this link:ย  Day 4: Count Objects Solution


 

Day 4: Classes Solution

Objective

In this challenge, we practice using JavaScript classes.

Task

Create aย Polygonย class that has the following properties:

  • Aย constructorย that takes an array of integer values describing the lengths of the polygonโ€™s sides.
  • Aย perimeter()ย method that returns the polygonโ€™s perimeter.

Locked code in the editor tests the Polygon constructor and theย perimeterย method.

Note:ย Theย perimeterย method must be lowercase and spelled correctly.

Input Format

There is no input for this challenge.

Output Format

Theย perimeterย method must return the polygonโ€™s perimeter using the side length array passed to the constructor.

Explanation

Consider the following code:

// Create a polygon with side lengths 3, 4, and 5
let triangle = new Polygon([3, 4, 5]);

// Print the perimeter
console.log(triangle.perimeter());

When executed with a properly implementedย Polygonย class, this code should print the result ofย 3 + 4 + 5 = 12.

 

Solution โ€“ Day 4: Classes


/*
ย *ย Implementย aย Polygonย classย withย theย followingย properties:
ย *ย 1.ย Aย constructorย thatย takesย anย arrayย ofย integerย sideย lengths.
ย *ย 2.ย Aย 'perimeter'ย methodย thatย returnsย theย sumย ofย theย Polygon'sย sideย lengths.
ย */
classย Polygonย {

ย ย ย ย constructor(sides)ย {
ย ย ย ย ย ย ย ย this.sidesย =ย sides
ย ย ย ย }
ย ย ย ย perimeter()ย {
ย ย ย ย ย ย ย ย returnย this.sides.reduce(functionย add(a,ย b)ย {ย returnย aย +ย b;ย })
ย ย ย ย }
}


constย rectangleย =ย newย Polygon([10,ย 20,ย 10,ย 20]);
constย squareย =ย newย Polygon([10,ย 10,ย 10,ย 10]);
constย pentagonย =ย newย Polygon([10,ย 20,ย 30,ย 40,ย 43]);

console.log(rectangle.perimeter());
console.log(square.perimeter());
console.log(pentagon.perimeter());

Complete the function in the editor. It has two parameters: a and b. It must return an object modeling a rectangle that has the following properties: Complete the function in the editor. It has two parameters:ย aย andย b. It must return an object modeling a rectangle that has the following properties: