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(".")
And this is what it means:
- Get the square-root of the argument
- Convert it to string
- Split on decimal point
- Get the second element of the split's result
- 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
Lychen> isSquare(81) True Lychen> isSquare(82) False