Created
March 19, 2014 19:02
-
-
Save inexorabletash/9648860 to your computer and use it in GitHub Desktop.
Resource Disposal: Haskell's Bracket pattern in JS
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
// http://cautionsingularityahead.blogspot.com/2012/07/resource-using-in-javascript.html | |
// Say you have a heavy-weight resource that you can explicitly finalize - either through | |
// some API or just by dropping a reference when you're done even if you want to hold onto | |
// the wrapper: | |
function Resource(a) { | |
var res = "a resource of " + a; | |
this.get = function() { | |
return res; | |
}; | |
this.dispose = function () { | |
console.log('destroyed: ' + res); | |
res = null; | |
}; | |
} | |
// A JS impl of Haskell's bracket pattern: | |
function bracket(before, during, after) { | |
before(); | |
try { | |
return during(); | |
} finally { | |
after(); | |
} | |
} | |
// And an example of using bracket() | |
(function() { | |
var res; | |
bracket( | |
function () { res = new Resource('foo'); }, | |
function () { console.log(res.get()); }, | |
function () { res.dispose(); res = null; } | |
); | |
}()); | |
// But it can be tailored more specifically to the resource disposal case... | |
function using(resource, user) { | |
if (!resource || typeof resource.dispose !== 'function') { | |
throw new Error('resource does not expose a dispose method'); | |
} | |
try { | |
user(resource); | |
} finally { | |
resource.dispose(); | |
} | |
} | |
// And you end up using it like C#: | |
(function() { | |
using(new Resource('bar'), function (res) { | |
console.log(res.get()); | |
}); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment