1 |
3a515b92
|
cagy
|
'use strict';
|
2 |
|
|
|
3 |
|
|
var regex = require('regex-not');
|
4 |
|
|
var Cache = require('fragment-cache');
|
5 |
|
|
|
6 |
|
|
/**
|
7 |
|
|
* Utils
|
8 |
|
|
*/
|
9 |
|
|
|
10 |
|
|
var utils = module.exports;
|
11 |
|
|
var cache = utils.cache = new Cache();
|
12 |
|
|
|
13 |
|
|
/**
|
14 |
|
|
* Cast `val` to an array
|
15 |
|
|
* @return {Array}
|
16 |
|
|
*/
|
17 |
|
|
|
18 |
|
|
utils.arrayify = function(val) {
|
19 |
|
|
if (!Array.isArray(val)) {
|
20 |
|
|
return [val];
|
21 |
|
|
}
|
22 |
|
|
return val;
|
23 |
|
|
};
|
24 |
|
|
|
25 |
|
|
/**
|
26 |
|
|
* Memoize a generated regex or function
|
27 |
|
|
*/
|
28 |
|
|
|
29 |
|
|
utils.memoize = function(type, pattern, options, fn) {
|
30 |
|
|
var key = utils.createKey(type + pattern, options);
|
31 |
|
|
|
32 |
|
|
if (cache.has(type, key)) {
|
33 |
|
|
return cache.get(type, key);
|
34 |
|
|
}
|
35 |
|
|
|
36 |
|
|
var val = fn(pattern, options);
|
37 |
|
|
if (options && options.cache === false) {
|
38 |
|
|
return val;
|
39 |
|
|
}
|
40 |
|
|
|
41 |
|
|
cache.set(type, key, val);
|
42 |
|
|
return val;
|
43 |
|
|
};
|
44 |
|
|
|
45 |
|
|
/**
|
46 |
|
|
* Create the key to use for memoization. The key is generated
|
47 |
|
|
* by iterating over the options and concatenating key-value pairs
|
48 |
|
|
* to the pattern string.
|
49 |
|
|
*/
|
50 |
|
|
|
51 |
|
|
utils.createKey = function(pattern, options) {
|
52 |
|
|
var key = pattern;
|
53 |
|
|
if (typeof options === 'undefined') {
|
54 |
|
|
return key;
|
55 |
|
|
}
|
56 |
|
|
for (var prop in options) {
|
57 |
|
|
key += ';' + prop + '=' + String(options[prop]);
|
58 |
|
|
}
|
59 |
|
|
return key;
|
60 |
|
|
};
|
61 |
|
|
|
62 |
|
|
/**
|
63 |
|
|
* Create the regex to use for matching text
|
64 |
|
|
*/
|
65 |
|
|
|
66 |
|
|
utils.createRegex = function(str) {
|
67 |
|
|
var opts = {contains: true, strictClose: false};
|
68 |
|
|
return regex(str, opts);
|
69 |
|
|
};
|