4 ms·
All that’s great about CoffeeScript in 40 characters
- elliotbradly 12y agoArray.prototype.compact = function( list) { for ( var i = list.length; i >= 0; i--) { if ( list[ i ] == null) results.splice( i, 1); }
- gmac 12y agoThat is nice, but you'd need to first copy this (or 'list') to results to make it do the same as the CoffeeScript example.
- nwienert 12y agoOP's example in coffeescript: Array::compact = -> x for x in @ when x? In es6: Array.prototype.compact = function() { return this.filter(x => x !== null); } I find it easier to read than OP's example, but I would like to see non-lexically bound this function shorthand in es6/7. I see a mention of it at the bottom of this spec[1], but not sure what they mean by "Initializer opt". Maybe like this: Array.prototype.compact = this => this.filter(x => x !== null) [1] http://tc39wiki.calculist.org/es6/arrow-functions/ http://tc39wiki.calculist.org/es6/arrow-functions/
- gumballhead 12y agoOr even in ES5... [].filter(function(item) { return item != null; }); It's not patched on the prototype, but I'm not sure why something that simple needs to be.
- gumballhead 12y agoSure, that is a nice one liner, but the reason that JavaScript code is so ugly is because it's what the CoffeeScript function compiled to.
- gmac 12y agoWell, it has a few more underscores, but it's otherwise pretty much identical to the JS I'd have written by hand.
- slashnull 12y agoAh yes the argument by neat one-liner. Now let's move on to the truly relevant and constructive activity: comparing which language has best-looking toy quicksort implementation
- gmac 12y agoHey, I didn't set out to write an essay on the joys of CoffeeScript. I was just writing some code, as you do, and was struck by this one-liner as a good example of why I like CoffeeScript so much.