CoffeeScript Ternary Operator (and more…)

The ternary operator ? : is a nice short-hand way of doing an if-then-else clause when you need to return a value. It exists in many languages, but for this post I will use C# as reference.

var result = (a < b) ? "a < b" : "a >= b";

In CoffeeScript, on the other hand, the ternary operator does not exist. What you can instead do is:

result = if (a < b) then 'a < b' else 'a >= b'

Another useful operator in C# is the null-coalescing operator ??. It returns the second value if the first one is null.

var result = myVariable ?? "Default value";

In JavaScript, the alternative is usually to utilise a logical or: ||. However, due to the truthyness in JavaScript (and CoffeeScript), the end result may not always be what you expect.

a = 1;
b = 2;
result = a || b // result = 1

a = 0;
result = a || b // result = 2 since 0 is falsy

In CoffeeScript, you can use the existential operator ? instead:

a = 0;
b = 2;
result = a ? b // result = 0

a = null
result = a ? b // result = 2

The existential operator can be used in assignments too:

result = 5
result ?= 7 // result = 5

result = null
result ?= 7 // result = 7
Advertisements

Extending OrderBy

I found some really sexy code today. It was written by “mazzy maxim” as Community Content to MSDN.

What it does is to extend the OrderBy method for IEnumerables. You provide the name of the property you want to sort by, and the sort order. Without further ado, here’s the code:

public static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> items, string property, bool ascending)
{
    var MyObject = Expression.Parameter(typeof(T), "MyObject");
    var MyEnumeratedObject = Expression.Parameter(typeof(IEnumerable<T>), "MyEnumeratedObject");
    var MyProperty = Expression.Property(MyObject, property);
    var MyLambda = Expression.Lambda(MyProperty, MyObject);
    var MyMethod = Expression.Call(typeof(Enumerable), 
                                   ascending ? "OrderBy" : "OrderByDescending", 
                                   new[] { typeof(T), MyLambda.Body.Type }, 
                                   MyEnumeratedObject, 
                                   MyLambda);
    var MySortedLambda = Expression.Lambda<Func<IEnumerable<T>, IOrderedEnumerable<T>>>(MyMethod, MyEnumeratedObject).Compile();
    return MySortedLambda(items);
}

So what we have is a generic extension method for IEnumerables that creates a  lambda expression on the fly to sort the objects by the property with the given name.

Pretty cool or what?