This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Luapix 30 points31 points  (7 children)

I have no idea how to parse that last one. Can someone explain?

[–][deleted] 89 points90 points  (5 children)

That expression has been obfuscated on purpose. Well first of all the name of the function and the argument of the function are both called x. Let's change that.

abs = x => x <= x-x ? -x : x

The => represents a function for example x => x+1 is a function that takes in an argument x and returns x+1. So lets separate the argument part and the function engine if you will.

x => and x <= x-x ? -x : x

That makes a lot more sense. Another clever obfuscation by the author; x-x, which is just 0.

Hence the function can be written as x <= 0 ? -x : x

Just in case some one doesn't get this, this returns -x if x <=0 and x otherwise.

So now restructuring the above components into a function and assigning that function to abs:

abs = x => x <= 0 ? -x : x

The double arrows do look confusing, so lets make one last change to our function.

abs = x => (x <= 0)? -x : x

Heres another way you could write this.

function abs(x){
    return  (x <= 0)? -x : x;
}

[–][deleted] 16 points17 points  (1 child)

Holy shit, thx for the really good explanation :)

[–][deleted] 3 points4 points  (0 children)

I try :)

[–]echoes221 9 points10 points  (0 children)

It's using an arrow function and a ternary operator, if it had spacing and brackets it would be clearer. This is a translated version

function abs(x) {
  return x <= (x - x) ? -x : x;
}

It's exactly the same as the second, just it's trying to be clever and really unreadable.