websplee

Posted on

# Implementing Standard Calculator

I was recently challenged to develop a standard basic calculator that would evaluate a given expression following the BODMAS rules and of course, return the answer. The one rule to this was that I did not have to use any inbuilt evaluation methods.

So lets get started. I began with an interface that defined the methods I was going to use.

interface IBaseCalculator
{
string EvaluateEquation(string equation);
string EvaluateOperation(string equation, char op);
double EvaluateSubtraction(double a, double b);
double EvaluateMultiplication(double a, double b);
double EvaluateDivision(double a, double b);
}

I then went ahead and implemented this with a constructor taking in the set of operations that I needed to support. In this case division, multiplication, addition and subtraction. This is the interesting part. I created an array of characters to represent the operations allowed for this calculator.

NOW, in order to make sure the rules of BODMAS were adhered to, I had to declare the array in the order representing BODMAS rule.

The EvaluateOperation method iterates through the equation and starts breaking it down following the BODMAS rules. It does this by invoking the appropriate Evaluate method. In case of multiplication, it calls EvaluateMultiplication.

public string EvaluateOperation(string equation, char op)
{
int i = 0;

``````        if (equation.Contains(op))
i = equation.IndexOf(op);
switch (op)
{
case '(':
throw new NotImplementedException();
case ')':
throw new NotImplementedException();
case '/':
Double.Parse(equation[i + 1].ToString()));
break;
case '*':
Double.Parse(equation[i + 1].ToString()));
break;
case '+':
Double.Parse(equation[i + 1].ToString()));
break;
case '-':
Double.Parse(equation[i + 1].ToString()));
break;
}
``````

https://github.com/websplee/StandardCalculator/blob/master/StandardCalculator/BaseCalculator.cs

DEV Community

## An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.