Last active
August 29, 2015 14:25
-
-
Save lewisje/2f3cb64187668664f483 to your computer and use it in GitHub Desktop.
This gist encapsulates most uses of try/catch/finally blocks, a simple way to make functions from non-functions, and getting a reference to the global object, without triggering the optimization killers in V8: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#2-unsupported-syntax
This file contains 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
// part of a pair of functions intended to isolate code that kills the optimizing compiler | |
// https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#2-unsupported-syntax | |
function functionize(func, arg) { | |
switch (typeof func) { | |
case 'string': | |
return arg ? new Function(String(arg), func) : new Function(func); | |
case 'function': | |
return func; | |
default: | |
return function () {return func;}; | |
} | |
} | |
// The first argument to the toCatch callback is the caught error; | |
// if toCatch is passed as a string, this argument must be named `e`. | |
function trial(toTry, toCatch, toFinal) { | |
var try1 = functionize(toTry), | |
catch1 = functionize(toCatch, 'e'), | |
final1 = functionize(toFinal); | |
try {try1();} | |
catch (e) {catch1(e);} | |
finally {final1();} | |
} | |
// This does not directly replace try/catch/finally blocks that | |
// would break or continue from loops or return from the function: | |
// Consider setting a variable indicating success or failure within | |
// each callback and then deciding to break, continue, or return. | |
// This is a reliable way to get a reference to the global object | |
// even in strict mode, without deoptimizing the entire function. | |
var global = function(){return this||(1,eval)('this');}(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment