Day 4 : Classes
Theory
This syntax is a means of more simply and clearly creating objects and deal with inheritance. There are 2 ways to define classes:
Class declaration - Use
classkeyword and follow with class name (TitleCase) (class Polygon {....})Class Expression - only difference is " let Polygon = class ... "
A class can only have one constructor (special method)
// 1. Class Declaration
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
let p = new Polygon(1, 2);
console.log('Polygon p:', p);
// 2. Class Expression ( can be named or unnamed)
let Polygon = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
// Named expression
let Polygon = class Polygon { // the name is right after " class" keyword
constructor(height, width) {
this.height = height;
this.width = width;
}
};
// 3. Constructors
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
getArea() {
return this.height * this.width;
}
}
const square = new Polygon(10, 10);
console.log(square.getArea());https://www.hackerrank.com/challenges/js10-class/topics
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.
We also learnt to use .reduce method
The reduce() method executes a user-supplied “reducer” callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value
Last updated