public
Created

  • Download Gist
FileInfo.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
class FileInfo
constructor: (filename) ->
@name = filename
 
mtime: ->
# in CoffeeScript, the last thing in a function is returned
# which in this case is the value returned from @withFile
# which is the value returned from the inner function
# => binds scope to the correct `this`
@withFile (f) =>
mtime = @mtimeFor(f)
return "too old" if mtime < Date.now() - 1000
console.log "recent!"
return mtime
 
body: ->
@withFile (f) =>
return f.read()
 
mtimeFor: (f) ->
return File.mtime(f)
 
withFile: (fn) ->
try
f = File.open(@name, "r")
fn(f) # the result of this is implicitly returned in CoffeeScript
finally
f.close()
FileInfo.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
function FileInfo(filename) {
this.name = filename;
}
 
FileInfo.prototype = {
mtime: function() {
// return the result of the inner function
return this.withFile(function(f) {
var mtime = this.mtimeFor(f);
if (mtime < Date.now() - 1000) {
return "too old";
}
console.log("recent!");
return mtime;
}.bind(this)); // bind scope
},
 
body: function() {
return this.withFile(function(f) { return f.read(); });
},
 
mtimeFor: function(f) {
return File.mtime(f);
},
 
withFile: function(fn) {
try {
var f = File.open(this.name, "r");
return fn(f); // call and return the result of the "block"
} finally {
f.close();
}
}
};

It didn't take much work to get JS to perform as expected, a few extra return statements and a bind call and we're done. CoffeeScript is even closer with its implicit returns and => binding syntax. Am I missing something else, or do we already have everything we need and this is just sugar?

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.