Share your favorite code snippet

in programming •  8 years ago 

I'm interested in your favorite code snippet. It can be in any language.
Please share it in the comments below.

Mine is a way to swap to variables without using a temporary variable:

var a = 5;
var b = 3;
var a = b + a;
var b = a - b;
var a = a - b;

After that a is equal to 3 and b is equal to 5. We have swapped the variables without using a third variable.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Alternate way of swapping two vars without using a third:

a ^= b;
b ^= a;
a ^= b;

I'm also a fan of Java 8 streams:

public class MyObj {
    int someValue;
    // ...
}

List<MyObj> someList; // already defined

someList.stream()
  .map(myObj -> myObj.someValue)
  .filter(value -> value > 0)
  .findFirst().orElse(null);

Cool XOR swap. Didn't know this trick! Really neat.

var port = process.env.PORT || 8000
It's just so fancy using the pipes to set a default value when the initial value is undefined.

Good example! Ty