Created
          March 21, 2012 04:22 
        
      - 
      
- 
        Save nakamura-to/2144314 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
    
  
  
    
  | // see http://d.hatena.ne.jp/ashigeru/20090113/1231855642 | |
| var calc = { | |
| add: function (node) { | |
| return visit(this, node.l) + visit(this, node.r); | |
| }, | |
| sub: function (node) { | |
| return visit(this, node.l) - visit(this, node.r); | |
| }, | |
| val: function (node) { | |
| return node.val; | |
| } | |
| }; | |
| 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); | |
| }, | |
| val: function (node) { | |
| return String(node.val); | |
| } | |
| }; | |
| var node = {tag: 'add', | |
| l: {tag: 'val', val: 2}, | |
| r: {tag: 'sub', | |
| l: {tag: 'val', val: 3}, | |
| r: {tag: 'val', val: 1} | |
| } | |
| }; | |
| function visit(visitor, node) { | |
| return visitor[node.tag].call(visitor, node); | |
| } | |
| console.log(visit(calc, node)); | |
| console.log(visit(dump, node)); | |
| // 4 | |
| // 2 + 3 - 1 | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment