Break out of functions in a more composable way.
breakable
is useful when you want to break out of a deep recursion, passing a value, without riddling your code with exception ceremony.
Get it: npm install breakable
Sample usage:
Instead of
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| const esprima = require("esprima").parse;
const traverse = require("ast-traverse");
const ast = esprima("f(!x, y)");
let val;
try {
traverse(ast, {pre: function(node) {
if (node.type === "UnaryExpression" && node.operator === "!") {
val = node.argument;
throw 0;
}
}});
} catch(e) {
if (val === undefined) {
throw e; // re-throw if it wasn't our exception
}
}
console.dir(val); // { type: 'Identifier', name: 'x' }
|
You could:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| const breakable = require("breakable");
const esprima = require("esprima").parse;
const traverse = require("ast-traverse");
const ast = esprima("f(!x, y)");
const val = breakable(function(brk) {
traverse(ast, {pre: function(node) {
if (node.type === "UnaryExpression" && node.operator === "!") {
brk(node.argument);
}
}});
});
console.dir(val); // { type: 'Identifier', name: 'x' }
|
GIF FTW
P.S: This is a trivial example, if you want to do something like that in the gif
you might want .some