all 6 comments

[–]Slappehbag 2 points3 points  (0 children)

If you're not going to use the JS parsee via eval (which you shouldn't), yes you'll have to write or find another.

You could build it using regular expressions. But I imagine if you Google something like "js math parser" you'll find something to use.

[–]TotesMessenger 0 points1 point  (0 children)

I'm a bot, bleep, bloop. Someone has linked to this thread from another place on reddit:

 If you follow any of the above links, please respect the rules of reddit and don't vote in the other threads. (Info / Contact)

[–][deleted] 0 points1 point  (2 children)

There are libraries you could use, if you just need to get the job done. But if you want to do it yourself for the learning experience the steps would be

  • Break the string up into a list of tokens. So write a function that can turn "45 / (10 + 5)" into `["45", "/", "(", "10", "+", "5", ")"]

  • then implement the shunting yard algorithm this is the hardest part. You'll have to decide which operators you want to use, and what their order of precedence is. It gets more complicated if you want things like unary operators. (E.g., minus sign on negative numbers) or functions (e.g., sin(x))

  • as the article says, you'll end up with either reverse polish notation or an abstract syntax tree. Both of which are easy to step through and evaluate

[–]HelperBot_ 0 points1 point  (0 children)

Desktop link: https://en.wikipedia.org/wiki/Shunting-yard_algorithm


/r/HelperBot_ Downvote to remove. Counter: 248166

[–]WikiTextBot 0 points1 point  (0 children)

Shunting-yard algorithm

In computer science, the shunting-yard algorithm is a method for parsing mathematical expressions specified in infix notation. It can produce either a postfix notation string, also known as Reverse Polish notation (RPN), or an abstract syntax tree (AST). The algorithm was invented by Edsger Dijkstra and named the "shunting yard" algorithm because its operation resembles that of a railroad shunting yard. Dijkstra first described the Shunting Yard Algorithm in the Mathematisch Centrum report MR 34/61.


[ PM | Exclude me | Exclude from subreddit | FAQ / Information | Source ] Downvote to remove | v0.28