I am looking to optimize my JavaScript function so that the console.log structure is functioning correctly. What changes can I make to

I've been trying out this method to tackle the issue, however, my console.log isn't providing the expected output. What adjustments should I make?

const executeCalculator = ({ x, y, operation }) => {
  let calculator = {
    x: this.x,
    y: this.y,
    operation: {
      "sum": (x, y) => x + y,
      "subtract": (x, y) => x - y,
      "multiply": (x, y) => x * y,
      "divide": (x, y) => x / y,
    },
  }
  if (operation !== 'sum' || 'multiply' || 'subtract' || 'divide') {
    console.error('undefined operation');
  } else {
    return;
  };
};

console.log(executeCalculator({
  operation: 'sum',
  x: 1,
  y: 1
}));

Answer №1

  • First and foremost, the formatting of your operation object was incorrect due to an extra comma.
  • The following code is unnecessary:
x: this.x,
y: this.y,

...as the parameters are already present in your function arguments.

  • The x, y parameters in "sum": (x, y) are also redundant for the same reason.
  • To verify the validity of the operation, utilize includes() and structure the condition as follows:
!['sum', 'multiply', 'subtract', 'divide'].includes(operation)
  • The executeCalculator() function was not returning a value, leading to the observed undefined outcome.

const executeCalculator = ({ x, y, operation }) => {

  let calculator = {
    operation: {
      "sum": () => x + y,
      "subtract": () => x - y,
      "multiply": () => x * y,
      "divide": () => x / y
    }
  }
  if (!['sum', 'multiply', 'subtract', 'divide'].includes(operation)) {
    console.error('undefined operation');
  } else {
    return calculator.operation[operation]();
  };
};

console.log(executeCalculator({
  operation: 'sum',
  x: 1,
  y: 1
}));

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

Personalize Tooltip on Highchart Area Chart

I am currently in the process of customizing the tooltip for my area chart using Highchart. Within this area chart, I have plotted 3 series. My goal is to display the tooltip at a fixed location on the chart's top center. When hovering over any point ...

Accessing the current route in a Vuex module using Vue.js

I've created a vuex store with namespaces that retrieves a specific store entry based on the current route parameter. import Router from '../../router/index' const options = { routeIdentifier: 'stepId' } export function fetchFr ...

Having difficulty accessing the Material UI Icons

I encountered an issue when attempting to utilize Material UI icons - as soon as I added the icon component, an error occurred. https://i.stack.imgur.com/issmm.png For reference, you can find the code on CodeSandbox at the following link: https://codesand ...

What is the best method to make a hyperlink within an IFrame open in a new window?

Let me share the code I've been working on: <!DOCTYPE html> <html> <head> <base target="_blank"> </head> <body> <div style="border: 2px solid #D5CC5A; overflow: hidden; margin: 15px auto; max-width: 800px; ...

The use of pattern fill in fabric.js is causing a decrease in rendering speed

I recently attempted to create a clip mask effect on a large image by using the picture as a pattern and setting it to the svg paths that support the desired shape. You can view the slow-loading jsfiddle example here: http://jsfiddle.net/minzojian/xwurbw ...

Rearrange the order of items in the fancybox gallery

Typically, fancybox displays items in the gallery based on the order they are added in the HTML code. Is there a way to customize the order of items when they are opened in the popup, while keeping the original order when displayed on the page? The solut ...

Tips for confirming date is earlier than current date in Reactjs?

Looking for guidance on how to ensure a date selected by a user is always before the current date when using Material UI in my project. For instance, if it's January 6th, 2021 and the user selects either January 5th or 6th that would be acceptable. Ho ...

Accessing information from req.files in a TypeScript environment

I am currently using multer for uploading images. How can I retrieve a specific file from req.files? Trying to access it by index or fieldname has been unsuccessful. Even when I log it, I see that it's a normal array, so I suspect the issue may be rel ...

The issue arises when the d3 startAngle and endAngle values are set to NaN, resulting in an

I am working with a dataset that includes the following information: { current: 5 expected: 8 gap: -3 id: 3924 name: "Forhandlingsevne" progress: "0" type: 2 } Now, I have implemented the ...

Charting Add-Ons for jQuery

Looking for suggestions on user-friendly graph drawing plugins compatible with jQuery. Currently developing a web application that will retrieve data from a remote database and present it through visual graphs... Explored jgcharts (the jQuery Google Chart ...

The integration of Node.js and express.js from distinct JavaScript files

How can I utilize express.js to render html in two separate files? file1.js file2.js The code inside file1.js is as follows: var express = require('express'); var app = express(); app.get('/foo/bar1', (req, res) => res.json([&apo ...

Jquery Plugin for Click Selection Activation

After receiving no response to my previous inquiry, I decided to proceed with this particular plugin setup. (function ( $ ) { $.fn.myPlugin = function (options) { options = $.extend( {}, $.fn.myPlugin.defaults, options ); return this.each(function (i ...

What is the best way to "re-upload" drop-down selection using javascript?

I am attempting to automate a drop-down selection process on a website using a headless browser called Firefox Marionette. The website is not under my control, and the process involves: A primary drop-down menu where I can choose an option. A secondary dr ...

Background image fixed with scrolling effect

I've been struggling with a parallax effect on my website. After seeing it work smoothly on other websites, I tried to implement it myself but couldn't quite get it right. The background image keeps moving when I scroll the page and I want it to ...

My current array is arr=[1,2,3,4]. I recently added an element to it using arr.push(5). Now I want to rearrange the array to be [5,4,3,2,1]. Any suggestions on how to achieve this

I currently have an array in the following format: var arr = [1,2,3,4] // Add another element to the array arr.push(5) // Now, arr = [1,2,3,4,5] I want to print my array as The elements in the array arr are: 5,1,2,3,4 When I use Arr.reverse(), it retu ...

Executing Custom Function Inside Custom Class

I've been attempting to develop a personalized class that can manage mail delivery on my behalf. Here's the code for my custom class (mailerclass.php): class Mailer { // Private fields private $to; private $subject; ...

What is preventing me from accessing these attributes using "${array[a].name}"?

What is preventing me from reading the properties using ${ array[a].name } with For Of loop? I created an example with an array of objects to help diagnose the problem. const movies = [{ title: "Shrek", year: 2001 }, { title: "Shrek 2", ...

Find and retrieve all data attributes with JavaScript

What is the method to retrieve all data-attributes and store them in an array? <ul data-cars="ford"> <li data-model="mustang"></li> <li data-color="blue"></li> <li data-doors="5"></li> </ul> The resultin ...

Using ObjectIDs in MongoDB may be successful, however, it may not function properly in Mongoose

The desired effect is successfully achieved by the first code snippet shown below: //in mongodb console: db.collection.update({"username":"name"}, {$pull : { "task" : { "_id" : ObjectId("55280205702c316b6d79c89c")}}}) However, the second code snippet wri ...

Getting row data from ag-grid using the angular material menu is a straightforward process

I have a specific requirement in ag-grid where I need to implement a menu to add/edit/delete row data. Currently, I am using the angular material menu component as the cell template URL. However, I am facing an issue where when I click on the menu item, it ...