Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

README.md 15 KiB

há 3 anos
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. # diff-sequences
  2. Compare items in two sequences to find a **longest common subsequence**.
  3. The items not in common are the items to delete or insert in a **shortest edit script**.
  4. To maximize flexibility and minimize memory, you write **callback** functions as configuration:
  5. **Input** function `isCommon(aIndex, bIndex)` compares items at indexes in the sequences and returns a truthy/falsey value. This package might call your function more than once for some pairs of indexes.
  6. - Because your function encapsulates **comparison**, this package can compare items according to `===` operator, `Object.is` method, or other criterion.
  7. - Because your function encapsulates **sequences**, this package can find differences in arrays, strings, or other data.
  8. **Output** function `foundSubsequence(nCommon, aCommon, bCommon)` receives the number of adjacent items and starting indexes of each common subsequence. If sequences do not have common items, then this package does not call your function.
  9. If N is the sum of lengths of sequences and L is length of a longest common subsequence, then D = N – 2L is the number of **differences** in the corresponding shortest edit script.
  10. [_An O(ND) Difference Algorithm and Its Variations_](http://xmailserver.org/diff2.pdf) by Eugene W. Myers is fast when sequences have **few** differences.
  11. This package implements the **linear space** variation with optimizations so it is fast even when sequences have **many** differences.
  12. ## Usage
  13. To add this package as a dependency of a project, do either of the following:
  14. - `npm install diff-sequences`
  15. - `yarn add diff-sequences`
  16. To use `diff` as the name of the default export from this package, do either of the following:
  17. - `var diff = require('diff-sequences'); // CommonJS modules`
  18. - `import diff from 'diff-sequences'; // ECMAScript modules`
  19. Call `diff` with the **lengths** of sequences and your **callback** functions:
  20. ```js
  21. /* eslint-disable no-var */
  22. var a = ['a', 'b', 'c', 'a', 'b', 'b', 'a'];
  23. var b = ['c', 'b', 'a', 'b', 'a', 'c'];
  24. function isCommon(aIndex, bIndex) {
  25. return a[aIndex] === b[bIndex];
  26. }
  27. function foundSubsequence(nCommon, aCommon, bCommon) {
  28. // see examples
  29. }
  30. diff(a.length, b.length, isCommon, foundSubsequence);
  31. ```
  32. ## Example of longest common subsequence
  33. Some sequences (for example, `a` and `b` in the example of usage) have more than one longest common subsequence.
  34. This package finds the following common items:
  35. | comparisons of common items | values | output arguments |
  36. | :------------------------------- | :--------- | --------------------------: |
  37. | `a[2] === b[0]` | `'c'` | `foundSubsequence(1, 2, 0)` |
  38. | `a[4] === b[1]` | `'b'` | `foundSubsequence(1, 4, 1)` |
  39. | `a[5] === b[3] && a[6] === b[4]` | `'b', 'a'` | `foundSubsequence(2, 5, 3)` |
  40. The “edit graph” analogy in the Myers paper shows the following common items:
  41. | comparisons of common items | values |
  42. | :------------------------------- | :--------- |
  43. | `a[2] === b[0]` | `'c'` |
  44. | `a[3] === b[2] && a[4] === b[3]` | `'a', 'b'` |
  45. | `a[6] === b[4]` | `'a'` |
  46. Various packages which implement the Myers algorithm will **always agree** on the **length** of a longest common subsequence, but might **sometimes disagree** on which **items** are in it.
  47. ## Example of callback functions to count common items
  48. ```js
  49. /* eslint-disable no-var */
  50. // Return length of longest common subsequence according to === operator.
  51. function countCommonItems(a, b) {
  52. var n = 0;
  53. function isCommon(aIndex, bIndex) {
  54. return a[aIndex] === b[bIndex];
  55. }
  56. function foundSubsequence(nCommon) {
  57. n += nCommon;
  58. }
  59. diff(a.length, b.length, isCommon, foundSubsequence);
  60. return n;
  61. }
  62. var commonLength = countCommonItems(
  63. ['a', 'b', 'c', 'a', 'b', 'b', 'a'],
  64. ['c', 'b', 'a', 'b', 'a', 'c'],
  65. );
  66. ```
  67. | category of items | expression | value |
  68. | :----------------- | ------------------------: | ----: |
  69. | in common | `commonLength` | `4` |
  70. | to delete from `a` | `a.length - commonLength` | `3` |
  71. | to insert from `b` | `b.length - commonLength` | `2` |
  72. If the length difference `b.length - a.length` is:
  73. - negative: its absolute value is the minimum number of items to **delete** from `a`
  74. - positive: it is the minimum number of items to **insert** from `b`
  75. - zero: there is an **equal** number of items to delete from `a` and insert from `b`
  76. - non-zero: there is an equal number of **additional** items to delete from `a` and insert from `b`
  77. In this example, `6 - 7` is:
  78. - negative: `1` is the minimum number of items to **delete** from `a`
  79. - non-zero: `2` is the number of **additional** items to delete from `a` and insert from `b`
  80. ## Example of callback functions to find common items
  81. ```js
  82. // Return array of items in longest common subsequence according to Object.is method.
  83. const findCommonItems = (a, b) => {
  84. const array = [];
  85. diff(
  86. a.length,
  87. b.length,
  88. (aIndex, bIndex) => Object.is(a[aIndex], b[bIndex]),
  89. (nCommon, aCommon) => {
  90. for (; nCommon !== 0; nCommon -= 1, aCommon += 1) {
  91. array.push(a[aCommon]);
  92. }
  93. },
  94. );
  95. return array;
  96. };
  97. const commonItems = findCommonItems(
  98. ['a', 'b', 'c', 'a', 'b', 'b', 'a'],
  99. ['c', 'b', 'a', 'b', 'a', 'c'],
  100. );
  101. ```
  102. | `i` | `commonItems[i]` | `aIndex` |
  103. | --: | :--------------- | -------: |
  104. | `0` | `'c'` | `2` |
  105. | `1` | `'b'` | `4` |
  106. | `2` | `'b'` | `5` |
  107. | `3` | `'a'` | `6` |
  108. ## Example of callback functions to diff index intervals
  109. Instead of slicing array-like objects, you can adjust indexes in your callback functions.
  110. ```js
  111. // Diff index intervals that are half open [start, end) like array slice method.
  112. const diffIndexIntervals = (a, aStart, aEnd, b, bStart, bEnd) => {
  113. // Validate: 0 <= aStart and aStart <= aEnd and aEnd <= a.length
  114. // Validate: 0 <= bStart and bStart <= bEnd and bEnd <= b.length
  115. diff(
  116. aEnd - aStart,
  117. bEnd - bStart,
  118. (aIndex, bIndex) => Object.is(a[aStart + aIndex], b[bStart + bIndex]),
  119. (nCommon, aCommon, bCommon) => {
  120. // aStart + aCommon, bStart + bCommon
  121. },
  122. );
  123. // After the last common subsequence, do any remaining work.
  124. };
  125. ```
  126. ## Example of callback functions to emulate diff command
  127. Linux or Unix has a `diff` command to compare files line by line. Its output is a **shortest edit script**:
  128. - **c**hange adjacent lines from the first file to lines from the second file
  129. - **d**elete lines from the first file
  130. - **a**ppend or insert lines from the second file
  131. ```js
  132. // Given zero-based half-open range [start, end) of array indexes,
  133. // return one-based closed range [start + 1, end] as string.
  134. const getRange = (start, end) =>
  135. start + 1 === end ? `${start + 1}` : `${start + 1},${end}`;
  136. // Given index intervals of lines to delete or insert, or both, or neither,
  137. // push formatted diff lines onto array.
  138. const pushDelIns = (aLines, aIndex, aEnd, bLines, bIndex, bEnd, array) => {
  139. const deleteLines = aIndex !== aEnd;
  140. const insertLines = bIndex !== bEnd;
  141. const changeLines = deleteLines && insertLines;
  142. if (changeLines) {
  143. array.push(getRange(aIndex, aEnd) + 'c' + getRange(bIndex, bEnd));
  144. } else if (deleteLines) {
  145. array.push(getRange(aIndex, aEnd) + 'd' + String(bIndex));
  146. } else if (insertLines) {
  147. array.push(String(aIndex) + 'a' + getRange(bIndex, bEnd));
  148. } else {
  149. return;
  150. }
  151. for (; aIndex !== aEnd; aIndex += 1) {
  152. array.push('< ' + aLines[aIndex]); // delete is less than
  153. }
  154. if (changeLines) {
  155. array.push('---');
  156. }
  157. for (; bIndex !== bEnd; bIndex += 1) {
  158. array.push('> ' + bLines[bIndex]); // insert is greater than
  159. }
  160. };
  161. // Given content of two files, return emulated output of diff utility.
  162. const findShortestEditScript = (a, b) => {
  163. const aLines = a.split('\n');
  164. const bLines = b.split('\n');
  165. const aLength = aLines.length;
  166. const bLength = bLines.length;
  167. const isCommon = (aIndex, bIndex) => aLines[aIndex] === bLines[bIndex];
  168. let aIndex = 0;
  169. let bIndex = 0;
  170. const array = [];
  171. const foundSubsequence = (nCommon, aCommon, bCommon) => {
  172. pushDelIns(aLines, aIndex, aCommon, bLines, bIndex, bCommon, array);
  173. aIndex = aCommon + nCommon; // number of lines compared in a
  174. bIndex = bCommon + nCommon; // number of lines compared in b
  175. };
  176. diff(aLength, bLength, isCommon, foundSubsequence);
  177. // After the last common subsequence, push remaining change lines.
  178. pushDelIns(aLines, aIndex, aLength, bLines, bIndex, bLength, array);
  179. return array.length === 0 ? '' : array.join('\n') + '\n';
  180. };
  181. ```
  182. ## Example of callback functions to format diff lines
  183. Here is simplified code to format **changed and unchanged lines** in expected and received values after a test fails in Jest:
  184. ```js
  185. // Format diff with minus or plus for change lines and space for common lines.
  186. const formatDiffLines = (a, b) => {
  187. // Jest depends on pretty-format package to serialize objects as strings.
  188. // Unindented for comparison to avoid distracting differences:
  189. const aLinesUn = format(a, {indent: 0 /*, other options*/}).split('\n');
  190. const bLinesUn = format(b, {indent: 0 /*, other options*/}).split('\n');
  191. // Indented to display changed and unchanged lines:
  192. const aLinesIn = format(a, {indent: 2 /*, other options*/}).split('\n');
  193. const bLinesIn = format(b, {indent: 2 /*, other options*/}).split('\n');
  194. const aLength = aLinesIn.length; // Validate: aLinesUn.length === aLength
  195. const bLength = bLinesIn.length; // Validate: bLinesUn.length === bLength
  196. const isCommon = (aIndex, bIndex) => aLinesUn[aIndex] === bLinesUn[bIndex];
  197. // Only because the GitHub Flavored Markdown doc collapses adjacent spaces,
  198. // this example code and the following table represent spaces as middle dots.
  199. let aIndex = 0;
  200. let bIndex = 0;
  201. const array = [];
  202. const foundSubsequence = (nCommon, aCommon, bCommon) => {
  203. for (; aIndex !== aCommon; aIndex += 1) {
  204. array.push('-·' + aLinesIn[aIndex]); // delete is minus
  205. }
  206. for (; bIndex !== bCommon; bIndex += 1) {
  207. array.push('+·' + bLinesIn[bIndex]); // insert is plus
  208. }
  209. for (; nCommon !== 0; nCommon -= 1, aIndex += 1, bIndex += 1) {
  210. // For common lines, received indentation seems more intuitive.
  211. array.push('··' + bLinesIn[bIndex]); // common is space
  212. }
  213. };
  214. diff(aLength, bLength, isCommon, foundSubsequence);
  215. // After the last common subsequence, push remaining change lines.
  216. for (; aIndex !== aLength; aIndex += 1) {
  217. array.push('-·' + aLinesIn[aIndex]);
  218. }
  219. for (; bIndex !== bLength; bIndex += 1) {
  220. array.push('+·' + bLinesIn[bIndex]);
  221. }
  222. return array;
  223. };
  224. const expected = {
  225. searching: '',
  226. sorting: {
  227. ascending: true,
  228. fieldKey: 'what',
  229. },
  230. };
  231. const received = {
  232. searching: '',
  233. sorting: [
  234. {
  235. descending: false,
  236. fieldKey: 'what',
  237. },
  238. ],
  239. };
  240. const diffLines = formatDiffLines(expected, received);
  241. ```
  242. If N is the sum of lengths of sequences and L is length of a longest common subsequence, then N – L is length of an array of diff lines. In this example, N is 7 + 9, L is 5, and N – L is 11.
  243. | `i` | `diffLines[i]` | `aIndex` | `bIndex` |
  244. | ---: | :--------------------------------- | -------: | -------: |
  245. | `0` | `'··Object {'` | `0` | `0` |
  246. | `1` | `'····"searching": "",'` | `1` | `1` |
  247. | `2` | `'-···"sorting": Object {'` | `2` | |
  248. | `3` | `'-·····"ascending": true,'` | `3` | |
  249. | `4` | `'+·····"sorting": Array ['` | | `2` |
  250. | `5` | `'+·······Object {'` | | `3` |
  251. | `6` | `'+·········"descending": false,'` | | `4` |
  252. | `7` | `'··········"fieldKey": "what",'` | `4` | `5` |
  253. | `8` | `'········},'` | `5` | `6` |
  254. | `9` | `'+·····],'` | | `7` |
  255. | `10` | `'··}'` | `6` | `8` |
  256. ## Example of callback functions to find diff items
  257. Here is simplified code to find changed and unchanged substrings **within adjacent changed lines** in expected and received values after a test fails in Jest:
  258. ```js
  259. // Return diff items for strings (compatible with diff-match-patch package).
  260. const findDiffItems = (a, b) => {
  261. const isCommon = (aIndex, bIndex) => a[aIndex] === b[bIndex];
  262. let aIndex = 0;
  263. let bIndex = 0;
  264. const array = [];
  265. const foundSubsequence = (nCommon, aCommon, bCommon) => {
  266. if (aIndex !== aCommon) {
  267. array.push([-1, a.slice(aIndex, aCommon)]); // delete is -1
  268. }
  269. if (bIndex !== bCommon) {
  270. array.push([1, b.slice(bIndex, bCommon)]); // insert is 1
  271. }
  272. aIndex = aCommon + nCommon; // number of characters compared in a
  273. bIndex = bCommon + nCommon; // number of characters compared in b
  274. array.push([0, a.slice(aCommon, aIndex)]); // common is 0
  275. };
  276. diff(a.length, b.length, isCommon, foundSubsequence);
  277. // After the last common subsequence, push remaining change items.
  278. if (aIndex !== a.length) {
  279. array.push([-1, a.slice(aIndex)]);
  280. }
  281. if (bIndex !== b.length) {
  282. array.push([1, b.slice(bIndex)]);
  283. }
  284. return array;
  285. };
  286. const expectedDeleted = ['"sorting": Object {', '"ascending": true,'].join(
  287. '\n',
  288. );
  289. const receivedInserted = [
  290. '"sorting": Array [',
  291. 'Object {',
  292. '"descending": false,',
  293. ].join('\n');
  294. const diffItems = findDiffItems(expectedDeleted, receivedInserted);
  295. ```
  296. | `i` | `diffItems[i][0]` | `diffItems[i][1]` |
  297. | --: | ----------------: | :---------------- |
  298. | `0` | `0` | `'"sorting": '` |
  299. | `1` | `1` | `'Array [\n'` |
  300. | `2` | `0` | `'Object {\n"'` |
  301. | `3` | `-1` | `'a'` |
  302. | `4` | `1` | `'de'` |
  303. | `5` | `0` | `'scending": '` |
  304. | `6` | `-1` | `'tru'` |
  305. | `7` | `1` | `'fals'` |
  306. | `8` | `0` | `'e,'` |
  307. The length difference `b.length - a.length` is equal to the sum of `diffItems[i][0]` values times `diffItems[i][1]` lengths. In this example, the difference `48 - 38` is equal to the sum `10`.
  308. | category of diff item | `[0]` | `[1]` lengths | subtotal |
  309. | :-------------------- | ----: | -----------------: | -------: |
  310. | in common | `0` | `11 + 10 + 11 + 2` | `0` |
  311. | to delete from `a` | `–1` | `1 + 3` | `-4` |
  312. | to insert from `b` | `1` | `8 + 2 + 4` | `14` |
  313. Instead of formatting the changed substrings with escape codes for colors in the `foundSubsequence` function to save memory, this example spends memory to **gain flexibility** before formatting, so a separate heuristic algorithm might modify the generic array of diff items to show changes more clearly:
  314. | `i` | `diffItems[i][0]` | `diffItems[i][1]` |
  315. | --: | ----------------: | :---------------- |
  316. | `6` | `-1` | `'true'` |
  317. | `7` | `1` | `'false'` |
  318. | `8` | `0` | `','` |
  319. For expected and received strings of serialized data, the result of finding changed **lines**, and then finding changed **substrings** within adjacent changed lines (as in the preceding two examples) sometimes displays the changes in a more intuitive way than the result of finding changed substrings, and then splitting them into changed and unchanged lines.