3 ms·
This is where syntactic sugar can be helpful. CoffeeScript can make the example a lot more readable by removing the unnecessary braketing when the last argument
by athenot 10y ago
This is where syntactic sugar can be helpful. CoffeeScript can make the example a lot more readable by removing the unnecessary braketing when the last argument of a function is a callback (common case in node.js). The only thing that's still ugly is the .bind() applied to a function, which somewhat messes with the style. Other than that, this makes callbacks flow a lot more naturally when reading source code.
(Of course, as it is for all stylistic considerations, it's a matter of taste, not absolutes.)
fs.readdir source, (err, files) ->
if err
console.log 'Error finding files: ' + err
else
files.forEach (filename, fileIndex) ->
console.log filename
gm(source + filename).size (err, values) ->
if err
console.log 'Error identifying file size: ' + err
else
console.log filename + ' : ' + values
aspect = values.width / values.height
widths
.forEach ((width, widthIndex) ->
height = Math.round(width / aspect)
console.log "resizing #{filename} to #{height}x#{height}"
this.resize width, height
.write "#{dest}w#{width}_#{filename}", (err) ->
if err then console.log 'Error writing file: ' + err
).bind this
- Mithaldu 10y agoPlease don't perpetuate the else silliness of the (intentionally bad) first example there. Stick a return in front of the log calls, lose the else, and unindent all following.
- athenot 10y agoYes, that is of course preferable. There are much better error handling strategies than what the example gave. I was only commenting on the readability aspect, all other things being equal.
- susw 10y agoUse '=>' instead of '->' to automatically bind 'this'.
- weberc2 10y agoI absolutely disagree. Brackets are a big part of the reason the JS version is more readable than the CoffeeScript version, IMO. I don't understand why anyone would think readability would increase with syntactical ambiguity. This isn't even the traditional braces-vs-indentation argument either; I much prefer Python's syntax to CoffeeScript's, and I use both regularly.
- j_r_f 10y agoThat is almost definitely more messy looking than the alternative.