deterministicGrouping.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. // Simulations show these probabilities for a single change
  7. // 93.1% that one group is invalidated
  8. // 4.8% that two groups are invalidated
  9. // 1.1% that 3 groups are invalidated
  10. // 0.1% that 4 or more groups are invalidated
  11. //
  12. // And these for removing/adding 10 lexically adjacent files
  13. // 64.5% that one group is invalidated
  14. // 24.8% that two groups are invalidated
  15. // 7.8% that 3 groups are invalidated
  16. // 2.7% that 4 or more groups are invalidated
  17. //
  18. // And these for removing/adding 3 random files
  19. // 0% that one group is invalidated
  20. // 3.7% that two groups are invalidated
  21. // 80.8% that 3 groups are invalidated
  22. // 12.3% that 4 groups are invalidated
  23. // 3.2% that 5 or more groups are invalidated
  24. /**
  25. *
  26. * @param {string} a key
  27. * @param {string} b key
  28. * @returns {number} the similarity as number
  29. */
  30. const similarity = (a, b) => {
  31. const l = Math.min(a.length, b.length);
  32. let dist = 0;
  33. for (let i = 0; i < l; i++) {
  34. const ca = a.charCodeAt(i);
  35. const cb = b.charCodeAt(i);
  36. dist += Math.max(0, 10 - Math.abs(ca - cb));
  37. }
  38. return dist;
  39. };
  40. /**
  41. * @param {string} a key
  42. * @param {string} b key
  43. * @param {Set<string>} usedNames set of already used names
  44. * @returns {string} the common part and a single char for the difference
  45. */
  46. const getName = (a, b, usedNames) => {
  47. const l = Math.min(a.length, b.length);
  48. let i = 0;
  49. while (i < l) {
  50. if (a.charCodeAt(i) !== b.charCodeAt(i)) {
  51. i++;
  52. break;
  53. }
  54. i++;
  55. }
  56. while (i < l) {
  57. const name = a.slice(0, i);
  58. const lowerName = name.toLowerCase();
  59. if (!usedNames.has(lowerName)) {
  60. usedNames.add(lowerName);
  61. return name;
  62. }
  63. i++;
  64. }
  65. // names always contain a hash, so this is always unique
  66. // we don't need to check usedNames nor add it
  67. return a;
  68. };
  69. /**
  70. * @param {Record<string, number>} total total size
  71. * @param {Record<string, number>} size single size
  72. * @returns {void}
  73. */
  74. const addSizeTo = (total, size) => {
  75. for (const key of Object.keys(size)) {
  76. total[key] = (total[key] || 0) + size[key];
  77. }
  78. };
  79. /**
  80. * @param {Record<string, number>} total total size
  81. * @param {Record<string, number>} size single size
  82. * @returns {void}
  83. */
  84. const subtractSizeFrom = (total, size) => {
  85. for (const key of Object.keys(size)) {
  86. total[key] -= size[key];
  87. }
  88. };
  89. /**
  90. * @param {Iterable<Node>} nodes some nodes
  91. * @returns {Record<string, number>} total size
  92. */
  93. const sumSize = nodes => {
  94. const sum = Object.create(null);
  95. for (const node of nodes) {
  96. addSizeTo(sum, node.size);
  97. }
  98. return sum;
  99. };
  100. const isTooBig = (size, maxSize) => {
  101. for (const key of Object.keys(size)) {
  102. const s = size[key];
  103. if (s === 0) continue;
  104. const maxSizeValue = maxSize[key];
  105. if (typeof maxSizeValue === "number") {
  106. if (s > maxSizeValue) return true;
  107. }
  108. }
  109. return false;
  110. };
  111. const isTooSmall = (size, minSize) => {
  112. for (const key of Object.keys(size)) {
  113. const s = size[key];
  114. if (s === 0) continue;
  115. const minSizeValue = minSize[key];
  116. if (typeof minSizeValue === "number") {
  117. if (s < minSizeValue) return true;
  118. }
  119. }
  120. return false;
  121. };
  122. const getTooSmallTypes = (size, minSize) => {
  123. const types = new Set();
  124. for (const key of Object.keys(size)) {
  125. const s = size[key];
  126. if (s === 0) continue;
  127. const minSizeValue = minSize[key];
  128. if (typeof minSizeValue === "number") {
  129. if (s < minSizeValue) types.add(key);
  130. }
  131. }
  132. return types;
  133. };
  134. const getNumberOfMatchingSizeTypes = (size, types) => {
  135. let i = 0;
  136. for (const key of Object.keys(size)) {
  137. if (size[key] !== 0 && types.has(key)) i++;
  138. }
  139. return i;
  140. };
  141. const selectiveSizeSum = (size, types) => {
  142. let sum = 0;
  143. for (const key of Object.keys(size)) {
  144. if (size[key] !== 0 && types.has(key)) sum += size[key];
  145. }
  146. return sum;
  147. };
  148. /**
  149. * @template T
  150. */
  151. class Node {
  152. /**
  153. * @param {T} item item
  154. * @param {string} key key
  155. * @param {Record<string, number>} size size
  156. */
  157. constructor(item, key, size) {
  158. this.item = item;
  159. this.key = key;
  160. this.size = size;
  161. }
  162. }
  163. /**
  164. * @template T
  165. */
  166. class Group {
  167. /**
  168. * @param {Node<T>[]} nodes nodes
  169. * @param {number[]} similarities similarities between the nodes (length = nodes.length - 1)
  170. * @param {Record<string, number>=} size size of the group
  171. */
  172. constructor(nodes, similarities, size) {
  173. this.nodes = nodes;
  174. this.similarities = similarities;
  175. this.size = size || sumSize(nodes);
  176. /** @type {string} */
  177. this.key = undefined;
  178. }
  179. /**
  180. * @param {function(Node): boolean} filter filter function
  181. * @returns {Node[]} removed nodes
  182. */
  183. popNodes(filter) {
  184. const newNodes = [];
  185. const newSimilarities = [];
  186. const resultNodes = [];
  187. let lastNode;
  188. for (let i = 0; i < this.nodes.length; i++) {
  189. const node = this.nodes[i];
  190. if (filter(node)) {
  191. resultNodes.push(node);
  192. } else {
  193. if (newNodes.length > 0) {
  194. newSimilarities.push(
  195. lastNode === this.nodes[i - 1]
  196. ? this.similarities[i - 1]
  197. : similarity(lastNode.key, node.key)
  198. );
  199. }
  200. newNodes.push(node);
  201. lastNode = node;
  202. }
  203. }
  204. if (resultNodes.length === this.nodes.length) return undefined;
  205. this.nodes = newNodes;
  206. this.similarities = newSimilarities;
  207. this.size = sumSize(newNodes);
  208. return resultNodes;
  209. }
  210. }
  211. /**
  212. * @param {Iterable<Node>} nodes nodes
  213. * @returns {number[]} similarities
  214. */
  215. const getSimilarities = nodes => {
  216. // calculate similarities between lexically adjacent nodes
  217. /** @type {number[]} */
  218. const similarities = [];
  219. let last = undefined;
  220. for (const node of nodes) {
  221. if (last !== undefined) {
  222. similarities.push(similarity(last.key, node.key));
  223. }
  224. last = node;
  225. }
  226. return similarities;
  227. };
  228. /**
  229. * @template T
  230. * @typedef {Object} GroupedItems<T>
  231. * @property {string} key
  232. * @property {T[]} items
  233. * @property {Record<string, number>} size
  234. */
  235. /**
  236. * @template T
  237. * @typedef {Object} Options
  238. * @property {Record<string, number>} maxSize maximum size of a group
  239. * @property {Record<string, number>} minSize minimum size of a group (preferred over maximum size)
  240. * @property {Iterable<T>} items a list of items
  241. * @property {function(T): Record<string, number>} getSize function to get size of an item
  242. * @property {function(T): string} getKey function to get the key of an item
  243. */
  244. /**
  245. * @template T
  246. * @param {Options<T>} options options object
  247. * @returns {GroupedItems<T>[]} grouped items
  248. */
  249. module.exports = ({ maxSize, minSize, items, getSize, getKey }) => {
  250. /** @type {Group<T>[]} */
  251. const result = [];
  252. const nodes = Array.from(
  253. items,
  254. item => new Node(item, getKey(item), getSize(item))
  255. );
  256. /** @type {Node<T>[]} */
  257. const initialNodes = [];
  258. // lexically ordering of keys
  259. nodes.sort((a, b) => {
  260. if (a.key < b.key) return -1;
  261. if (a.key > b.key) return 1;
  262. return 0;
  263. });
  264. // return nodes bigger than maxSize directly as group
  265. // But make sure that minSize is not violated
  266. for (const node of nodes) {
  267. if (isTooBig(node.size, maxSize) && !isTooSmall(node.size, minSize)) {
  268. result.push(new Group([node], []));
  269. } else {
  270. initialNodes.push(node);
  271. }
  272. }
  273. if (initialNodes.length > 0) {
  274. const initialGroup = new Group(initialNodes, getSimilarities(initialNodes));
  275. const removeProblematicNodes = (group, consideredSize = group.size) => {
  276. const problemTypes = getTooSmallTypes(consideredSize, minSize);
  277. if (problemTypes.size > 0) {
  278. // We hit an edge case where the working set is already smaller than minSize
  279. // We merge problematic nodes with the smallest result node to keep minSize intact
  280. const problemNodes = group.popNodes(
  281. n => getNumberOfMatchingSizeTypes(n.size, problemTypes) > 0
  282. );
  283. if (problemNodes === undefined) return false;
  284. // Only merge it with result nodes that have the problematic size type
  285. const possibleResultGroups = result.filter(
  286. n => getNumberOfMatchingSizeTypes(n.size, problemTypes) > 0
  287. );
  288. if (possibleResultGroups.length > 0) {
  289. const bestGroup = possibleResultGroups.reduce((min, group) => {
  290. const minMatches = getNumberOfMatchingSizeTypes(min, problemTypes);
  291. const groupMatches = getNumberOfMatchingSizeTypes(
  292. group,
  293. problemTypes
  294. );
  295. if (minMatches !== groupMatches)
  296. return minMatches < groupMatches ? group : min;
  297. if (
  298. selectiveSizeSum(min.size, problemTypes) >
  299. selectiveSizeSum(group.size, problemTypes)
  300. )
  301. return group;
  302. return min;
  303. });
  304. for (const node of problemNodes) bestGroup.nodes.push(node);
  305. bestGroup.nodes.sort((a, b) => {
  306. if (a.key < b.key) return -1;
  307. if (a.key > b.key) return 1;
  308. return 0;
  309. });
  310. } else {
  311. // There are no other nodes with the same size types
  312. // We create a new group and have to accept that it's smaller than minSize
  313. result.push(new Group(problemNodes, null));
  314. }
  315. return true;
  316. } else {
  317. return false;
  318. }
  319. };
  320. if (initialGroup.nodes.length > 0) {
  321. const queue = [initialGroup];
  322. while (queue.length) {
  323. const group = queue.pop();
  324. // only groups bigger than maxSize need to be splitted
  325. if (!isTooBig(group.size, maxSize)) {
  326. result.push(group);
  327. continue;
  328. }
  329. // If the group is already too small
  330. // we try to work only with the unproblematic nodes
  331. if (removeProblematicNodes(group)) {
  332. // This changed something, so we try this group again
  333. queue.push(group);
  334. continue;
  335. }
  336. // find unsplittable area from left and right
  337. // going minSize from left and right
  338. // at least one node need to be included otherwise we get stuck
  339. let left = 1;
  340. let leftSize = Object.create(null);
  341. addSizeTo(leftSize, group.nodes[0].size);
  342. while (left < group.nodes.length && isTooSmall(leftSize, minSize)) {
  343. addSizeTo(leftSize, group.nodes[left].size);
  344. left++;
  345. }
  346. let right = group.nodes.length - 2;
  347. let rightSize = Object.create(null);
  348. addSizeTo(rightSize, group.nodes[group.nodes.length - 1].size);
  349. while (right >= 0 && isTooSmall(rightSize, minSize)) {
  350. addSizeTo(rightSize, group.nodes[right].size);
  351. right--;
  352. }
  353. // left v v right
  354. // [ O O O ] O O O [ O O O ]
  355. // ^^^^^^^^^ leftSize
  356. // rightSize ^^^^^^^^^
  357. // leftSize > minSize
  358. // rightSize > minSize
  359. // Perfect split: [ O O O ] [ O O O ]
  360. // right === left - 1
  361. if (left - 1 > right) {
  362. // We try to remove some problematic nodes to "fix" that
  363. let prevSize;
  364. if (right < group.nodes.length - left) {
  365. subtractSizeFrom(rightSize, group.nodes[right + 1].size);
  366. prevSize = rightSize;
  367. } else {
  368. subtractSizeFrom(leftSize, group.nodes[left - 1].size);
  369. prevSize = leftSize;
  370. }
  371. if (removeProblematicNodes(group, prevSize)) {
  372. // This changed something, so we try this group again
  373. queue.push(group);
  374. continue;
  375. }
  376. // can't split group while holding minSize
  377. // because minSize is preferred of maxSize we return
  378. // the problematic nodes as result here even while it's too big
  379. // To avoid this make sure maxSize > minSize * 3
  380. result.push(group);
  381. continue;
  382. }
  383. if (left <= right) {
  384. // when there is a area between left and right
  385. // we look for best split point
  386. // we split at the minimum similarity
  387. // here key space is separated the most
  388. // But we also need to make sure to not create too small groups
  389. let best = -1;
  390. let bestSimilarity = Infinity;
  391. let pos = left;
  392. let rightSize = sumSize(group.nodes.slice(pos));
  393. // pos v v right
  394. // [ O O O ] O O O [ O O O ]
  395. // ^^^^^^^^^ leftSize
  396. // rightSize ^^^^^^^^^^^^^^^
  397. while (pos <= right + 1) {
  398. const similarity = group.similarities[pos - 1];
  399. if (
  400. similarity < bestSimilarity &&
  401. !isTooSmall(leftSize, minSize) &&
  402. !isTooSmall(rightSize, minSize)
  403. ) {
  404. best = pos;
  405. bestSimilarity = similarity;
  406. }
  407. addSizeTo(leftSize, group.nodes[pos].size);
  408. subtractSizeFrom(rightSize, group.nodes[pos].size);
  409. pos++;
  410. }
  411. if (best < 0) {
  412. // This can't happen
  413. // but if that assumption is wrong
  414. // fallback to a big group
  415. result.push(group);
  416. continue;
  417. }
  418. left = best;
  419. right = best - 1;
  420. }
  421. // create two new groups for left and right area
  422. // and queue them up
  423. const rightNodes = [group.nodes[right + 1]];
  424. /** @type {number[]} */
  425. const rightSimilarities = [];
  426. for (let i = right + 2; i < group.nodes.length; i++) {
  427. rightSimilarities.push(group.similarities[i - 1]);
  428. rightNodes.push(group.nodes[i]);
  429. }
  430. queue.push(new Group(rightNodes, rightSimilarities));
  431. const leftNodes = [group.nodes[0]];
  432. /** @type {number[]} */
  433. const leftSimilarities = [];
  434. for (let i = 1; i < left; i++) {
  435. leftSimilarities.push(group.similarities[i - 1]);
  436. leftNodes.push(group.nodes[i]);
  437. }
  438. queue.push(new Group(leftNodes, leftSimilarities));
  439. }
  440. }
  441. }
  442. // lexically ordering
  443. result.sort((a, b) => {
  444. if (a.nodes[0].key < b.nodes[0].key) return -1;
  445. if (a.nodes[0].key > b.nodes[0].key) return 1;
  446. return 0;
  447. });
  448. // give every group a name
  449. const usedNames = new Set();
  450. for (let i = 0; i < result.length; i++) {
  451. const group = result[i];
  452. if (group.nodes.length === 1) {
  453. group.key = group.nodes[0].key;
  454. } else {
  455. const first = group.nodes[0];
  456. const last = group.nodes[group.nodes.length - 1];
  457. const name = getName(first.key, last.key, usedNames);
  458. group.key = name;
  459. }
  460. }
  461. // return the results
  462. return result.map(group => {
  463. /** @type {GroupedItems<T>} */
  464. return {
  465. key: group.key,
  466. items: group.nodes.map(node => node.item),
  467. size: group.size
  468. };
  469. });
  470. };