If you’ve been doing code for a while, you may have heard of code golf which is the practice of trying to write algorithms in as little as characters possible. Here, at Exercism, we generally discourage it because in general it goes against adopting fluency and all (defacto) standards.
It’s (sometimes) fun though.
However, that made me think about a lot of things a lot of us may or may not do in the languages we feel confident or competent in, that are actually hard for beginners (of that language) to understand.
Benign operators
An example would be:
!!value
# converts to a boolean
This seems benign, but if you come from a language that only has true
and false
and not thruthy and falsy, or a language that uses !
not as not but as assert, you may not understand that this is the equivalent of the pseudo code value to boolean
.
Another example may be the JavaScript:
const date = new Date()
+date
…which will give you the unix timestamp of that date. The clearer way to write this is date.getTime()
, or if you must, Number(date)
because its intend is clearer for more people, and .getTime()
is easier to find in documentation than plus operator on a Date
.
Complex non-operators
Some languages have cool complex operators, such as the spaceship operator in Ruby:
a <=> b
What this does is similar to a.compareTo(b)
in other languages. It effectively tells you if:
if a < b then return -1
if a = b then return 0
if a > b then return 1
if a and b are not comparable then return nil
This is an actual operator in Ruby, but -->
looks like an operator in C++ and is not:
int x = 10;
while (x --> 0) // x goes to 0
{
printf("%d ", x);
}
Whilst this looks like the downto operator, there is no operator -->
in C++. It’s a different way of writing x-- > 0
which is subtract one from x
and greater than
combined.
Your examples?
What I am looking for are seemingly benign examples that have a much clearer alternative in your language, and complex combinations that are confusing but fun. With one exception: RegExp is generally considered information dense and thus isn’t something you need to list as it’s difficult for people to understand by its very nature.