UNPKG

1.29 kBJavaScriptView Raw
1/*!
2 * regex-cache <https://github.com/jonschlinkert/regex-cache>
3 *
4 * Copyright (c) 2015-2017, Jon Schlinkert.
5 * Released under the MIT License.
6 */
7
8'use strict';
9
10var equal = require('is-equal-shallow');
11var basic = {};
12var cache = {};
13
14/**
15 * Expose `regexCache`
16 */
17
18module.exports = regexCache;
19
20/**
21 * Memoize the results of a call to the new RegExp constructor.
22 *
23 * @param {Function} fn [description]
24 * @param {String} str [description]
25 * @param {Options} options [description]
26 * @param {Boolean} nocompare [description]
27 * @return {RegExp}
28 */
29
30function 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
59function memo(key, opts, regex) {
60 cache[key] = {regex: regex, opts: opts};
61}
62
63/**
64 * Expose `cache`
65 */
66
67module.exports.cache = cache;
68module.exports.basic = basic;