Tips for tackling several math problems simultaneously

I've attempted various methods, but the output is limited to simple addition or subtraction calculations.

Below is my code. Can anyone suggest a solution or provide additional code to enhance its functionality? Thank you!

Please note that the input should follow the format of '1+1' or similar due to the utilization of the split method.


var Equation = prompt("Enter Equation: (Currently only supports one math operation. Stay tuned for updates!'");
if (Equation === null) {
    close();
}
if (Equation.includes("+")) {
    const mySumAddition = Equation.split("+").map(x => parseFloat(x, 10));
    var AOne = mySumAddition[0], ATwo = mySumAddition[1];
    var additionAnswer = AOne + ATwo;
    alert(additionAnswer);
    var CO = confirm("Equation complete. Goodbye!");
}
// Repeat similar logic for subtraction, multiplication, and division

Answer №1

If you're looking to tackle multiple math questions simultaneously, such as 5+6+7+8-6-1*5+1=16, 5+6+7+8-6-1*(5+1)=14, and 5**5=3125 (which is equivalent to 5*5*5*5*5=3125), then this code could be the solution.

Note: Apologies if my explanation is hard to follow. English isn't my strong suit.

Using eval() can be risky but results in lightweight code. To ensure safety, add if (!(/[a-z]/i.test(Equation)) to filter out equations that contain other code (e.g., 1+'alert("You get infect")'+5) and only accept equations with numbers and basic operators (e.g., 1+5+9*8/5-9).

var Equation = prompt("Equation? (Can only take 1 math equation for now. Upcoming updates soon!)");

if (Equation === null) close();
if (!(/[a-z]/i.test(Equation)) && Equation.match(/\+|\-|\/|\*/g)) {
  var Answer = eval(Equation);

  alert(Answer);
  console.log(Answer)
  var CO = confirm("Equation Done, Goodbye!");

} else {alert(`Equation contain other words`)}
if (CO === true) {
  close();
}
if (CO === false) {
  close();
}

This script functions as a straightforward calculator.

var screen = document.querySelector(".screen > span");
document.querySelector(".equal-item").onclick = () => calc();
document.querySelector(".clear").onclick = () => screen.textContent = '';
document.querySelector(".back").onclick = () => screen.textContent = screen.textContent.substring(0, screen.textContent.length - 1);
document.querySelectorAll(".touche__box-item").forEach(a => a.onclick = () => screen.textContent += a.id)

const calc = () => {
  var Equation = screen.textContent;
  if (Equation === null) return;
  if (Equation.match(/\+|\-|\/|\*/g)) {
    var additionAwnser = eval(Equation);
    screen.textContent = additionAwnser;
  }
}
.calculator {
  width: 408px;
  height: 837px;
  margin: 10px auto;
  position: relative;
  color: #000;
  font-size: 3em;
}

/* CSS styling information continued here... */

<html lang="en">

<head>

</head>

<body>

<main>

<div class="container calculator">
<div class="screen-item screen"> <span></span></div>
<dl class="touche__box">
<dt class="clear-item clear"> <span>C</span></dt><dt class="clear-item back"> <span><</span></dt>
<dt class="touche__box-item" id="-"> <span class="soustraction">_</span></dt>
<dt class="touche__box-item" id="+"><span class="sign">+</span></dt>
<!-- Additional HTML structure for the calculator buttons -->
</dl>
</div>

</main>
</body>

</html>

Answer №2

  • Process each question individually in the code and close after completion. Split the input into an array before processing.

    const equationArray = Equations.split(',');

  • Divide the input into an array of equations. Iterate through each equation using a loop.

    for(const Equation of equationArray) { // include your code within the loop }

  • Avoid setting equal to true inside the if condition, as the condition already returns true.

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

When processing UTF-8, REST only acknowledges English characters and ignores any other characters

When sending an AJAX request in UTF8 to a server that uses REST, any part that contains non-English characters is disregarded. I am working with Java on the server side with REST, and the client sends AJAX requests in UTF8 that may include Hebrew words. ...

Tips for generating a single CSS file that adapts to various screen sizes without the ability to modify the class names within the library

I am currently learning ReactJs and JavaScript and I have a question on how to optimize this css setup effectively. I am utilizing the react-responsive library to detect screen sizes and determine the best layout for my project. The issue I am facing is ...

The removal of a JQuery element can result in causing the webpage to become unresponsive and lead to

When attempting to create a loop in JQuery to remove elements from my HTML, I encountered an issue where the function caused my browser to hang and become unresponsive. Here is the JQuery code I used: function removeElement(){ var i =0; ...

Every time I try to retrieve my JavaScript code, I am bombarded with endless prompts that prevent me

Desperate for assistance! I have been using a website called "codepen" for my javascript coding, but I mistakenly triggered infinite prompts every time I open the project. Now, I am unable to access the code and despite my efforts in searching for a solu ...

"Encountering an error with Meteor while attempting to generate ObjectID due to an invalid hexadecimal

Recently, I've been working on updating data in the database while also inserting new information using jQuery (I know, I'm still learning). After this process, I need to be able to click on the data and display some user interface elements, whic ...

Exploring React hook functionalities can lead to discovering unexpected issues such as cyclic dependencies on location.hash when

My implementation of a useEffect involves reading the location.hash and adjusting the hash based on certain dependencies. Here is a snippet of how it works: useEffect(() => { const hashAlreadyPresent = () => { const hashArr = history.locati ...

Angular allows for easy downloading of files from a server by implementing a

I am attempting to retrieve a file from the server using REST in JAVA and pass some parameters. Although I have had success with the FileSaver.js library, it is not functioning properly in Safari 8. How can I go about downloading the file in Safari? I ha ...

Problem occurs when tab links vanish after clicking on another part of the website

Exploring the world of Javascript as a newcomer has been quite an adventure, but I've encountered a hurdle with tab links on my website. Everything seems to be working fine – the links cycle through and display the correct content. However, when it ...

A beginner's guide to integrating three.js into your React projects

I am having trouble integrating three.js into my React application. Despite following the basic sample from the three.js documentation, I am unable to load it on the canvas. Initially, I successfully implemented the sample in a vanilla.js sandbox. However ...

What is the process for executing a "hello world" on webassembly using the most recent version of Node.js?

Having thoroughly gone through the official documentation, I am still unable to locate the necessary information. Currently operating on Node.js version v8.1.3, I am seeking guidance on compiling and executing a basic "hello world" program in wast (WebAss ...

Can Java provide functionality similar to JS callbacks?

Can a similar functionality be achieved in Java? function sum(num1, num2, onComplete) { var result = num1 + num2; onComplete(result); } (function(){ sum(3, 5, function(res){alert(res)}); })() Is it possible to implement this in Java without ...

Is it necessary to have a "required" field in addition to a "default" field?

Consider the following mongoose schema: const projectSchema = new Schema({ mode: { type: Number, enum: { values: [0,1,2,3] message: "Values must be between 0 and 3" }, default: 1, ...

Using Angular to make a request to a NodeJS+Express server for a simple GET operation

I need help with making a successful GET request from my Angular component to a NodeJS+Express server. someComponent.ts console.log("Before"); // send to server console.log(this.http.get('/email').map((res:Response) => { console.log(" ...

Tips for concealing a class within JavaScript

I am looking for a way to hide a specific shipping class for products that qualify for free postmail delivery. Here is the scenario: If a product with the following link: is added to the cart and it belongs to this shipping class: shipping_method_0_adva ...

Refreshing the page causes Material UI Button to revert to default styling

My question regarding the Material UI Button losing styling after a page refresh (link: Material UI Button loses Styling after page refresh) went unanswered, so I am reposting with a CodeSandbox included for reference: https://codesandbox.io/s/bold-resonan ...

Utilizing jQuery to convert object properties into a table

Here is the table structure I am working with: <table> <thead> <tr> <th>Loan Type</th> <th>Amount Borrowed</th> <th>Current Payment< ...

Removing a Django object via AJAX or JavaScript with a confirmation prompt

Greetings! I am looking to implement a feature in Django where I can delete an object using AJAX or JavaScript with a confirmation message upon clicking the delete button. However, I am struggling to complete the AJAX request. Here is the code in views.py ...

Ruby on Rails allows for the selection of values in a dropdown menu to trigger the visibility of different sections of HTML

As a newcomer to Rails, I was able to successfully implement the onclick function for a f.checkbox element. Now, my challenge lies in achieving a similar functionality for a f.select element within a _form. Below is the code snippet that works for a chec ...

Extension for capturing videos on Chrome or Firefox

I am interested in developing a Chrome or Firefox extension that can capture video from a window or tab. My goal is to record full screen videos, such as those on YouTube, for offline viewing similar to a DVR for online content. Creating an extension see ...

Expand and enhance your content with the Vue Sidebar Menu plugin

Recently, I integrated a side-bar-menu utilizing . My goal is to have a sidebar menu that pushes its content when it expands. Any suggestions on which props or styles I should incorporate to achieve this effect? Below is my Vue code: <template> ...