Not Your Father's JavaScript - Better built-in methods for common actions
neversaw.us9 pointsby isntitvacant0 comments
function compile(filename, ready) {
return fs.readFile(filename, make_fn)
function make_fn(err, data) {
if(err) return ready(err)
ready(null, new Function(data))
}
}
Which neatly addresses the desire to retain closures, while avoiding unnecessary nesting. res.on('data', accum.push.bind(accum))
// vs:
res.on('data', function(data) { accum.push(data) }) var validator = new RepoPathValidator(path);
validator.on('data', function(repoData) {
// do whatever needs to be done with the repo.
});
// redirect all errors to console.error
validator.on('error', console.error.bind(console));
I'm very fond of using this method to destroy nested code -- I'm not sure how it's thought of in the community
at large, though (part of the reason I'm so eager for the community to put together the aforementioned PEP-8
style "best practices" guide!) var session = require('session'),
models = require('models'),
template = require('template');
function main(request,response){
session.start(
models.getEntries.bind(models,
template.render.bind(template, 'blog',
response.write.bind(response))));
}
would be easy to put together with node.js; it's functionally equivalent to the above (though it assumes that data comes into the template.render call as the last argument(s)), and neatly avoids too much nesting.
Where you have to be careful is if you have a function that's being called repeatedly and it contains a function instantiation -- that function will be reallocated each time.
Will repeatedly allocate that inner multiplication function, vs:
Will only allocate that multiplication function once.