-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathindex.js
108 lines (98 loc) · 2.14 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
99
100
101
102
103
104
105
106
107
108
'use strict';
/**
* Create new transform function
*
* @constructor
* @return {object:{exec:fn,use:fn}}
* @return {fn:exec}
* @api public
*/
module.exports = function textr(defaults) {
/**
* list of registred middlewares
* @api public
*/
var mws = [];
/**
* Default options will be passed to each middleware as second param.
* You can redefine props by passing your options to `tf.exec()` as second arg.
* @api private
*/
defaults = defaults || {};
/**
* expose public interface of the textr
*
* @example
*
* // functional style
* text = textr()
* // register plugins
* .use(quotes)
* .use(capitalize)
* .exec(text)
*
* // save transformer to reuse
* tf = textr()
* // register plugins
* .use(quotes, elipses, capitalize)
* ;
* return ['Hello', 'world'].map(tf);
*
* @constructor
* @alias exec
*/
function api() {
return exec.apply(null, arguments);
}
/**
* Expose `exec`, `use` and `mws` as properties
* of the `api`
*
* @alias exec
* @alias use
* @alias mws
*/
api.exec = exec;
api.use = use;
api.mws = mws;
return api;
/**
* process given text by the middlewares
* @param {string} text
* @param {Object} options Options to merge with defaults
* @return {string} text
* @api public
*/
function exec(text, options) {
options = clone(defaults, options);
var l = mws.length;
for (var i = 0; i < l; i++) {
text = mws[i].apply(text, [text, options]) || text;
}
return text;
}
/**
* Register new middleware and array of middlewares
* @param {...fn} ...middlewares
* @return {api}
* @api public
*/
function use() {
[].push.apply(mws, arguments);
return api;
}
};
/**
* merge given objects to new one. Returns clone
* @param {Object} ...objects Objects to clone into the one new
* @return {Object}
*/
function clone() {
var res = {};
var length = arguments.length;
for (var i = 0; i < length; i++) {
var obj = arguments[i];
for (var k in obj) { res[k] = obj[k]; }
}
return res;
}