Attempting to grasp the concept of incorporating functional mixins

Here's my calculator function:

var MyCalculator = function(c, d) { 
  this.addition = function(c, d) { return c + d; }; 
  this.multiply = function(c, d) { return d * c; }; 
  this.subtraction = function(c, d) { return c - d; }; 
  this.division = function(c, d) { 
    if (c/d === Infinity) {
      return Infinity - Infinity; 
    } else return c/d; 
  }; 
};

I'm looking to create a functional mixin for 'total' (MyCalculator.total) so that when given values "1,2,3,4", it would output 10 without becoming part of the Calculator property.

Can someone provide instructions on achieving this?

Answer №1

Suppose you're discussing the concept of the functional mixin pattern as detailed in a post available here:

const withSum = (object) => {
  return Object.assign({}, object, {
    sum(...args) {
      return args.reduce((sum, number) => sum + number, 0);
    }
  });
};

var Calculator = function(a, b) { 
  this.add = function(a, b) { return a + b; }; 
  this.multiply = function(a, b) { return b * a; }; 
  this.subtract = function(a, b) { return a - b; }; 
  this.divide = function(a, b) { 
    if (a/b === Infinity) {
      return Infinity - Infinity; 
    } else return a/b; 
  }; 
};

var calculator = withSum(new Calculator(1, 2));

console.log('calculator.add(1, 2):', calculator.add(1, 2));
console.log('calculator.multiply(1, 2):', calculator.multiply(1, 2));
console.log('calculator.subtract(2, 1):', calculator.subtract(2, 1));
console.log('calculator.divide(1, 2):', calculator.divide(1, 2));
console.log('calculator.sum(1, 2, 3, 4): ', calculator.sum(1, 2, 3, 4));

Keep in mind that for the Calculator.divide method to return NaN when a/b === Infinity, simply use return NaN; instead of Infinity - Infinity (NaN being a global constant).

Furthermore, you can remove the formal parameter list within the Calculator constructor: function Calculator() {...} is enough since a, b are not utilized.

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

Difficulty with two-dimensional arrays in Angular and Typescript

I am currently stuck trying to assign values to a 2-dimensional object array in Angular/Typescript. I have noticed that the last assignment seems to override the previous ones, but I cannot pinpoint why this is happening. Could someone please review my cod ...

Managing nested Angular repeats with counter

In the previous section of my document, I have a presentation layer that effectively organizes information within a shopping cart. This arrangement functions perfectly fine. At the lower portion, I employ the following code to generate form variables whic ...

Switch the background color of the checkbox div or label with a single click

I have successfully implemented the following code, with one small issue. When I select the checkbox, the background color of the div changes from #fff to #ffe600 as expected. However, after submitting the form and refreshing the page, the background color ...

Confirm that the array contains exactly 2 elements

Is there a way to confirm that an array contains exactly two specific values, for example: ['foo', 'bar'] After trying different approaches, the closest solution I found looks like this: Yup.array() .of(Yup.mixed().oneOf(['foo&a ...

What steps can I take to stop a website in an iframe from causing the entire page to refresh?

My website includes an iframe that showcases different websites submitted by users. This feature works well, but there is an issue with certain sites causing the whole page to refresh and redirect users away from my site. I want to prevent this initial r ...

Exploring the possibility of designing custom pageload tooltips inspired by jQuery validationEngine's visual style and interface

My website incorporates the jQuery.validationEngine plugin to ensure the accuracy of user input. The tooltips that accompany this validation feature are particularly appealing; they gracefully fade in and vanish when users interact with them. To visualize ...

What is the purpose of setting the Z-Index on a Popper menu

If you want to see a live example demonstrating the issue, head over to codesandbox.io. My goal is to create a 'sit below' menu just like it's shown in the Material-UI documentation here. return ( <div className={classes.root}&g ...

Checking the opacity with an if/else statement, then adding a class without removing the existing class

This function is designed to check the opacity of the header, which fades out as a user scrolls down. If the opacity is less than 1, it disables clickability by adding the class "headerclickoff". However, there seems to be an issue with removing the clas ...

Issues with babel plugin-proposal-decorators failing to meet expectations

I recently included these two devDependencies in my package.json: "@babel/plugin-proposal-class-properties": "^7.1.0", "@babel/plugin-proposal-decorators": "^7.1.6", In the configuration file .babelrc, I have listed them as plugins: { "presets": ["m ...

Having difficulty accessing any of the links on the webpage

I'm currently utilizing the selenium webdriver to automate a specific webpage. However, I am encountering an issue where my selenium code is unable to identify a certain link, resulting in the following error message. Exception in thread "main" org ...

Enhance the versatility of the image upload script

My script successfully previews an uploaded image for a single upload. Now, I want to apply this script to multiple image uploads and make the readURL function dynamic so that I don't have to repeat lines of code. $(".patient_pic").on("change",funct ...

Unable to sort the list items when utilizing the load() function

I have multiple li elements within a ul and I am using the following code to sort them in ascending order based on the data-percentage attribute: $(function() { $(".alll li").sort(sort_li).appendTo('.alll'); function sort_li(a, b) { re ...

Create a custom countdown using Jquery and Javascript that integrates with MySQL and PHP to display the datetime in the format Y-m-d

Hey there, I'm looking to create a countdown script using dates in the format (Y-m-d H:m:s). The goal is to retrieve the current_datetime and expire_datetime in this format and incorporate them into some JavaScript or jQuery plugin to display a countd ...

Changing the color of an open Bootstrap 4 accordion panel when the page loads

I am looking to emphasize the panel that the user has opened. If a user clicks the button in the card header, the background turns red, which is working smoothly as demonstrated in the code snippet. In certain scenarios, the first panel is open by default ...

How to Maintain Button Activation in NextJS

I am facing an issue with my buttons and form interaction. I have a group of 3 buttons and a form. When I select a button, it stays active as expected. However, once I click on the "submit" button in the form, the previously selected button loses its activ ...

What could be causing the issue with Vite build and npm serve not functioning together?

After shifting from CRA to VITE, I am encountering a problem with serving my app. I successfully build my app using vite build. and can serve it using Vite serve without any issues. However, I want to use npm's serve command. Whenever I run vite bui ...

Node.js Error: The object does not have the specified method

Recently, I dived into the world of node.js by following a fantastic tutorial on node.js, express, and mongodb from Howtonode. However, I encountered an error that doesn't seem to have been addressed in the comments section. The last comment was made ...

Maintain a persistent Facebook login session using PHP and Puppeteer

Currently, I am utilizing puphpeteer, a PHP bridge for node's puppeteer that supports the entire API. My task involves scraping various Facebook pages to gather specific information. To accomplish this, I need to login with my credentials and then acc ...

JavaScript code that includes a while loop and an ajax call is malfunctioning

While attempting to create a basic while loop in JavaScript, I keep encountering the spinning wheel icon on my Mac every time I run my script. The code below is triggered by pressing an HTML button: <script type="text/javascript"> $(document).re ...

To prevent the page focus from shifting, make sure to force click on a blank link

My question involves an empty link: <a href="#" id="stop-point-btn">+ add stop-point</a> This link is connected to a JavaScript function: $("#stop-point-btn").bind("click", addStopPoint); The JS function simply inserts content into a specif ...