Skip to content

Instantly share code, notes, and snippets.

@asvny
Forked from nakamura-to/gist:2144314
Created June 29, 2016 15:27
Show Gist options
  • Save asvny/dd9aefc524f11d97fe6755bd7ac44246 to your computer and use it in GitHub Desktop.
Save asvny/dd9aefc524f11d97fe6755bd7ac44246 to your computer and use it in GitHub Desktop.
Visitor Pattern in JavaScript
// 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