Everyone Can Code!

JavaScript Kata #9: Basic Mathematical Operations

By YayoDrayber | Learn To Code With Me | 11 Aug 2022


If you missed the introductory post, it's here. For a list of previously solved katas, please refer to the bottom of this page.

If this is your first time seeing my post, please note - these katas are probably randomly assigned per user so please don't go into Codewars thinking we will have exactly the same user experience, I am just posting these in the order that I got them.

Kata #9

DESCRIPTION:

Your task is to create a function that does four basic mathematical operations.

The function should take three arguments - operation(string/char), value1(number), value2(number).
The function should return result of numbers after applying the chosen operation.

Examples(Operator, value1, value2) --> output

('+', 4, 7) --> 11
('-', 15, 18) --> -3
('*', 5, 5) --> 25
('/', 49, 7) --> 7

Starting code:

function basicOp(operation, value1, value2)
{
  // Code
}

My attempt:

function basicOp(operation, value1, value2)
{
  // Code
  let result = 0
  switch(operation) {
  case '+':
    result = value1 + value2
    break
  case '-':
    result = value1 - value2
    break
  case '*':
    result = value1 * value2
    break
  case '/':
    result = value1 / value2
    break
  default:
    return "not a valid operator"
    break
  }
  return result
}

Rank #1 'Best Practice' with 803 votes and 108 'Clever' votes at the time of writing: 

function basicOp(operation, value1, value2) {
    switch (operation) {
        case '+':
            return value1 + value2;
        case '-':
            return value1 - value2;
        case '*':
            return value1 * value2;
        case '/':
            return value1 / value2;
        default:
            return 0;
    }
}

Wow. Seems like it will feel pretty good because I decided to try my hand on using switch instead of so many ifs/else if and I'm only off by an excess variable declaration plus all those 'breaks', but this quickly turned very unsatisfying when we see the approach of rank #2 with 299 votes and 1120 'Clever' votes at the time of writing:

function basicOp(o, a, b) {
  return eval(a+o+b);
}

Pretty neat with the built-in eval() function, good trick to learn today.

Tidier ways to do it than my way at rank #3:

function basicOp(operation, value1, value2) {
    switch (operation) {
        case '+': return value1 + value2;
        case '-': return value1 - value2;
        case '*': return value1 * value2;
        case '/': return value1 / value2;
        default: return 'Operation must be one of + - * /';
    }
}

Rank #4:

function basicOp(operation, value1, value2)
{
  var cases = {
    '+': value1 + value2,
    '-': value1 - value2,
    '*': value1 * value2,
    '/': value1 / value2
  };
  return cases[operation]
}

Rank #7 submitted by a single person (metasean):

const basicOperations = {
  '+': (a,b) => a + b,
  '-': (a,b) => a - b,
  '*': (a,b) => a * b,
  '/': (a,b) => a / b,
}

const basicOp = (op, x, y) => basicOperations[op](x, y)

Rank #9 also submitted by a single person (randyf99):

function basicOp(operation, value1, value2) {
  return  operation == '+' ? value1 + value2 :
          operation == '-' ? value1 - value2 :
          operation == '*' ? value1 * value2 :
          operation == '/' ? value1 / value2 : 'Wrong Operation';
}

Rank #5 also made use of the eval() function and the switch statement for rank #8 so those were not worth repeating here while rank #6 made use of the aforementioned many ifs:

function basicOp(operation, value1, value2)
{
  // Code
  if( operation == "+") {
    return value1 + value2
  }
  if( operation == "-") {
    return value1 - value2
  }
  if( operation == "*") {
    return value1 * value2
  }
  if( operation == "/") {
    return value1 / value2
  }
}

Thanks to this coding challenge, I was able to move up from the 8 kyu rank to 7 kyu at the time of writing which was on August 6 2022. There's a bit of a backlog in posts because Publish0x only allows 2 articles posted per 24 hour period and sometimes irl activities get in the way of posting within that 24 hour period. My short-term goal is to hit the 6 kyu rank because Leon said that consistently solving the problems at that rank means I'm probably job-ready.

That's it for Kata #9, stay tuned for more katas to be solved!

Link to Kata #1: Square(n) Sum

Link to Kata #2: Convert a Number to a String

Link to Kata #3: DNA to RNA Conversion

Link to Kata #4: Remove First and Last Character

Link to Kata #5: MakeUpperCase

Link to Kata #6: Total amount of points

Link to Kata #7: A Needle in the Haystack

Link to Kata #8: Sum of positive

How do you rate this article?

4


YayoDrayber
YayoDrayber

A Yayo, A Drayber, among others.


Learn To Code With Me
Learn To Code With Me

Just started with Codewars and will be posting the solutions I came up with here and the apparent best practices.

Publish0x

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.