index.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /*!
  2. * to-regex-range <https://github.com/jonschlinkert/to-regex-range>
  3. *
  4. * Copyright (c) 2015, 2017, Jon Schlinkert.
  5. * Released under the MIT License.
  6. */
  7. 'use strict';
  8. var repeat = require('repeat-string');
  9. var isNumber = require('is-number');
  10. var cache = {};
  11. function toRegexRange(min, max, options) {
  12. if (isNumber(min) === false) {
  13. throw new RangeError('toRegexRange: first argument is invalid.');
  14. }
  15. if (typeof max === 'undefined' || min === max) {
  16. return String(min);
  17. }
  18. if (isNumber(max) === false) {
  19. throw new RangeError('toRegexRange: second argument is invalid.');
  20. }
  21. options = options || {};
  22. var relax = String(options.relaxZeros);
  23. var shorthand = String(options.shorthand);
  24. var capture = String(options.capture);
  25. var key = min + ':' + max + '=' + relax + shorthand + capture;
  26. if (cache.hasOwnProperty(key)) {
  27. return cache[key].result;
  28. }
  29. var a = Math.min(min, max);
  30. var b = Math.max(min, max);
  31. if (Math.abs(a - b) === 1) {
  32. var result = min + '|' + max;
  33. if (options.capture) {
  34. return '(' + result + ')';
  35. }
  36. return result;
  37. }
  38. var isPadded = padding(min) || padding(max);
  39. var positives = [];
  40. var negatives = [];
  41. var tok = {min: min, max: max, a: a, b: b};
  42. if (isPadded) {
  43. tok.isPadded = isPadded;
  44. tok.maxLen = String(tok.max).length;
  45. }
  46. if (a < 0) {
  47. var newMin = b < 0 ? Math.abs(b) : 1;
  48. var newMax = Math.abs(a);
  49. negatives = splitToPatterns(newMin, newMax, tok, options);
  50. a = tok.a = 0;
  51. }
  52. if (b >= 0) {
  53. positives = splitToPatterns(a, b, tok, options);
  54. }
  55. tok.negatives = negatives;
  56. tok.positives = positives;
  57. tok.result = siftPatterns(negatives, positives, options);
  58. if (options.capture && (positives.length + negatives.length) > 1) {
  59. tok.result = '(' + tok.result + ')';
  60. }
  61. cache[key] = tok;
  62. return tok.result;
  63. }
  64. function siftPatterns(neg, pos, options) {
  65. var onlyNegative = filterPatterns(neg, pos, '-', false, options) || [];
  66. var onlyPositive = filterPatterns(pos, neg, '', false, options) || [];
  67. var intersected = filterPatterns(neg, pos, '-?', true, options) || [];
  68. var subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
  69. return subpatterns.join('|');
  70. }
  71. function splitToRanges(min, max) {
  72. min = Number(min);
  73. max = Number(max);
  74. var nines = 1;
  75. var stops = [max];
  76. var stop = +countNines(min, nines);
  77. while (min <= stop && stop <= max) {
  78. stops = push(stops, stop);
  79. nines += 1;
  80. stop = +countNines(min, nines);
  81. }
  82. var zeros = 1;
  83. stop = countZeros(max + 1, zeros) - 1;
  84. while (min < stop && stop <= max) {
  85. stops = push(stops, stop);
  86. zeros += 1;
  87. stop = countZeros(max + 1, zeros) - 1;
  88. }
  89. stops.sort(compare);
  90. return stops;
  91. }
  92. /**
  93. * Convert a range to a regex pattern
  94. * @param {Number} `start`
  95. * @param {Number} `stop`
  96. * @return {String}
  97. */
  98. function rangeToPattern(start, stop, options) {
  99. if (start === stop) {
  100. return {pattern: String(start), digits: []};
  101. }
  102. var zipped = zip(String(start), String(stop));
  103. var len = zipped.length, i = -1;
  104. var pattern = '';
  105. var digits = 0;
  106. while (++i < len) {
  107. var numbers = zipped[i];
  108. var startDigit = numbers[0];
  109. var stopDigit = numbers[1];
  110. if (startDigit === stopDigit) {
  111. pattern += startDigit;
  112. } else if (startDigit !== '0' || stopDigit !== '9') {
  113. pattern += toCharacterClass(startDigit, stopDigit);
  114. } else {
  115. digits += 1;
  116. }
  117. }
  118. if (digits) {
  119. pattern += options.shorthand ? '\\d' : '[0-9]';
  120. }
  121. return { pattern: pattern, digits: [digits] };
  122. }
  123. function splitToPatterns(min, max, tok, options) {
  124. var ranges = splitToRanges(min, max);
  125. var len = ranges.length;
  126. var idx = -1;
  127. var tokens = [];
  128. var start = min;
  129. var prev;
  130. while (++idx < len) {
  131. var range = ranges[idx];
  132. var obj = rangeToPattern(start, range, options);
  133. var zeros = '';
  134. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  135. if (prev.digits.length > 1) {
  136. prev.digits.pop();
  137. }
  138. prev.digits.push(obj.digits[0]);
  139. prev.string = prev.pattern + toQuantifier(prev.digits);
  140. start = range + 1;
  141. continue;
  142. }
  143. if (tok.isPadded) {
  144. zeros = padZeros(range, tok);
  145. }
  146. obj.string = zeros + obj.pattern + toQuantifier(obj.digits);
  147. tokens.push(obj);
  148. start = range + 1;
  149. prev = obj;
  150. }
  151. return tokens;
  152. }
  153. function filterPatterns(arr, comparison, prefix, intersection, options) {
  154. var res = [];
  155. for (var i = 0; i < arr.length; i++) {
  156. var tok = arr[i];
  157. var ele = tok.string;
  158. if (options.relaxZeros !== false) {
  159. if (prefix === '-' && ele.charAt(0) === '0') {
  160. if (ele.charAt(1) === '{') {
  161. ele = '0*' + ele.replace(/^0\{\d+\}/, '');
  162. } else {
  163. ele = '0*' + ele.slice(1);
  164. }
  165. }
  166. }
  167. if (!intersection && !contains(comparison, 'string', ele)) {
  168. res.push(prefix + ele);
  169. }
  170. if (intersection && contains(comparison, 'string', ele)) {
  171. res.push(prefix + ele);
  172. }
  173. }
  174. return res;
  175. }
  176. /**
  177. * Zip strings (`for in` can be used on string characters)
  178. */
  179. function zip(a, b) {
  180. var arr = [];
  181. for (var ch in a) arr.push([a[ch], b[ch]]);
  182. return arr;
  183. }
  184. function compare(a, b) {
  185. return a > b ? 1 : b > a ? -1 : 0;
  186. }
  187. function push(arr, ele) {
  188. if (arr.indexOf(ele) === -1) arr.push(ele);
  189. return arr;
  190. }
  191. function contains(arr, key, val) {
  192. for (var i = 0; i < arr.length; i++) {
  193. if (arr[i][key] === val) {
  194. return true;
  195. }
  196. }
  197. return false;
  198. }
  199. function countNines(min, len) {
  200. return String(min).slice(0, -len) + repeat('9', len);
  201. }
  202. function countZeros(integer, zeros) {
  203. return integer - (integer % Math.pow(10, zeros));
  204. }
  205. function toQuantifier(digits) {
  206. var start = digits[0];
  207. var stop = digits[1] ? (',' + digits[1]) : '';
  208. if (!stop && (!start || start === 1)) {
  209. return '';
  210. }
  211. return '{' + start + stop + '}';
  212. }
  213. function toCharacterClass(a, b) {
  214. return '[' + a + ((b - a === 1) ? '' : '-') + b + ']';
  215. }
  216. function padding(str) {
  217. return /^-?(0+)\d/.exec(str);
  218. }
  219. function padZeros(val, tok) {
  220. if (tok.isPadded) {
  221. var diff = Math.abs(tok.maxLen - String(val).length);
  222. switch (diff) {
  223. case 0:
  224. return '';
  225. case 1:
  226. return '0';
  227. default: {
  228. return '0{' + diff + '}';
  229. }
  230. }
  231. }
  232. return val;
  233. }
  234. /**
  235. * Expose `toRegexRange`
  236. */
  237. module.exports = toRegexRange;