-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
98 lines (88 loc) · 2.09 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
'use strict';
/**
* Module dependencies
*/
const assert = require('assert');
const Emitter = require('@sellside/emitter');
const use = require('use');
/**
* Create a new `Handlers` with the given `options`.
*
* ```js
* const Handlers = require('snapdragon-handlers');
* class Lexer extends Handlers {
* constructor(options) {
* super(options);
* // do lexer stuff
* }
* }
* ```
* @name Handlers
* @param {Object} `options`
* @api public
*/
class Handlers extends Emitter {
constructor(options) {
super();
this.options = Object.assign({}, options);
this.handlers = {};
this.types = [];
use(this);
}
/**
* Register a handler function.
*
* ```js
* handlers.set('star', function() {
* // do parser, lexer, or compiler stuff
* });
* ```
* @name .set
* @param {String} `type`
* @param {Function} `fn` The handler function to register.
* @api public
*/
set(type, handler) {
assert.equal(typeof handler, 'function', 'expected a function');
assert.equal(typeof type, 'string', 'expected a string');
if (this.types.indexOf(type) === -1) {
this.types.push(type);
}
const self = this;
const fn = function() {
if (self.isLexer && self.constructor.isLexer(this)) {
return handler.apply(this, arguments);
}
return handler.apply(self, arguments);
};
if (handler.name) {
Reflect.defineProperty(fn, 'name', {value: handler.name});
}
this.handlers[type] = fn;
return this;
}
/**
* Get a registered handler function.
*
* ```js
* handlers.set('star', function() {
* // do parser, lexer, or compiler stuff
* });
* const star = handlers.get('star');
* ```
* @name .get
* @param {String} `type`
* @param {Function} `fn` The handler function to register.
* @api public
*/
get(type) {
const handler = this.handlers[type] || this.handlers.default;
assert.equal(typeof handler, 'function', 'expected handler to be a function');
return handler;
}
};
/**
* Expose `Handlers`
* @type {Function}
*/
module.exports = Handlers;