Ways to set up an object's attributes or properties upon its creation through a method within a class

In my JavaScript code, I have a class called Bank that has a method "addBranch" which adds a Branch object to an array of branches. My goal is to set up a custom attribute "customers" for each Branch object as it gets added to the array.

Below is a simplified snippet 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
  }

  // Method to add branch
  addBranch(branch) {
    // Check if branch already exists
    if (this.#branches.includes(branch)) return false

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

I attempted to use "branch.customers = []" but encountered this error:

TypeError: Cannot create property 'customers' on string 'Branch1'. at Bank.addBranch (C:\Users\npdkh\Desktop\Integrify\fs17-week2-TS\src\bank.js:25:22). at Object. (C:\Users\npdkh\Desktop\Integrify\fs17-week2-TS\src\bank.js:85:6).

Node.js v18.17.1

Answer №1

Consider introducing an abstraction for the Branch and possibly even for the Customer. However, it is not mandatory to take that approach. The decision depends on when one wants to handle all the object states involved. An alternative could be passing simple object types with unprotected properties.

By opting for another abstraction, the original task of adding a customers property to the branch value/object can be alleviated.

It is also important to reconsider how comparisons between added branches and customers are conducted. The example code provided below only compares the name properties for similarity, which might be considered a limited form of comparison. This method can be extended based on requirements.

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; }

Answer №2

let newBranch = new Branch('Primary Branch'); let myBank = new Bank('Best Bank');

myBank.addBranch(newBranch); console.log(newBranch.customers); // prints: []

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the proper way to implement React's Link component from an external npm package to avoid the error message stating, "you should not use link outside router"?

A custom NPM package has been developed to display an icon menu that can be used across multiple projects. Users have the flexibility to provide a 'route' prop to each icon, allowing them to act as links to different pages. Despite importing and ...

Dealing with the Back Button Problem in History API and History.js

Using Ajax to load the page presents a challenge when the user clicks the back button. Here is the scenario: Initial page (index.php) is loaded User clicks on a link The new page loads successfully via Ajax User clicks the back button The initial page is ...

Issue with data set

$modules = array( 'home' => 'home', 'login' => 'login', 'forum' => 'forum', 'topic' => 't ...

What is the best way to invoke a single ajax function across multiple pages with varying URLs?

Hello everyone! I am attempting to streamline my ajax post function and use it across the entire site with different URLs on each page. Below is my original function and how it currently operates: <button type="button" class="submit" ...

the sequence of events in a web setting

Can you explain the sequence of execution in a web application? The order typically involves PHP, HTML, JavaScript, CSS, and MySQL being executed. ...

Obtaining a value from HTML and passing it to another component in Angular

I am facing an issue where I am trying to send a value from a web service to another component. The problem is that the value appears empty in the other component, even though I can see that the value is present when I use console.log() in the current comp ...

What is the best way to implement a scroll to top/bottom button globally in Vue?

I have created a scroll-to-top and scroll-to-bottom button for my application. However, I want to make these buttons accessible globally throughout the app without having to repeat the code in every page where the component is needed. Currently, I am inclu ...

Updating ng-init in AngularJS triggered by a changeOR Changing

Is there a way for ng-init to be updated when the tableCells change? I'm looking for a method that will avoid angular from calling findCellsByDate twice. I've also attempted changing ng-init to ng-bind or ng-model, but ng-bind displays [object O ...

Is there a way to smoothly navigate back to the top of the page after the fragment identifier causes the page to scroll down?

I do not want to disable the functionality of the fragment identifier. My goal is for the page to automatically scroll back to the top after navigating to a specific section. This inquiry pertains to utilizing jQuery's UI tabs. It is crucial to have ...

Using pointer arrays of characters in the C programming language

I am attempting to create a multi-dimensional array of strings, where each index in the main array holds another array of strings. char Example[0] = { "array", "of", "strings"} Example[1] = { "array", "of", "strings2"} Example[...] = { ... } I have consi ...

The URL being called by $http.get is incorrect

Attempting to invoke a URL through my AngularJS service, I have encountered an issue where a particular call is not reaching the intended URL. The following code snippet depicts the function responsible for making the call, along with a console.log statem ...

Should the index.js file in Next.js serve as the homepage or solely as the initial starting point?

Should I integrate my homepage directly into the index.js file, or create a separate "home-page.js" file in the pages directory? Is index.js just for initializing the application, or can it serve as a standalone page? Alternatively, should I have index.j ...

Having trouble with charts not appearing on your Django website?

I am working on a Django project where I need to integrate bar-charts using Django-nvd3. Although I have successfully displayed the bar-charts in separate projects, I am facing an issue with integrating them into my current project. Below is the code snipp ...

I aimed to find the first day of the month, but my calculation led me to the last day instead

To begin, I retrieve the date for the first day of the month: var currentDate = new Date(); var beginningOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1); Next, I convert this date to ISO format: beginningOfMonth = beginningOfMon ...

Utilizing useRef with React Three in App component results in null value for threejs entities

I'm encountering an issue with ref values while developing my threejs app in react. Typically, when we use useRef on any element, it returns the exact object after the first render. However, when working with threejs objects such as mesh or perspectiv ...

Sending a list via Ajax in Django

I recently executed an Ajax call successfully: $.ajax({ url:'/quespaper/intermediate_table', type:'GET', processData: false, data:{'url_link':url_link_copy,'updated ...

Transforming Image Annotation from Angular 1 to Angular 4: Overcoming Conversion Challenges and Comparing Equivalents from 1.x to 4

After exploring various options, I am still struggling to resolve the conversion error that occurs when trying to convert my Angular 1.x script for image annotation into Angular 4. The equivalent of angular 1.x code in Angular 4 is not readily available. H ...

React not displaying wrapped div

I am facing an issue with my render() function where the outer div is not rendering, but the inner ReactComponent is displaying. Here is a snippet of my code: return( <div style={{background: "black"}}> <[ReactComponent]> ...

Working with a character array as the file name in C using the fopen() function

I am currently developing a C program that allows users to input a file name for the program to read. The input format required is "/i:", which means I need to remove the first three characters to extract the actual file name. To store the file name, I am ...

Discovering the technique to dynamically load various content using jQuery in a div based on its

After discovering this code to extract information from the first div with an id of container (box4) and retrieve any new data from the URL, everything was functioning correctly. However, I encountered an issue when attempting to load box5 and rerun the co ...