skip to Main Content

I have a JavaScript class Bank with a method "addBranch" that adds a Branch object to an array of branches. I want to initialize a custom attribute "customers" for each Branch object when it is added to the array.

Here is a simplified version of the code:

class Bank {
  #name
  #branches
  constructor(name) {
    this.#name = name
    this.#branches = []
  }

  // name getter
  get name() {
    return this.#name
  }

  // branches getter
  get branches() {
    return this.#branches
  }

  // adding branch method
  addBranch(branch) {
    // check if branch is already existed
    if (this.#branches.includes(branch)) return false

    // Initialize customers attribute for the new branch
    branch.customers = []
    this.#branches.push(branch)
    console.log(`Push new branch: ${branch}`)
    return true
  }

I have tried to use "branch.customers = []" but it doesn’t work for me

TypeError: Cannot create property ‘customers’ on string ‘Branch1’
at Bank.addBranch (C:UsersnpdkhDesktopIntegrifyfs17-week2-TSsrcbank.js:25:22)
at Object. (C:UsersnpdkhDesktopIntegrifyfs17-week2-TSsrcbank.js:85:6)
at Module._compile (node:internal/modules/cjs/loader:1256:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
at Module.load (node:internal/modules/cjs/loader:1119:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47

Node.js v18.17.1

2

Answers


  1. const myBranch = new Branch(‘Main Branch’);
    const myBank = new Bank(‘My Bank’);

    myBank.addBranch(myBranch);
    console.log(myBranch.customers); // outputs :[]

    Login or Signup to reply.
  2. The OP might think about implementing an abstraction for Branch as well, maybe even for Customer. But one does not necessarily need to go that path. It is all about at which point one wants to manage all of the involved object states. Depending on that one could also go with an approach that just passes simple object types with unprotected properties around.

    Going with another abstraction will also free the OP from the original task, which was adding a customers property to the passed branch value/object.

    In addition one needs to rethink of how one wants to check the sameness of to be added branch and customer items/objects. The next provided example code does implement a checking exclusively on such items’ name properties which might be a weak sameness comparison, but one could extend this comparison approach as needed.

    class Branch {
      #name;
      #customers = [];
    
      constructor(name) {
        this.#name = name;
      }
    
      get name() {
        return this.#name;
      }
      get customers() {
        return this.#customers.map(customer => customer.valueOf());
      }
      valueOf() {
        return {
          name: this.name,
          customers: this.customers,
        };
      }
    
      addCustomer(customer) {
        let success = false;
    
        const customerName = customer.name;
        const match = this.#customers.find(({ name }) => name === customerName);
    
        if (!match) {
          success = true;
    
          this.#customers.push(customer);
    
          console.log('... newly added customer ...', customer.valueOf());
        }
        return success;
      }
    }
    
    class Bank {
      #name;
      #branches = [];
    
      constructor(name) {
        this.#name = name;
      }
    
      get name() {
        return this.#name;
      }
      get branches() {
        return this.#branches.map(branch => branch.valueOf());
      }
      valueOf() {
        return {
          name: this.name,
          branches: this.branches,
        };
      }
    
      addBranch(branch) {
        let success = false;
    
        const branchName = branch.name;
        const match = this.#branches.find(({ name }) => name === branchName);
    
        if (!match) {
          success = true;
    
          this.#branches.push(branch);
    
          console.log('... newly added branch ...', branch.valueOf());
        }
        return success;
      }
    }
    
    const bank = new Bank('A Bank');
    
    console.log({
      bank: bank.valueOf(),
    });
    bank.addBranch(new Branch('A Branch'));
    
    console.log({
      bank: bank.valueOf(),
    });
    .as-console-wrapper { min-height: 100%!important; top: 0; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search