2 * to-regex-range <https://github.com/micromatch/to-regex-range>
4 * Copyright (c) 2015-present, Jon Schlinkert.
5 * Released under the MIT License.
10 const isNumber = require('is-number');
12 const toRegexRange = (min, max, options) => {
13 if (isNumber(min) === false) {
14 throw new TypeError('toRegexRange: expected the first argument to be a number');
17 if (max === void 0 || min === max) {
21 if (isNumber(max) === false) {
22 throw new TypeError('toRegexRange: expected the second argument to be a number.');
25 let opts = { relaxZeros: true, ...options };
26 if (typeof opts.strictZeros === 'boolean') {
27 opts.relaxZeros = opts.strictZeros === false;
30 let relax = String(opts.relaxZeros);
31 let shorthand = String(opts.shorthand);
32 let capture = String(opts.capture);
33 let wrap = String(opts.wrap);
34 let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
36 if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
37 return toRegexRange.cache[cacheKey].result;
40 let a = Math.min(min, max);
41 let b = Math.max(min, max);
43 if (Math.abs(a - b) === 1) {
44 let result = min + '|' + max;
48 if (opts.wrap === false) {
51 return `(?:${result})`;
54 let isPadded = hasPadding(min) || hasPadding(max);
55 let state = { min, max, a, b };
60 state.isPadded = isPadded;
61 state.maxLen = String(state.max).length;
65 let newMin = b < 0 ? Math.abs(b) : 1;
66 negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
71 positives = splitToPatterns(a, b, state, opts);
74 state.negatives = negatives;
75 state.positives = positives;
76 state.result = collatePatterns(negatives, positives, opts);
78 if (opts.capture === true) {
79 state.result = `(${state.result})`;
80 } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
81 state.result = `(?:${state.result})`;
84 toRegexRange.cache[cacheKey] = state;
88 function collatePatterns(neg, pos, options) {
89 let onlyNegative = filterPatterns(neg, pos, '-', false, options) || [];
90 let onlyPositive = filterPatterns(pos, neg, '', false, options) || [];
91 let intersected = filterPatterns(neg, pos, '-?', true, options) || [];
92 let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
93 return subpatterns.join('|');
96 function splitToRanges(min, max) {
100 let stop = countNines(min, nines);
101 let stops = new Set([max]);
103 while (min <= stop && stop <= max) {
106 stop = countNines(min, nines);
109 stop = countZeros(max + 1, zeros) - 1;
111 while (min < stop && stop <= max) {
114 stop = countZeros(max + 1, zeros) - 1;
123 * Convert a range to a regex pattern
124 * @param {Number} `start`
125 * @param {Number} `stop`
129 function rangeToPattern(start, stop, options) {
130 if (start === stop) {
131 return { pattern: start, count: [], digits: 0 };
134 let zipped = zip(start, stop);
135 let digits = zipped.length;
139 for (let i = 0; i < digits; i++) {
140 let [startDigit, stopDigit] = zipped[i];
142 if (startDigit === stopDigit) {
143 pattern += startDigit;
145 } else if (startDigit !== '0' || stopDigit !== '9') {
146 pattern += toCharacterClass(startDigit, stopDigit, options);
154 pattern += options.shorthand === true ? '\\d' : '[0-9]';
157 return { pattern, count: [count], digits };
160 function splitToPatterns(min, max, tok, options) {
161 let ranges = splitToRanges(min, max);
166 for (let i = 0; i < ranges.length; i++) {
168 let obj = rangeToPattern(String(start), String(max), options);
171 if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
172 if (prev.count.length > 1) {
176 prev.count.push(obj.count[0]);
177 prev.string = prev.pattern + toQuantifier(prev.count);
183 zeros = padZeros(max, tok, options);
186 obj.string = zeros + obj.pattern + toQuantifier(obj.count);
195 function filterPatterns(arr, comparison, prefix, intersection, options) {
198 for (let ele of arr) {
199 let { string } = ele;
201 // only push if _both_ are negative...
202 if (!intersection && !contains(comparison, 'string', string)) {
203 result.push(prefix + string);
206 // or _both_ are positive
207 if (intersection && contains(comparison, 'string', string)) {
208 result.push(prefix + string);
220 for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
224 function compare(a, b) {
225 return a > b ? 1 : b > a ? -1 : 0;
228 function contains(arr, key, val) {
229 return arr.some(ele => ele[key] === val);
232 function countNines(min, len) {
233 return Number(String(min).slice(0, -len) + '9'.repeat(len));
236 function countZeros(integer, zeros) {
237 return integer - (integer % Math.pow(10, zeros));
240 function toQuantifier(digits) {
241 let [start = 0, stop = ''] = digits;
242 if (stop || start > 1) {
243 return `{${start + (stop ? ',' + stop : '')}}`;
248 function toCharacterClass(a, b, options) {
249 return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
252 function hasPadding(str) {
253 return /^-?(0+)\d/.test(str);
256 function padZeros(value, tok, options) {
261 let diff = Math.abs(tok.maxLen - String(value).length);
262 let relax = options.relaxZeros !== false;
268 return relax ? '0?' : '0';
270 return relax ? '0{0,2}' : '00';
272 return relax ? `0{0,${diff}}` : `0{${diff}}`;
281 toRegexRange.cache = {};
282 toRegexRange.clearCache = () => (toRegexRange.cache = {});
285 * Expose `toRegexRange`
288 module.exports = toRegexRange;