Code Issues Solver

Prototypal Inheritance Implementation in JavaScript

This project implements a prototypal inheritance structure in JavaScript with three classes: Activity, Payment, and Refund. Each class has defined methods for managing amounts and associated properties, demonstrating robust inheritance


Empty image or helper icon

Prompt

The goal of this problem is to use prototypal inheritance in Javascript.

 

Implement inheritance as described below-

 

Create a function Activity that takes a single parameter amount (Number) and assigns it to member variable 'amount'.

Add the following functions to the Activity prototype -

  1. setAmount - This function takes a single parameter , value.
    • If the value is less than or equal to 0, it returns false.
    • Otherwise, it assigns value to the member variable amount and returns true.
  2. getAmount - This function returns the member variable amount value.

 

Create a function Payment that -

  1. inherits from parent Activity.
  2. takes 2 parameters - amount (Number) and receiver (string).  It  assigns the parent's member variable 'amount', and self's member variable 'receiver' respectively. 

Add the following functions to Payment's existing prototype -

  1. setReceiver - This function takes a single parameter and assigns it to the member variable 'receiver'.
  2. getReceiver - This function returns the member variable 'receiver' value.

 

Create a function Refund that -

  1. inherits from parent Activity.
  2. takes 2 parameters - amount (Number) and sender (string) and assigns the parent's member variable, 'amount', and self's member variable, 'sender'. 

Add below functions to Refund's existing prototype -

  1. setSender - This function takes a single parameter and assigns it to the member variable sender.
  2. getSender - This function returns the member variable sender.

 

Implementation of the function will be tested by the provided code stub using several input files. Each input file contains parameters for the function calls. The result of their executions will be printed to the standard output by the provided code. In the case of a setAmount function call, if the value returned is false, the stubbed code prints 'Amount not updated'. If the value returned is true, it prints 'Amount updates to <value>'.

Input Format For Custom Testing

The first line specifies the function name for which object needs to be created i.e. either Payment or Refund.

The second line contains space-separated initial amount and receiver/sender values for initial object creation.

The third line contains an integer to update the amount.

The fourth line contains a string to update the receiver/sender value of the object.

Sample Case 0

Sample Input For Custom Testing

STDIN        Function
-----        --------
Payment    rarr    object to create = Payment
5000 John    rarr    initial amount = 5000, initial receiver = 'John'
4000        rarr    update amount to 4000
John B    rarr    update receiver to 'John B'

Sample Output

Payment object created with amount 5000 and receiver John
Amount updated to 4000
Receiver updated to John B
Payment object details - amount is 4000 and receiver is John B
Payment.prototype has property setAmount: false
Payment.prototype has property getAmount: false
Payment.prototype has property setReceiver: true
Payment.prototype has property getReceiver: true

Explanation

A Payment object is created with the amount as 5000 and receiver as 'John' (inputs from the second line). The third and fourth lines have updated amount and receiver values that are used to update the object's member variables using setAmount and setReceiver functions. Since setAmount returns true in this case, it prints 'Amount updated to 4000'. The stub code then calls the getAmount and getReceiver functions and prints the values. The last 4 lines check if the object prototype chain is built correctly.

Sample Case 1

Sample Input For Custom Testing

Refund
5000 John
4000
John B

Sample Output

Refund object created with amount 5000 and sender John
Amount updated to 4000
Sender updated to John B
Refund object details - amount is 4000 and sender is John B
Refund.prototype has property setAmount: false
Refund.prototype has property getAmount: false
Refund.prototype has property setSender: true
Refund.prototype has property getSender: true

Explanation

A Refund object is created with the amount as 5000 and sender as 'John' (inputs from the second line). The third and fourth lines have updated amount and sender values that are used to update the object's member variables using setAmount and setSender functions. Since setAmount returns true in this case, it prints 'Amount updated to 4000'. The stub code then calls getAmount and getSender functions and prints the values. The last 4 lines check if the object prototype chain is built correctly.

Answer

Prototypal Inheritance in JavaScript

Problem Analysis

The objective is to implement a prototypal inheritance structure in JavaScript involving three functions: Activity, Payment, and Refund. Each of these functions has specific parameters and behaviors that need to be defined.

Classes Overview

  1. Activity: Base class that initializes with an amount.

    • Prototype Methods:
      • setAmount(value): Sets the amount if valid.
      • getAmount(): Returns the current amount.
  2. Payment: Inherits from Activity, initializes with amount and receiver.

    • Prototype Methods:
      • setReceiver(value): Sets the receiver's name.
      • getReceiver(): Returns the receiver's name.
  3. Refund: Inherits from Activity, initializes with amount and sender.

    • Prototype Methods:
      • setSender(value): Sets the sender's name.
      • getSender(): Returns the sender's name.

