We're back with another code challenge, this one comes from user obrok on Codewars:
Create a simple calculator that given a string of operators (+ - * and /) and numbers separated by spaces returns the value of that expression
Example:
Calculator().evaluate("2 / 2 + 3 * 4 - 6") # => 7
Remember about the order of operations! Multiplications and divisions have a higher priority and should be performed left-to-right. Additions and subtractions have a lower priority and should also be performed left-to-right.
Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Latest comments (25)
a bit late... this is the solution in PHP
My solution in js
I’m (still) learning Erlang. This is my solution with the given operators and integer numbers. I’m quite satisfied:
To run it:
Then I extended it with:
125e-2 = 1.25);^;You can find it in this Gist, and try it:
parse_numbergot a bit out of hand, but I find the rest quite elegant. I like Erlang.I remember doing this in C in college. It handled Real numbers (even Complex at one point, I believe), supported variables, could graph a function of
xand even calculate the derivative. Much fun.I missed this one yesterday! I'll get it done sometime this week though!
Haskell:
Would anyone be able to help me abstract out that operation pattern? I'm a little stumped on how to de-duplicate this code, even though Haskell is great at that.
JavaScript
Live demo on CodePen
10 out of 10 challenges! :)
Although I was just able to make 2 using CSS only :-/
I'm gonna try to keep doing em each day in July if I can, you game lol?
I'm currently a day behind you since I didn't get this one done yesterday
Let's do it!
Nim.
Did some cleanup using types. No more string->float->string conversions. Adding old solution below!