Last active
August 29, 2015 14:18
-
-
Save obenjiro/3fad96d58fe83e4b01a1 to your computer and use it in GitHub Desktop.
Visitor Pattern in JavaScript
This file contains hidden or 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 calc = { | |
| add: function (node) { | |
| return visit(node.l) + visit(node.r); | |
| }, | |
| sub: function (node) { | |
| return visit(node.l) - visit(node.r); | |
| }, | |
| val: function (node) { | |
| return node.val; | |
| } | |
| }; | |
| var dump = { | |
| add: function (node) { | |
| return visit(node.l) + ' + ' + visit(node.r); | |
| }, | |
| sub: function (node) { | |
| return visit(node.l) + ' - ' + visit(node.r); | |
| }, | |
| val: function (node) { | |
| return String(node.val); | |
| } | |
| }; | |
| var convert = { | |
| add: function (node) { | |
| var currentNode = {n:node.tag}; | |
| currentNode.content = currentNode.content || []; | |
| currentNode.content.push(visit(node.l)); | |
| currentNode.content.push(visit(node.r)); | |
| return currentNode; | |
| }, | |
| sub: function (node) { | |
| var currentNode = {n:node.tag}; | |
| currentNode.content = currentNode.content || []; | |
| currentNode.content.push(visit(node.l)); | |
| currentNode.content.push(visit(node.r)); | |
| return currentNode; | |
| }, | |
| val: function (node) { | |
| var currentNode = {n:node.tag, v: node.val}; | |
| return currentNode; | |
| } | |
| }; | |
| var root = { | |
| tag: 'add', | |
| l: { | |
| tag: 'val', | |
| val: 2 | |
| }, | |
| r: { | |
| tag: 'sub', | |
| l: { | |
| tag: 'val', | |
| val: 3 | |
| }, | |
| r: { | |
| tag: 'val', | |
| val: 1 | |
| } | |
| } | |
| }; | |
| var visit = (function() { | |
| var currentVisitor; | |
| return function(node, visitor) { | |
| currentVisitor = visitor || currentVisitor; | |
| return currentVisitor[node.tag](node); | |
| }; | |
| })(); | |
| console.log(visit(root, calc)); | |
| console.log(visit(root, dump)); | |
| console.log(JSON.stringify(visit(root, convert), null, 4)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment