Skip to content

Instantly share code, notes, and snippets.

@MikeBild
Created July 21, 2013 05:41
Show Gist options
  • Save MikeBild/6047611 to your computer and use it in GitHub Desktop.
Save MikeBild/6047611 to your computer and use it in GitHub Desktop.
simple visitor pattern implementation
var calculator = {
add: function (node) {
return visit(this, node.l) + visit(this, node.r);
},
sub: function (node) {
return visit(this, node.l) - visit(this, node.r);
},
value: function (node) {
return node.value;
}
};
var dump = {
add: function (node) {
return visit(this, node.l) + ' + ' + visit(this, node.r);
},
sub: function (node) {
return visit(this, node.l) + ' - ' + visit(this, node.r);
},
value: function (node) {
return String(node.value);
}
};
var visit = function (visitor, node) {
return visitor[node.operation].call(visitor, node);
}
var tree = {operation: 'add',
l: {operation: 'value', value: 2},
r: {operation: 'sub',
l: {operation: 'value', value: 3},
r: {operation: 'value', value: 1}
}
};
console.log(visit(calculator, tree));
console.log(visit(dump, tree));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment