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]
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 true
.
Thus:
Lychen> isSquare(81)
True
Lychen> isSquare(82)
False
Maybe somewhere there's a TIOOWTDI (There is only one ...) language but JavaScript isn't it.
Top comments (1)
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