Implementation Steps

  1. Define the Activity function and its methods.
  2. Define Payment and Refund functions, ensuring they inherit from Activity.
  3. Add specific prototypes for Payment and Refund.
  4. Test the structure with sample inputs.

Complete Code Implementation

// Define the Activity constructor
function Activity(amount) {
    this.amount = amount; // Initial amount assignment
}

// Add setAmount method to Activity's prototype
Activity.prototype.setAmount = function(value) {
    if (value <= 0) {
        return false;  // Reject invalid amount
    }
    this.amount = value; // Set the valid amount
    return true;  // Indicate success
};

// Add getAmount method to Activity's prototype
Activity.prototype.getAmount = function() {
    return this.amount; // Return current amount
};

// Define the Payment constructor
function Payment(amount, receiver) {
    Activity.call(this, amount); // Call parent constructor
    this.receiver = receiver; // Initialize receiver
}

// Inherit from Activity
Payment.prototype = Object.create(Activity.prototype);
Payment.prototype.constructor = Payment;

// Add setReceiver method to Payment's prototype
Payment.prototype.setReceiver = function(value) {
    this.receiver = value; // Assign new receiver
};

// Add getReceiver method to Payment's prototype
Payment.prototype.getReceiver = function() {
    return this.receiver; // Return current receiver
};

// Define the Refund constructor
function Refund(amount, sender) {
    Activity.call(this, amount); // Call parent constructor
    this.sender = sender; // Initialize sender
}

// Inherit from Activity
Refund.prototype = Object.create(Activity.prototype);
Refund.prototype.constructor = Refund;

// Add setSender method to Refund's prototype
Refund.prototype.setSender = function(value) {
    this.sender = value; // Assign new sender
};

// Add getSender method to Refund's prototype
Refund.prototype.getSender = function() {
    return this.sender; // Return current sender
};

// Example Usage
let payment = new Payment(5000, "John");
console.log(`Payment object created with amount ${payment.getAmount()} and receiver ${payment.getReceiver()}`);

let isAmountUpdated = payment.setAmount(4000);
console.log(isAmountUpdated ? `Amount updated to ${payment.getAmount()}` : 'Amount not updated');

payment.setReceiver("John B");
console.log(`Receiver updated to ${payment.getReceiver()}`);

// Check properties
console.log(`Payment.prototype has property setAmount: ${Payment.prototype.setAmount !== undefined}`);
console.log(`Payment.prototype has property getAmount: ${Payment.prototype.getAmount !== undefined}`);
console.log(`Payment.prototype has property setReceiver: ${Payment.prototype.setReceiver !== undefined}`);
console.log(`Payment.prototype has property getReceiver: ${Payment.prototype.getReceiver !== undefined}`);

let refund = new Refund(5000, "John");
console.log(`Refund object created with amount ${refund.getAmount()} and sender ${refund.getSender()}`);

isAmountUpdated = refund.setAmount(4000);
console.log(isAmountUpdated ? `Amount updated to ${refund.getAmount()}` : 'Amount not updated');

refund.setSender("John B");
console.log(`Sender updated to ${refund.getSender()}`);

// Check properties for Refund
console.log(`Refund.prototype has property setAmount: ${Refund.prototype.setAmount !== undefined}`);
console.log(`Refund.prototype has property getAmount: ${Refund.prototype.getAmount !== undefined}`);
console.log(`Refund.prototype has property setSender: ${Refund.prototype.setSender !== undefined}`);
console.log(`Refund.prototype has property getSender: ${Refund.prototype.getSender !== undefined}`);

Code Explanation

  1. Activity Constructor:

    • Initializes with an amount.
    • Validates and sets a new amount through setAmount.
    • Retrieves the amount with getAmount.
  2. Payment Constructor:

    • Inherits from Activity.
    • Initializes with an additional receiver property.
    • Allows setting and getting of the receiver.
  3. Refund Constructor:

    • Also inherits from Activity.
    • Initializes with a sender property.
    • Allows setting and getting of the sender.

Conclusion

This implementation successfully demonstrates prototypal inheritance in JavaScript and adheres to the principles outlined in the problem statement. The methods are succinct, and the structure is flexible for future extensions or modifications.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This project implements a prototypal inheritance structure in JavaScript with three classes: Activity, Payment, and Refund. Each class has defined methods for managing amounts and associated properties, demonstrating robust inheritance and prototype method usage.