DEV Community

loading...

A Couple of Beautiful Things I Learned Today

tang
"Poets do not go mad; but chess-players do. Mathematicians go mad, and cashiers; but creative artists very seldom." -GK Chesterton
・2 min read

I just wanted to make this post to share a couple of beautiful moments from the workshop I attended today.

This one is something I managed to write myself, and I'm fairly proud of it. The problem was to write a function that would take a number and return true if it was even, and false if it wasn't.

function even(num){
    return !(num%2);
}

This function relies on the fact that 0 evaluates falsey (that is to say, when it's type coerced to a boolean, it resolves as "false"). Since I know that the modulo operation will give a zero when a number divides evenly, I just have to flip the value with a not (!) operator. After that, it'll give me true when num is even, and false when it isn't.

I felt proud of myself for finding this solution.


Next, we have some stuff that's obvious for anyone who's done any amount of formal logic, but felt like a real revelation/accomplishment for me.

The first part of the assignment was to reproduce "or" functionality, meaning the || operator, with only ! and && operators. The second was to reproduce "and" functionality (&&) with only ! and || to work with.

function or(a, b){
    return !(!a&&!b);
}

function and(a, b){
    return !(!a||!b);
}

Previously I had written the "or" with if/else statements, accounting for !a&&b, a&&!b, and a&&b as potential cases that should return true. Finding a way to write it succinctly in a single line without any of the accoutrements of JS control flow felt like a revelation.

The secret, of course is that the "or" operator will only return false when both operands are false. So we can represent that situation as !a&&!b. That will resolve to "true" when both a and b are false, and it will resolve to "false" in all other scenarios. This is the opposite of the functionality we want from it, so the last step is to simply invert the resulting boolean.

Similarly, I had written a&&b as follows:

function and(a, b){
    if (a) if (b) return true;
    return false;
}

I couldn't understand how to constrain the || operator in an effective way, and honestly I needed a glimpse at someone else's solution in order to understand how to conceptualize my own.

Still, filling in the rest to reach this solution and cleaning it up in these ways felt beautiful. The solutions are elegant, perfect constructs. Not a single wasted character, all working in concert. No flaws, no edge cases. Just logic.

Let's look at them again:

function or(a, b){
    return !(!a&&!b);
}

function and(a, b){
    return !(!a||!b);
}

ahhh, so serene.

Discussion (0)