Created
January 11, 2012 07:04
-
-
Save devongovett/1593480 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It didn't take much work to get JS to perform as expected, a few extra
return
statements and abind
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?