Revamp a function designed to calculate complimentary items

Recently, I've been working on a method that calculates the total number of freebies based on an array of items. While the current implementation gets the job done, it seems like there is a fair amount of redundant code present. I'm looking for suggestions on how to clean up and refactor this code for better efficiency. Thoughts?

freebieCalculator(orders) {
  const freeItemAmount = [];
  const totalAmount = [];
  for (const order of orders) {

   const items = Math.floor(order.cash / order.price);
   const freebies = Math.floor(items / order.bonus_ratio);

   if (order.type === 'foo') {
       const bar = 0;
       const boo = 0;
       let foo = 0;
       foo = (foo + 1) * freebies;
       freeItemAmount.push({'\"foo\"': foo, '\"bar\"': bar, '\"boo\"' : boo});
       totalAmount.push({'\"foo\"': foo + items, '\"bar\"': bar, '\"boo\"' : boo});
      } else if (order.type === 'bar') {
         const foo = 0;
         const boo = 0;
         let bar = 0;
         bar = (bar + 2) * freebies;
         freeItemAmount.push({'\"foo\"': foo, '\"bar\"': bar, '\"boo\"' : boo});
         totalAmount.push({'\"foo\"': foo, '\"bar\"': bar + items, '\"boo\"' : boo});
        } else if (order.type === 'boo') {
         const bar = 0;
         let foo = 0;
         let boo = 0;
         foo = (foo + 1) *  freebies;
         boo = (boo + 1) *  freebies;
         freeItemAmount.push({'\"foo\"': foo, '\"bar\"': bar, '\"boo\"' : boo});
         totalAmount.push({'\"foo\"': foo, '\"bar\"': bar, '\"boo\"' : boo + items});
        }
  }
  return totalAmount;

}

Answer №1

Develop private functions to calculate the foo and boo variables. Here is an example:

let foo = calculatePrice(freebies);
let boo = calculatePrice(freebies);

Create objects (JSON)...

freeItemAmount.push(createItem(foo, bar, boo));

If bar and boo always have the same value, define them as constants (in uppercase)

freeItemAmount.push(createItem(foo, CONSTANT_BAR, CONSTANT_BOO));

etc...

When reviewing code written by someone else, it's often not necessary to understand all the technical details. Focus on understanding the business logic. For example:

for (const order of orders) {
    if (isFooProduct(order)) {
        freeItemAmount.put(createItem(...));
        totalAmount.put(createItem(...));
    else if (isBarProduct(order)) {
        ....
    }
    .....
}

Answer №2

Make sure to declare the variables only once, rather than repeating them for each order type.

Add items to the freeItemAmount array after the if statements for all three order types since the process is the same.

If you assign items directly to the variables, you can also push them to the totalAmount array in a similar manner.

    for (const order of orders) {
        const items = Math.floor(order.cash / order.price);
        const freebies = Math.floor(items / order.bonus_ratio);
        let bar = 0;
        let boo = 0;
        let foo = 0;

        if (order.type === 'foo') {
            foo = ((foo + 1) * freebies) + items;
        } else if (order.type === 'bar') {
            bar = ((bar + 2) * freebies) + items;
        } else if (order.type === 'boo') {
            foo = (foo + 1) * freebies;
            boo = ((boo + 1) * freebies) + items;
        }

        freeItemAmount.push({'\"foo\"': foo, '\"bar\"': bar, '\"boo\"' : boo});
        totalAmount.push({'\"foo\"': foo, '\"bar\"': bar, '\"boo\"' : boo});
    }

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

Retrieving the main color specified in the custom theme within the component's SCSS file

After creating a custom theme in Angular 4, I am trying to use it in one of my component's SCSS file. Specifically, I want the background of a particular mat-grid-tile to reflect the primary color of the theme. Here is my custom theme: @import &apo ...

Is there a way to easily toggle a Material Checkbox in Angular with just one click?

Issue with Checkbox Functionality: In a Material Dialog Component, I have implemented several Material Checkboxes to serve as column filters for a table: <h1 mat-dialog-title>Filter</h1> <div mat-dialog-content> <ng-container *ng ...

Bypass Auth0 HttpInterceptor based on certain conditions

During the transition from Firebase to Auth0, my Angular front-end application authenticates users to either Firebase or Auth0 based on their email address. I am working on configuring the Auth0 AuthHttpInterceptor provided in the Auth0 Angular SDK for SPA ...

Utilize Angular to input data into a CRUD table and enhance its value

While working on a CRUD table today, I encountered several errors that are too numerous to mention in the title of the question. Please forgive this oversight. Despite being a simple table and not an Angular material table, I am struggling with debugging i ...

The [image link] in the NextJS image was loaded in advance using link preload, but it was not utilized within a short time after the window finished loading

While working on my blog website with NextJS, I encountered a warning in the console related to using next/image: The resource http://localhost:3000/_next/image... was preloaded using link preload but not used within a few seconds from the window's lo ...

Issue with MSAL v2 Angular in Microsoft Teams Desktop Application

We are currently experiencing an AAD login issue with our web application (built using node.js + angular 10) specifically in MS Teams Desktop & Mobile app. Interestingly, users are able to easily login by simply clicking a login button in any web browser o ...

Retrieve all properties associated with the current instance in the Angular 2 controller

I am looking to assign class variables with values from session storage if they exist, otherwise the variable will retain its default value initialized in ngOnInit. private getTableSessionItems = () => { var tSession = JSON.parse(sessionStorage.g ...

Tips for obtaining an Instance of a Mat-Table when there are multiple tables within the component

Encountering an issue where I have a component in Angular 6 generating multiple Mat-Tables with Data. Using the ng-for loop to iterate through all the Mat-Table Data sources within a div tag. However, when trying to add a new row to a table, unable to iden ...

Verify if the array entries match

Within my select element, I populate options based on an array of values. For example: [{ name: 'A', type: 'a', }, { name: 'B', type: 'b', }, { name: 'B', type: 'b', }, { name: &apos ...

Nestjs: Accessing the request or context using a Decorator

In my current project using NestJS, I am attempting to make the executionContext accessible in a logger for the purpose of filtering logs by request. Each injectable has its own instance of a logger, and I want to maintain this setup (where the scope of t ...

What could be the reason for the unexpected behavior of comparing an environment variable with undefined in Jest?

During the process of creating Jest tests to validate the existence of a required environment variable, I encountered unexpected behavior while comparing the variable to undefined. The @types/node documentation implies that each environment variable is eit ...

Angular asynchronous testing with Observable using karma

I am currently working on testing an asynchronous scenario. Here is a snippet of my component: ngOnInit(private service: MyService) { this.isLoading = true; this.service.getData().subscribe((data) => { this.data = data; this.isLoa ...

Encountering the error "No exported member 'RouteComponentProps' in the 'react-router-dom' module while upgrading to react-router v6"

We are currently in the process of migrating legacy class-based code to the latest version 6 of react router. However, we are encountering the following error during the migration: Module '"react-router-dom"' has no exported member &a ...

How to effectively eliminate the border of a single cell within a Bootstrap Table

Is there a way to remove the border of a single cell in a bootstrap table without affecting the others? I attempted using an id on that specific cell and adding the following CSS code: #borderless-cell { border: 0; } Unfortunately, this solution doesn&ap ...

The use of window.Image() is ineffective when working with TypeScript and React

In my React project, I am utilizing the KonvaJS library. You can find more information about it here. To display an image using JavaScript/React, I have implemented the following code: componentDidMount() { const image = new window.Image(); ima ...

What could be the reason behind Angular2 TestBed's compileComponents failing to locate my templates?

My current project includes a component that I'll refer to as MyComponent. This particular component utilizes my.component.html as its templateUrl. @Component({ selector: "my-component", templateUrl: "./my.component.html", styleUrls: ["./my.com ...

Sending JSON object data to an API endpoint using the POST method in an Angular application

Attempted to post data to an API, but received a 400 bad request error. After testing with Postman, it seems that the issue may lie within my service or TypeScript code. As a newcomer to Angular, I am seeking assistance as I have searched extensively witho ...

Building NextJS with Typescript encountered an error while using @auth0/nextjs-auth0

I am currently facing an issue while trying to build my NextJS application using Typescript. The problem lies with the auth0/nextjs-auth0 package, causing persistent errors during installation. One specific error can be found at the following link: https: ...

Save the reference URL of an image in Firestore by uploading the image

Here is my StackBlitz link for reference: https://stackblitz.com/edit/upload-image-ref-firestore?embed=1&file=src/app/ app.component.html I am currently utilizing AngularFire2 to upload images and I am curious about how I can store the reference of th ...

Tips for effectively generating a JSON object array in Typescript

Currently, I'm attempting to construct an array of JSON objects using TypeScript. Here is my current method: const queryMutations: any = _.uniq(_.map(mutationData.result, function (mutation: Mutation) { if (mutation && mutation.gene) { co ...