compileBooleanMatcher.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /**
  7. * @param {string} str string
  8. * @returns {string} quoted meta
  9. */
  10. const quoteMeta = str => {
  11. return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&");
  12. };
  13. /**
  14. * @param {string} str string
  15. * @returns {string} string
  16. */
  17. const toSimpleString = str => {
  18. if (`${+str}` === str) {
  19. return str;
  20. }
  21. return JSON.stringify(str);
  22. };
  23. /**
  24. * @param {Record<string|number, boolean>} map value map
  25. * @returns {boolean|(function(string): string)} true/false, when unconditionally true/false, or a template function to determine the value at runtime
  26. */
  27. const compileBooleanMatcher = map => {
  28. const positiveItems = Object.keys(map).filter(i => map[i]);
  29. const negativeItems = Object.keys(map).filter(i => !map[i]);
  30. if (positiveItems.length === 0) return false;
  31. if (negativeItems.length === 0) return true;
  32. return compileBooleanMatcherFromLists(positiveItems, negativeItems);
  33. };
  34. /**
  35. * @param {string[]} positiveItems positive items
  36. * @param {string[]} negativeItems negative items
  37. * @returns {function(string): string} a template function to determine the value at runtime
  38. */
  39. const compileBooleanMatcherFromLists = (positiveItems, negativeItems) => {
  40. if (positiveItems.length === 0) return () => "false";
  41. if (negativeItems.length === 0) return () => "true";
  42. if (positiveItems.length === 1)
  43. return value => `${toSimpleString(positiveItems[0])} == ${value}`;
  44. if (negativeItems.length === 1)
  45. return value => `${toSimpleString(negativeItems[0])} != ${value}`;
  46. const positiveRegexp = itemsToRegexp(positiveItems);
  47. const negativeRegexp = itemsToRegexp(negativeItems);
  48. if (positiveRegexp.length <= negativeRegexp.length) {
  49. return value => `/^${positiveRegexp}$/.test(${value})`;
  50. } else {
  51. return value => `!/^${negativeRegexp}$/.test(${value})`;
  52. }
  53. };
  54. /**
  55. * @param {Set<string>} itemsSet items set
  56. * @param {(str: string) => string | false} getKey get key function
  57. * @param {(str: Array<string>) => boolean} condition condition
  58. * @returns {Array<Array<string>>} list of common items
  59. */
  60. const popCommonItems = (itemsSet, getKey, condition) => {
  61. /** @type {Map<string, Array<string>>} */
  62. const map = new Map();
  63. for (const item of itemsSet) {
  64. const key = getKey(item);
  65. if (key) {
  66. let list = map.get(key);
  67. if (list === undefined) {
  68. /** @type {Array<string>} */
  69. list = [];
  70. map.set(key, list);
  71. }
  72. list.push(item);
  73. }
  74. }
  75. /** @type {Array<Array<string>>} */
  76. const result = [];
  77. for (const list of map.values()) {
  78. if (condition(list)) {
  79. for (const item of list) {
  80. itemsSet.delete(item);
  81. }
  82. result.push(list);
  83. }
  84. }
  85. return result;
  86. };
  87. /**
  88. * @param {Array<string>} items items
  89. * @returns {string} common prefix
  90. */
  91. const getCommonPrefix = items => {
  92. let prefix = items[0];
  93. for (let i = 1; i < items.length; i++) {
  94. const item = items[i];
  95. for (let p = 0; p < prefix.length; p++) {
  96. if (item[p] !== prefix[p]) {
  97. prefix = prefix.slice(0, p);
  98. break;
  99. }
  100. }
  101. }
  102. return prefix;
  103. };
  104. /**
  105. * @param {Array<string>} items items
  106. * @returns {string} common suffix
  107. */
  108. const getCommonSuffix = items => {
  109. let suffix = items[0];
  110. for (let i = 1; i < items.length; i++) {
  111. const item = items[i];
  112. for (let p = item.length - 1, s = suffix.length - 1; s >= 0; p--, s--) {
  113. if (item[p] !== suffix[s]) {
  114. suffix = suffix.slice(s + 1);
  115. break;
  116. }
  117. }
  118. }
  119. return suffix;
  120. };
  121. /**
  122. * @param {Array<string>} itemsArr array of items
  123. * @returns {string} regexp
  124. */
  125. const itemsToRegexp = itemsArr => {
  126. if (itemsArr.length === 1) {
  127. return quoteMeta(itemsArr[0]);
  128. }
  129. /** @type {Array<string>} */
  130. const finishedItems = [];
  131. // merge single char items: (a|b|c|d|ef) => ([abcd]|ef)
  132. let countOfSingleCharItems = 0;
  133. for (const item of itemsArr) {
  134. if (item.length === 1) {
  135. countOfSingleCharItems++;
  136. }
  137. }
  138. // special case for only single char items
  139. if (countOfSingleCharItems === itemsArr.length) {
  140. return `[${quoteMeta(itemsArr.sort().join(""))}]`;
  141. }
  142. const items = new Set(itemsArr.sort());
  143. if (countOfSingleCharItems > 2) {
  144. let singleCharItems = "";
  145. for (const item of items) {
  146. if (item.length === 1) {
  147. singleCharItems += item;
  148. items.delete(item);
  149. }
  150. }
  151. finishedItems.push(`[${quoteMeta(singleCharItems)}]`);
  152. }
  153. // special case for 2 items with common prefix/suffix
  154. if (finishedItems.length === 0 && items.size === 2) {
  155. const prefix = getCommonPrefix(itemsArr);
  156. const suffix = getCommonSuffix(
  157. itemsArr.map(item => item.slice(prefix.length))
  158. );
  159. if (prefix.length > 0 || suffix.length > 0) {
  160. return `${quoteMeta(prefix)}${itemsToRegexp(
  161. itemsArr.map(i => i.slice(prefix.length, -suffix.length || undefined))
  162. )}${quoteMeta(suffix)}`;
  163. }
  164. }
  165. // special case for 2 items with common suffix
  166. if (finishedItems.length === 0 && items.size === 2) {
  167. /** @type {Iterator<string>} */
  168. const it = items[Symbol.iterator]();
  169. const a = it.next().value;
  170. const b = it.next().value;
  171. if (a.length > 0 && b.length > 0 && a.slice(-1) === b.slice(-1)) {
  172. return `${itemsToRegexp([a.slice(0, -1), b.slice(0, -1)])}${quoteMeta(
  173. a.slice(-1)
  174. )}`;
  175. }
  176. }
  177. // find common prefix: (a1|a2|a3|a4|b5) => (a(1|2|3|4)|b5)
  178. const prefixed = popCommonItems(
  179. items,
  180. item => (item.length >= 1 ? item[0] : false),
  181. list => {
  182. if (list.length >= 3) return true;
  183. if (list.length <= 1) return false;
  184. return list[0][1] === list[1][1];
  185. }
  186. );
  187. for (const prefixedItems of prefixed) {
  188. const prefix = getCommonPrefix(prefixedItems);
  189. finishedItems.push(
  190. `${quoteMeta(prefix)}${itemsToRegexp(
  191. prefixedItems.map(i => i.slice(prefix.length))
  192. )}`
  193. );
  194. }
  195. // find common suffix: (a1|b1|c1|d1|e2) => ((a|b|c|d)1|e2)
  196. const suffixed = popCommonItems(
  197. items,
  198. item => (item.length >= 1 ? item.slice(-1) : false),
  199. list => {
  200. if (list.length >= 3) return true;
  201. if (list.length <= 1) return false;
  202. return list[0].slice(-2) === list[1].slice(-2);
  203. }
  204. );
  205. for (const suffixedItems of suffixed) {
  206. const suffix = getCommonSuffix(suffixedItems);
  207. finishedItems.push(
  208. `${itemsToRegexp(
  209. suffixedItems.map(i => i.slice(0, -suffix.length))
  210. )}${quoteMeta(suffix)}`
  211. );
  212. }
  213. // TODO further optimize regexp, i. e.
  214. // use ranges: (1|2|3|4|a) => [1-4a]
  215. const conditional = finishedItems.concat(Array.from(items, quoteMeta));
  216. if (conditional.length === 1) return conditional[0];
  217. return `(${conditional.join("|")})`;
  218. };
  219. compileBooleanMatcher.fromLists = compileBooleanMatcherFromLists;
  220. compileBooleanMatcher.itemsToRegexp = itemsToRegexp;
  221. module.exports = compileBooleanMatcher;