Skip to content

Commit 26a74af

Browse files
committed
refactor again
1 parent 04ab6fc commit 26a74af

File tree

1 file changed

+85
-12
lines changed

1 file changed

+85
-12
lines changed

index.js

Lines changed: 85 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -25,28 +25,101 @@ module.exports = regexCache;
2525
* @return {RegExp}
2626
*/
2727

28-
function regexCache(fn, str, options) {
29-
var key = '_default_';
28+
// function regexCache(fn, str, options) {
29+
// var key = '_default_', regex;
3030

31-
if (!str) {
32-
return cache[key] || (cache[key] = fn());
31+
// if (!str) {
32+
// if (cache[key]) {
33+
// return cache[key].regex;
34+
// }
35+
// memo(key, null, (regex = fn()));
36+
// return regex;
37+
// }
38+
39+
// if (!options) {
40+
// key = typeof str === 'string' ? str : key = toKey(str);
41+
42+
// if (cache[key]) {
43+
// return cache[key].regex;
44+
// }
45+
// memo(key, null, (regex = fn(str)));
46+
// return regex;
47+
// }
48+
49+
// key = str + toKey(options);
50+
// if (cache[key]) {
51+
// return cache[key].regex;
52+
// }
53+
54+
// memo(key, null, (regex = fn(str, options)));
55+
// return regex;
56+
// }
57+
58+
function regexCache(fn, str, opts) {
59+
var key = '_default_', regex, cached;
60+
61+
if (!str && !opts) {
62+
if (typeof fn !== 'function') {
63+
return fn;
64+
}
65+
return basic[key] || (basic[key] = fn());
66+
}
67+
68+
var isString = typeof str === 'string';
69+
if (isString) {
70+
key = str;
71+
} else {
72+
opts = str;
3373
}
3474

35-
if (!options) {
36-
if (typeof str === 'string') {
37-
return cache[str] || (cache[str] = fn(str));
38-
} else {
39-
key = toKey(str);
40-
return cache[key] || (cache[key] = fn(str));
75+
if (!opts) {
76+
if (isString) {
77+
return basic[key] || (basic[key] = fn(key));
4178
}
79+
80+
// else, `str` is an object
81+
// cached = cache[key];
82+
// opts = str;
83+
84+
// if (cached && equal(cached.opts, opts)) {
85+
// return cached.regex;
86+
// }
87+
88+
// memo(key, opts, (regex = fn(str)));
89+
// return regex;
90+
}
91+
92+
cached = cache[key];
93+
if (cached && equal(cached.opts, opts)) {
94+
return cached.regex;
4295
}
4396

44-
key = str + toKey(options);
45-
return cache[key] || (cache[key] = fn(str, options));
97+
memo(key, opts, (regex = fn(str, opts)));
98+
return regex;
99+
}
100+
101+
function memo(key, opts, regex) {
102+
cache[key] = {regex: regex, opts: opts};
103+
}
104+
105+
function equal(a, b) {
106+
for (var key in b) {
107+
if (!a[key]) {
108+
return false;
109+
}
110+
if (a[key] !== b[key]) {
111+
return false;
112+
}
113+
if (typeof b[key] === 'object') {
114+
return false;
115+
}
116+
}
117+
return true;
46118
}
47119

48120
/**
49121
* Expose `cache`
50122
*/
51123

52124
var cache = module.exports.cache = {};
125+
var basic = module.exports.basic = {};

0 commit comments

Comments
 (0)