Home > katas > Multiply JavaScript (8kyu)

Multiply JavaScript (8kyu)


Let's start with Multiply kata. I have to solve this one when I signed up for the Codewars account. It is some kind of validation, I guess.

Chek kata on Codewars

Description:

The code does not execute properly. Try to figure out why.

We start with this code:

function multiply(a, b){
  a * b
}

We can solve it just by adding the return

function multiply(a, b){
  return a * b
}

Or we can do oneliner

const multiply = (a, b) => a * b

Let's check others solutions.

Some people thought about edge cases.

The most popular one is:

function multiply(a, b){
  if (!a || !b || typeof(a) != "number" || typeof(b) != "number") {
    return 0;
  }
  return a * b;
}

Personly speaking I'd rather prefer to throw an error instead of 0. And I'd change if statement a little bit.


There is one more solution which I like better than the previous one.

function multiply(a, b){
  if (undefined == a || undefined == b
    || isNaN(a) || isNaN(b))
    throw new Error('Both arguments should be numbers')
  return a * b
}

My new solution

After looking at previous solutions a came up with this one.

function multiply(a, b){
  if (!isNaN(a) && !isNaN(b))
    return a * b
  throw new Error('Both arguments should be numbers')
}

I think it's better to throw an error if we didn't meet 'if' statement and it might be easier to read. But it's just personal preference.

© 2021, Andrew Losseff