1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | 'use strict';
|
9 |
|
10 | var equal = require('is-equal-shallow');
|
11 | var basic = {};
|
12 | var cache = {};
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | module.exports = regexCache;
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 | function regexCache(fn, str, opts) {
|
31 | var key = '_default_', regex, cached;
|
32 |
|
33 | if (!str && !opts) {
|
34 | if (typeof fn !== 'function') {
|
35 | return fn;
|
36 | }
|
37 | return basic[key] || (basic[key] = fn(str));
|
38 | }
|
39 |
|
40 | var isString = typeof str === 'string';
|
41 | if (isString) {
|
42 | if (!opts) {
|
43 | return basic[str] || (basic[str] = fn(str));
|
44 | }
|
45 | key = str;
|
46 | } else {
|
47 | opts = str;
|
48 | }
|
49 |
|
50 | cached = cache[key];
|
51 | if (cached && equal(cached.opts, opts)) {
|
52 | return cached.regex;
|
53 | }
|
54 |
|
55 | memo(key, opts, (regex = fn(str, opts)));
|
56 | return regex;
|
57 | }
|
58 |
|
59 | function memo(key, opts, regex) {
|
60 | cache[key] = {regex: regex, opts: opts};
|
61 | }
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 | module.exports.cache = cache;
|
68 | module.exports.basic = basic;
|