Wednesday, August 14, 2024

Addition and Subtraction of Two Numbers Using Polymorphism in JavaScript

 


Program Listing

const readline = require('readline');

class MathOperation {
    performOperation(a, b) {
        return 0; // Base class default implementation
    }
}

class Addition extends MathOperation {
    performOperation(a, b) {
        return a + b;
    }
}

class Subtraction extends MathOperation {
    performOperation(a, b) {
        return a - b;
    }
}

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question("\n\tEnter the first number: ", (num1) => {
    rl.question("\tEnter the second number: ", (num2) => {
        rl.question("\tEnter the operation (+ for addition, - for subtraction): ", (op) => {
            let operation;

            if (op === '+') {
                operation = new Addition();
            } else if (op === '-') {
                operation = new Subtraction();
            } else {
                console.log("\tInvalid operation.");
                rl.close();
                process.exit();
            }

            const result = operation.performOperation(parseInt(num1), parseInt(num2));
            console.log("\n\tThe Result:", result);

            rl.close();
            console.log("\n\tEnd of Program. Thank you for using this program.\n");
        });
    });
});

No comments:

Post a Comment