Skip to content

Commit 95ad3f6

Browse files
committed
minor optimizations, code comments
1 parent 2fcb3ee commit 95ad3f6

File tree

1 file changed

+41
-16
lines changed

1 file changed

+41
-16
lines changed

index.js

Lines changed: 41 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,30 +7,45 @@
77

88
'use strict';
99

10-
module.exports = function regexCache(fn, str, options, nocompare) {
10+
/**
11+
* Expose `regexCache`
12+
*/
13+
14+
module.exports = regexCache;
15+
16+
/**
17+
* Memoize the results of a call to the new RegExp constructor.
18+
*
19+
* @param {Function} fn [description]
20+
* @param {String} str [description]
21+
* @param {Options} options [description]
22+
* @param {Boolean} nocompare [description]
23+
* @return {RegExp}
24+
*/
25+
26+
function regexCache(fn, str, options, nocompare) {
1127
var regex, cached;
12-
if (arguments.length === 1) {
28+
29+
// `str` might be explicitly defined as `null`
30+
if (str === null || arguments.length === 1) {
31+
str = '_default_';
1332
nocompare = true;
1433
options = null;
1534
str = null;
1635
}
1736

18-
if (str === null) {
19-
str = '__default';
20-
}
21-
2237
if (cache.hasOwnProperty(str)) {
2338
cached = cache[str];
24-
if (nocompare) {
25-
return cached.regex;
26-
}
39+
// return early without comparing options
40+
if (nocompare) { return cached.regex; }
2741

42+
// otherwise, compare options first
2843
if (equal(cached.opts, options)) {
2944
return cached.regex;
3045
}
3146
}
3247

33-
if (str === '__default') {
48+
if (str === '_default_') {
3449
regex = fn(options);
3550
} else {
3651
regex = fn(str, options);
@@ -40,20 +55,30 @@ module.exports = function regexCache(fn, str, options, nocompare) {
4055
return regex;
4156
};
4257

58+
/**
59+
* Cache a `str` with the given `opts` and
60+
* generated `regex`.
61+
*
62+
* @param {String} `str`
63+
* @param {Object} `opts`
64+
* @param {RegExp} `regex`
65+
*/
66+
4367
function memo(str, opts, regex) {
4468
cache[str] = {regex: regex, opts: opts};
4569
}
4670

4771
var cache = module.exports.cache = {};
4872

4973
/**
50-
* Return false if object A is different (enough)
51-
* from object B.
74+
* Return false if object A is different (enough) from object B.
75+
*
76+
* When creating the regex, memoization is used to increase
77+
* performance. This function tells us if options have changed
78+
* so we can generate a new regex instead of using the cached one.
5279
*
53-
* When creating the regex memoization is used
54-
* to increase performance. This function tells
55-
* us if options have changed so we can generate
56-
* a new regex instead of using the cached one.
80+
* It seems like a lot of logic but in most cases this function
81+
* returns early.
5782
*
5883
* @param {Object} `a` cached options
5984
* @param {Object} `b` passed options

0 commit comments

Comments
 (0)