Initial commit
[yaffs-website] / node_modules / regex-cache / index.js
1 /*!
2  * regex-cache <https://github.com/jonschlinkert/regex-cache>
3  *
4  * Copyright (c) 2015 Jon Schlinkert.
5  * Licensed under the MIT license.
6  */
7
8 'use strict';
9
10 var isPrimitive = require('is-primitive');
11 var equal = require('is-equal-shallow');
12 var basic = {};
13 var cache = {};
14
15 /**
16  * Expose `regexCache`
17  */
18
19 module.exports = regexCache;
20
21 /**
22  * Memoize the results of a call to the new RegExp constructor.
23  *
24  * @param  {Function} fn [description]
25  * @param  {String} str [description]
26  * @param  {Options} options [description]
27  * @param  {Boolean} nocompare [description]
28  * @return {RegExp}
29  */
30
31 function regexCache(fn, str, opts) {
32   var key = '_default_', regex, cached;
33
34   if (!str && !opts) {
35     if (typeof fn !== 'function') {
36       return fn;
37     }
38     return basic[key] || (basic[key] = fn(str));
39   }
40
41   var isString = typeof str === 'string';
42   if (isString) {
43     if (!opts) {
44       return basic[str] || (basic[str] = fn(str));
45     }
46     key = str;
47   } else {
48     opts = str;
49   }
50
51   cached = cache[key];
52   if (cached && equal(cached.opts, opts)) {
53     return cached.regex;
54   }
55
56   memo(key, opts, (regex = fn(str, opts)));
57   return regex;
58 }
59
60 function memo(key, opts, regex) {
61   cache[key] = {regex: regex, opts: opts};
62 }
63
64 /**
65  * Expose `cache`
66  */
67
68 module.exports.cache = cache;
69 module.exports.basic = basic;