4 ms·
The examples weren't too enlightening. In the first example I would have written the original handler like this, for example. Written more concisely it doesn't
by yason 15y ago
The examples weren't too enlightening.
In the first example I would have written the original handler like this, for example. Written more concisely it doesn't present an immediate need for shortening or clarification by CS:
document.onkeydown = function(event) {
var key_to_func = {
37: "pan_left", 38: "pan_up",
39: "pan_right", 40: "pan_down",
189: "zoom_out", 187: "zoom_in"
};
for (var i in game_pieces)
game_pieces[i][key_to_func[event.keyCode]]();
return the_screen.refresh(game_pieces);
};
The class example is better but I haven't found much use for the JavaScript prototypes to build class-like constructs. Instead of using prototyping I generally just create objects and shove stuff into them. YMMV.
Last example is merely a transformation of the first version. The constructs used are quite similar: it would have been nice to see CoffeeScript transform the actual paradigms used in the code. The CoffeeScript version still reads like JavaScript, just with slight syntactic sugar.
Mere syntactic sugar might actually be the core idea of CoffeeScript (instead of landing a somewhat higher-level language on top of JS) in which case the example illustrates nicely why the gains from switching from JS to CS are mostly cosmetic. You can compress your code conceptually much better if you just write JS more functionally, i.e. write a few quick functions to provide map/filter/reduce and some helpers.