Skip to content

Instantly share code, notes, and snippets.

@devongovett
Created January 11, 2012 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devongovett/1593480 to your computer and use it in GitHub Desktop.
Save devongovett/1593480 to your computer and use it in GitHub Desktop.
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()
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();
}
}
};
@devongovett
Copy link
Author

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment