Created
July 21, 2013 05:41
-
-
Save MikeBild/6047611 to your computer and use it in GitHub Desktop.
simple visitor pattern implementation
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
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