All that’s great about CoffeeScript in 40 characters
Today, I needed a JavaScript equivalent of Ruby’s Array#compact (which returns the array stripped of any nil values).
A standard JavaScript implementation looks like this:
Array.prototype.compact = function() {
var x, _i, _len, _results;
_results = [];
for (_i = 0, _len = this.length; _i < _len; _i++) {
x = this[_i];
if (x != null) {
_results.push(x);
}
}
return _results;
};
But since I’m using CoffeeScript, I get this monstrosity of line-noise and distraction for free when I type this:
Array::compact = -> x for x in @ when x?
This is some of the best of CoffeeScript: array comprehensions, implicit return, the existential operator ?, and more. Taking 11 lines of JavaScript busywork and turning it into 40 pithy, elegant characters.