DEV Community

Bruce Axtens
Bruce Axtens

Posted on • Updated on

Javascript madness - perfect square

Today I had it drummed into to me again that TMTOWTDI (There's more than one way to do it) and this is as true for JavaScript as it is for Perl.

Thanks to someone here on dev.to, I discovered how cool CodeWars is, and have been spending some happy minutes solving various kata.

Today one of them required me to build a function that returned true or false depending on whether the argument was a perfect square or not.

I'm not going to show you my solution. I'm going to show you a TMTOWTDI solution, viz

const isSquare = x => !Math.sqrt(x).toString().split(".")[1]
Enter fullscreen mode Exit fullscreen mode

And this is what it means:

  1. Get the square-root of the argument
  2. Convert it to string
  3. Split on decimal point
  4. Get the second element of the split's result
  5. Negate the result of the expression (with !)

Now if the square-root is not an integer, there will be something in that second element and the negation will translate to false. However, if the square-root is an integer, then the second element will be undefined which the ! will translate into true.

Thus:

Lychen> isSquare(81)
True
Lychen> isSquare(82)
False
Enter fullscreen mode Exit fullscreen mode

Maybe somewhere there's a TIOOWTDI (There is only one ...) language but JavaScript isn't it.

Top comments (1)

Collapse
 
bugmagnet profile image
Bruce Axtens

Thank you very much indeed for pointing me at exercism.io. It's very good and bit easier for me to work with compared to codewars.com