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:

  1. Class declaration - Use class keyword and follow with class name (TitleCase) (class Polygon {....})

  2. 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.

//TASK Answer
class Polygon{
     constructor(arr){
         this.arr = arr;
     }
     perimeter(){
         return this.arr.reduce((a,b) => a+b, 0) //Array.prototype.reduce can be used to iterate through the array, 
         //adding the current element value to the sum of the previous element values.
     }
 }

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

const array1 = [1, 2, 3, 4];
const reducer = (previousValue, currentValue) => previousValue + currentValue;    

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5)); // console.log(array1.reduce((a,b) => a+b, 0)    
// expected output: 15   // in this case 5 is the default value

Last updated