2

I want (for example my prompt is enter a calculation) if the user enters 2+2 the document.write(sum); should display 4 on my empty page. I know how to easily do this with 2 prompts but im trying to make a sort of calculator. Ive seen this done on google or math way where you can type long strings of numbers and operators then it gives you the steps and finally the answer. I need a way to retrieve 1st item, then 2nd item, then 3rd item then store them in a variable. it would be great if i can do like 22+22 eventually but not sure how that would work. userInput.includes("+") might be good enough because theirs no other time.

//if (userInput.includes(allNumbers && "+")){
     // value1 = userInput.split("").map(parseInt).filter(i =>!isNaN(i))[0]
        //value2 = parseint(userInput);
       // sum = value1 + value1;

        //document.write(sum);

   //}

I have tried this but when i type 2+2 nothing happens. ive tried looking all over the internet but all i see is all string inputs or 1 number then a 2nd prmpt for the 2nd number.

I expect when a user types 2+2 for document.write to display 4. then i eventually want to do subtraction , division, and multiplication. but at the moment 2+2 does nothing

  • 2
    Possible duplicate of [Evaluating a string as a mathematical expression in JavaScript](https://stackoverflow.com/questions/2276021/evaluating-a-string-as-a-mathematical-expression-in-javascript) – ASDFGerte Oct 02 '19 at 23:35
  • [calculator-in-javascript](https://stackoverflow.com/questions/18141301/calculator-in-javascript) may also be an interesting read. – ASDFGerte Oct 02 '19 at 23:35
  • node has all this functionailty built in fyi – sao Oct 02 '19 at 23:46
  • how ? I cant find how to document.write what a user inputs in var userInput = prompt("Please enter your math problem: ", ""); then solves it – tmanrocks999 Oct 02 '19 at 23:49
  • https://mathjs.org/ this is perfect but im not sure how to make it work – tmanrocks999 Oct 03 '19 at 00:00
  • @traktor53 i have a solution i want to post on what i used ( people will like the answer its very simple can u reopen the question – tmanrocks999 Oct 09 '19 at 17:37

2 Answers2

3

A better approach would be to split up the calculation into parts and follow the BEDMAS rule:

  1. B: Extract and process items in brackets first. Keep going down into nested brackets until there are no more.
  2. E: Process items with exponents next.
  3. D: Process all items either side of the division symbol in turn.
  4. M: Process all items either side of the multiplication symbol in turn.
  5. A: Process all items either side of the addition symbol in turn.
  6. S: Process all items either side of the subtraction symbol in turn.
  7. If within a nested bracket, go up one level and continue at step 2. Replace the nested bracket with the result of the calculations within that backet.
  8. Keep repeating cyclically through the "tree" of brackets until you are done.

This is a VERY general overview of a basic calculator by simply flattening all the items until you get the final value (assuming there are no variables of course ;)).

Here is a way to get started:

var mathParts = "1 + 2 - ((3 + (2 * 3 / 3)) * 5^2) / 6".match(/[0-9()^/*+-]/g);

mathParts: (23) ["1", "+", "2", "-", "(", "(", "3", "+", "(", "2", "", "3", "/", "3", ")", ")", "", "5", "^", "2", ")", "/", "6"]

Now all you have to do is iterate over the array (mathParts) and increment your nesting level each time you hit ( and decrement the level each time you hit ). After that use multiple passes: first pass (or loop) handle exponents (^), then / on the next pass, then * on the next, then +, then -.

If you only run this client side, and strip out all non-math characters (don't allow $_AtoZ[]) and allow symbols needed for math only, then it should also be safe enough to simply use eval() to do the calculation. It is safe if used correctly, and only by the user of the webpage at the client side, since those same users can already press F12 and hack the site if they wanted to; thus, protecting from eval is pointless in that context. I would suggest if you go that route to run eval() within a new Function("eval()") scope so it runs at the global level and not within the scope of your own code (to keep private things private).

James Wilkins
  • 6,836
  • 3
  • 48
  • 73
  • 1
    that seams really complex . in class now might try when i get home. I have no idea how to do this sort of thing ug. – tmanrocks999 Oct 02 '19 at 23:43
  • const amountOfVariables = userInput.split("").map(parseInt).filter(i => !isNaN(i))[0] this worked earlier in my program for finding the first numbers in a String makes it a number then I used it to print out the amount of variables . but now i want 2 numbers and a symbol from a input prompt – tmanrocks999 Oct 02 '19 at 23:44
  • https://mathjs.org/ i found this but im not sure how the demo thing works – tmanrocks999 Oct 02 '19 at 23:54
  • `if (userInput.includes("+")){ sum = math.eval(userInput) document.write(sum); } ` I feel like im close – tmanrocks999 Oct 02 '19 at 23:56
2

https://www.npmjs.com/package/calculator-scripts

node module

why write it all yourself when there is a module. You'll need a node environment. I can give you some easy to hard ways to build one based on your experience level, let me know if you need help on that.

sao
  • 1,835
  • 6
  • 21
  • 40
  • https://jsfiddle.net/hw04Lbc5/ how can i post this for everyone's use. i just had to import a library. easy input from user . so little code – tmanrocks994 Oct 04 '19 at 01:22
  • you will have to build a backend or use a simulated one. you might want to check out Wix. they have a node backend built in and they have a lot of built in modules. – sao Oct 04 '19 at 13:22
  • is there anyway to get my question reopened – tmanrocks999 Oct 14 '19 at 23:48
  • @tmanrocks999 I dont have the authority, i think you have to have 2000 rep to do that. Just ask it again : ) try to be more specific. whoever voted it closed did so due to "unclear as to what you are asking" cheers – sao Oct 15 '19 at 00:12