UNPKG

route-parser

Version:

A isomorphic, bullet-proof, ninja-ready route parsing, matching, and reversing library for Javascript in Node and the browser.

38 lines (33 loc) 1.11 kB
'use strict'; /** * @module route/visitors/create_visitor */ var nodeTypes = Object.keys(require('../nodes')); /** * Helper for creating visitors. Take an object of node name to handler * mappings, returns an object with a "visit" method that can be called * @param {Object.<string,function(node,context)>} handlers A mapping of node * type to visitor functions * @return {{visit: function(node,context)}} A visitor object with a "visit" * method that can be called on a node with a context */ function createVisitor(handlers) { nodeTypes.forEach(function(nodeType) { if( typeof handlers[nodeType] === 'undefined') { throw new Error('No handler defined for ' + nodeType.displayName); } }); return { /** * Call the given handler for this node type * @param {Object} node the AST node * @param {Object} context context to pass through to handlers * @return {Object} */ visit: function(node, context) { return this.handlers[node.displayName].call(this,node, context); }, handlers: handlers }; } module.exports = createVisitor;