diff.js 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. import { DiffChange } from './diffChange.js';
  6. import { stringHash } from '../hash.js';
  7. export class StringDiffSequence {
  8. constructor(source) {
  9. this.source = source;
  10. }
  11. getElements() {
  12. const source = this.source;
  13. const characters = new Int32Array(source.length);
  14. for (let i = 0, len = source.length; i < len; i++) {
  15. characters[i] = source.charCodeAt(i);
  16. }
  17. return characters;
  18. }
  19. }
  20. export function stringDiff(original, modified, pretty) {
  21. return new LcsDiff(new StringDiffSequence(original), new StringDiffSequence(modified)).ComputeDiff(pretty).changes;
  22. }
  23. //
  24. // The code below has been ported from a C# implementation in VS
  25. //
  26. export class Debug {
  27. static Assert(condition, message) {
  28. if (!condition) {
  29. throw new Error(message);
  30. }
  31. }
  32. }
  33. export class MyArray {
  34. /**
  35. * Copies a range of elements from an Array starting at the specified source index and pastes
  36. * them to another Array starting at the specified destination index. The length and the indexes
  37. * are specified as 64-bit integers.
  38. * sourceArray:
  39. * The Array that contains the data to copy.
  40. * sourceIndex:
  41. * A 64-bit integer that represents the index in the sourceArray at which copying begins.
  42. * destinationArray:
  43. * The Array that receives the data.
  44. * destinationIndex:
  45. * A 64-bit integer that represents the index in the destinationArray at which storing begins.
  46. * length:
  47. * A 64-bit integer that represents the number of elements to copy.
  48. */
  49. static Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length) {
  50. for (let i = 0; i < length; i++) {
  51. destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i];
  52. }
  53. }
  54. static Copy2(sourceArray, sourceIndex, destinationArray, destinationIndex, length) {
  55. for (let i = 0; i < length; i++) {
  56. destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i];
  57. }
  58. }
  59. }
  60. /**
  61. * A utility class which helps to create the set of DiffChanges from
  62. * a difference operation. This class accepts original DiffElements and
  63. * modified DiffElements that are involved in a particular change. The
  64. * MarkNextChange() method can be called to mark the separation between
  65. * distinct changes. At the end, the Changes property can be called to retrieve
  66. * the constructed changes.
  67. */
  68. class DiffChangeHelper {
  69. /**
  70. * Constructs a new DiffChangeHelper for the given DiffSequences.
  71. */
  72. constructor() {
  73. this.m_changes = [];
  74. this.m_originalStart = 1073741824 /* MAX_SAFE_SMALL_INTEGER */;
  75. this.m_modifiedStart = 1073741824 /* MAX_SAFE_SMALL_INTEGER */;
  76. this.m_originalCount = 0;
  77. this.m_modifiedCount = 0;
  78. }
  79. /**
  80. * Marks the beginning of the next change in the set of differences.
  81. */
  82. MarkNextChange() {
  83. // Only add to the list if there is something to add
  84. if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
  85. // Add the new change to our list
  86. this.m_changes.push(new DiffChange(this.m_originalStart, this.m_originalCount, this.m_modifiedStart, this.m_modifiedCount));
  87. }
  88. // Reset for the next change
  89. this.m_originalCount = 0;
  90. this.m_modifiedCount = 0;
  91. this.m_originalStart = 1073741824 /* MAX_SAFE_SMALL_INTEGER */;
  92. this.m_modifiedStart = 1073741824 /* MAX_SAFE_SMALL_INTEGER */;
  93. }
  94. /**
  95. * Adds the original element at the given position to the elements
  96. * affected by the current change. The modified index gives context
  97. * to the change position with respect to the original sequence.
  98. * @param originalIndex The index of the original element to add.
  99. * @param modifiedIndex The index of the modified element that provides corresponding position in the modified sequence.
  100. */
  101. AddOriginalElement(originalIndex, modifiedIndex) {
  102. // The 'true' start index is the smallest of the ones we've seen
  103. this.m_originalStart = Math.min(this.m_originalStart, originalIndex);
  104. this.m_modifiedStart = Math.min(this.m_modifiedStart, modifiedIndex);
  105. this.m_originalCount++;
  106. }
  107. /**
  108. * Adds the modified element at the given position to the elements
  109. * affected by the current change. The original index gives context
  110. * to the change position with respect to the modified sequence.
  111. * @param originalIndex The index of the original element that provides corresponding position in the original sequence.
  112. * @param modifiedIndex The index of the modified element to add.
  113. */
  114. AddModifiedElement(originalIndex, modifiedIndex) {
  115. // The 'true' start index is the smallest of the ones we've seen
  116. this.m_originalStart = Math.min(this.m_originalStart, originalIndex);
  117. this.m_modifiedStart = Math.min(this.m_modifiedStart, modifiedIndex);
  118. this.m_modifiedCount++;
  119. }
  120. /**
  121. * Retrieves all of the changes marked by the class.
  122. */
  123. getChanges() {
  124. if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
  125. // Finish up on whatever is left
  126. this.MarkNextChange();
  127. }
  128. return this.m_changes;
  129. }
  130. /**
  131. * Retrieves all of the changes marked by the class in the reverse order
  132. */
  133. getReverseChanges() {
  134. if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
  135. // Finish up on whatever is left
  136. this.MarkNextChange();
  137. }
  138. this.m_changes.reverse();
  139. return this.m_changes;
  140. }
  141. }
  142. /**
  143. * An implementation of the difference algorithm described in
  144. * "An O(ND) Difference Algorithm and its variations" by Eugene W. Myers
  145. */
  146. export class LcsDiff {
  147. /**
  148. * Constructs the DiffFinder
  149. */
  150. constructor(originalSequence, modifiedSequence, continueProcessingPredicate = null) {
  151. this.ContinueProcessingPredicate = continueProcessingPredicate;
  152. this._originalSequence = originalSequence;
  153. this._modifiedSequence = modifiedSequence;
  154. const [originalStringElements, originalElementsOrHash, originalHasStrings] = LcsDiff._getElements(originalSequence);
  155. const [modifiedStringElements, modifiedElementsOrHash, modifiedHasStrings] = LcsDiff._getElements(modifiedSequence);
  156. this._hasStrings = (originalHasStrings && modifiedHasStrings);
  157. this._originalStringElements = originalStringElements;
  158. this._originalElementsOrHash = originalElementsOrHash;
  159. this._modifiedStringElements = modifiedStringElements;
  160. this._modifiedElementsOrHash = modifiedElementsOrHash;
  161. this.m_forwardHistory = [];
  162. this.m_reverseHistory = [];
  163. }
  164. static _isStringArray(arr) {
  165. return (arr.length > 0 && typeof arr[0] === 'string');
  166. }
  167. static _getElements(sequence) {
  168. const elements = sequence.getElements();
  169. if (LcsDiff._isStringArray(elements)) {
  170. const hashes = new Int32Array(elements.length);
  171. for (let i = 0, len = elements.length; i < len; i++) {
  172. hashes[i] = stringHash(elements[i], 0);
  173. }
  174. return [elements, hashes, true];
  175. }
  176. if (elements instanceof Int32Array) {
  177. return [[], elements, false];
  178. }
  179. return [[], new Int32Array(elements), false];
  180. }
  181. ElementsAreEqual(originalIndex, newIndex) {
  182. if (this._originalElementsOrHash[originalIndex] !== this._modifiedElementsOrHash[newIndex]) {
  183. return false;
  184. }
  185. return (this._hasStrings ? this._originalStringElements[originalIndex] === this._modifiedStringElements[newIndex] : true);
  186. }
  187. ElementsAreStrictEqual(originalIndex, newIndex) {
  188. if (!this.ElementsAreEqual(originalIndex, newIndex)) {
  189. return false;
  190. }
  191. const originalElement = LcsDiff._getStrictElement(this._originalSequence, originalIndex);
  192. const modifiedElement = LcsDiff._getStrictElement(this._modifiedSequence, newIndex);
  193. return (originalElement === modifiedElement);
  194. }
  195. static _getStrictElement(sequence, index) {
  196. if (typeof sequence.getStrictElement === 'function') {
  197. return sequence.getStrictElement(index);
  198. }
  199. return null;
  200. }
  201. OriginalElementsAreEqual(index1, index2) {
  202. if (this._originalElementsOrHash[index1] !== this._originalElementsOrHash[index2]) {
  203. return false;
  204. }
  205. return (this._hasStrings ? this._originalStringElements[index1] === this._originalStringElements[index2] : true);
  206. }
  207. ModifiedElementsAreEqual(index1, index2) {
  208. if (this._modifiedElementsOrHash[index1] !== this._modifiedElementsOrHash[index2]) {
  209. return false;
  210. }
  211. return (this._hasStrings ? this._modifiedStringElements[index1] === this._modifiedStringElements[index2] : true);
  212. }
  213. ComputeDiff(pretty) {
  214. return this._ComputeDiff(0, this._originalElementsOrHash.length - 1, 0, this._modifiedElementsOrHash.length - 1, pretty);
  215. }
  216. /**
  217. * Computes the differences between the original and modified input
  218. * sequences on the bounded range.
  219. * @returns An array of the differences between the two input sequences.
  220. */
  221. _ComputeDiff(originalStart, originalEnd, modifiedStart, modifiedEnd, pretty) {
  222. const quitEarlyArr = [false];
  223. let changes = this.ComputeDiffRecursive(originalStart, originalEnd, modifiedStart, modifiedEnd, quitEarlyArr);
  224. if (pretty) {
  225. // We have to clean up the computed diff to be more intuitive
  226. // but it turns out this cannot be done correctly until the entire set
  227. // of diffs have been computed
  228. changes = this.PrettifyChanges(changes);
  229. }
  230. return {
  231. quitEarly: quitEarlyArr[0],
  232. changes: changes
  233. };
  234. }
  235. /**
  236. * Private helper method which computes the differences on the bounded range
  237. * recursively.
  238. * @returns An array of the differences between the two input sequences.
  239. */
  240. ComputeDiffRecursive(originalStart, originalEnd, modifiedStart, modifiedEnd, quitEarlyArr) {
  241. quitEarlyArr[0] = false;
  242. // Find the start of the differences
  243. while (originalStart <= originalEnd && modifiedStart <= modifiedEnd && this.ElementsAreEqual(originalStart, modifiedStart)) {
  244. originalStart++;
  245. modifiedStart++;
  246. }
  247. // Find the end of the differences
  248. while (originalEnd >= originalStart && modifiedEnd >= modifiedStart && this.ElementsAreEqual(originalEnd, modifiedEnd)) {
  249. originalEnd--;
  250. modifiedEnd--;
  251. }
  252. // In the special case where we either have all insertions or all deletions or the sequences are identical
  253. if (originalStart > originalEnd || modifiedStart > modifiedEnd) {
  254. let changes;
  255. if (modifiedStart <= modifiedEnd) {
  256. Debug.Assert(originalStart === originalEnd + 1, 'originalStart should only be one more than originalEnd');
  257. // All insertions
  258. changes = [
  259. new DiffChange(originalStart, 0, modifiedStart, modifiedEnd - modifiedStart + 1)
  260. ];
  261. }
  262. else if (originalStart <= originalEnd) {
  263. Debug.Assert(modifiedStart === modifiedEnd + 1, 'modifiedStart should only be one more than modifiedEnd');
  264. // All deletions
  265. changes = [
  266. new DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, 0)
  267. ];
  268. }
  269. else {
  270. Debug.Assert(originalStart === originalEnd + 1, 'originalStart should only be one more than originalEnd');
  271. Debug.Assert(modifiedStart === modifiedEnd + 1, 'modifiedStart should only be one more than modifiedEnd');
  272. // Identical sequences - No differences
  273. changes = [];
  274. }
  275. return changes;
  276. }
  277. // This problem can be solved using the Divide-And-Conquer technique.
  278. const midOriginalArr = [0];
  279. const midModifiedArr = [0];
  280. const result = this.ComputeRecursionPoint(originalStart, originalEnd, modifiedStart, modifiedEnd, midOriginalArr, midModifiedArr, quitEarlyArr);
  281. const midOriginal = midOriginalArr[0];
  282. const midModified = midModifiedArr[0];
  283. if (result !== null) {
  284. // Result is not-null when there was enough memory to compute the changes while
  285. // searching for the recursion point
  286. return result;
  287. }
  288. else if (!quitEarlyArr[0]) {
  289. // We can break the problem down recursively by finding the changes in the
  290. // First Half: (originalStart, modifiedStart) to (midOriginal, midModified)
  291. // Second Half: (midOriginal + 1, minModified + 1) to (originalEnd, modifiedEnd)
  292. // NOTE: ComputeDiff() is inclusive, therefore the second range starts on the next point
  293. const leftChanges = this.ComputeDiffRecursive(originalStart, midOriginal, modifiedStart, midModified, quitEarlyArr);
  294. let rightChanges = [];
  295. if (!quitEarlyArr[0]) {
  296. rightChanges = this.ComputeDiffRecursive(midOriginal + 1, originalEnd, midModified + 1, modifiedEnd, quitEarlyArr);
  297. }
  298. else {
  299. // We didn't have time to finish the first half, so we don't have time to compute this half.
  300. // Consider the entire rest of the sequence different.
  301. rightChanges = [
  302. new DiffChange(midOriginal + 1, originalEnd - (midOriginal + 1) + 1, midModified + 1, modifiedEnd - (midModified + 1) + 1)
  303. ];
  304. }
  305. return this.ConcatenateChanges(leftChanges, rightChanges);
  306. }
  307. // If we hit here, we quit early, and so can't return anything meaningful
  308. return [
  309. new DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1)
  310. ];
  311. }
  312. WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr) {
  313. let forwardChanges = null;
  314. let reverseChanges = null;
  315. // First, walk backward through the forward diagonals history
  316. let changeHelper = new DiffChangeHelper();
  317. let diagonalMin = diagonalForwardStart;
  318. let diagonalMax = diagonalForwardEnd;
  319. let diagonalRelative = (midOriginalArr[0] - midModifiedArr[0]) - diagonalForwardOffset;
  320. let lastOriginalIndex = -1073741824 /* MIN_SAFE_SMALL_INTEGER */;
  321. let historyIndex = this.m_forwardHistory.length - 1;
  322. do {
  323. // Get the diagonal index from the relative diagonal number
  324. const diagonal = diagonalRelative + diagonalForwardBase;
  325. // Figure out where we came from
  326. if (diagonal === diagonalMin || (diagonal < diagonalMax && forwardPoints[diagonal - 1] < forwardPoints[diagonal + 1])) {
  327. // Vertical line (the element is an insert)
  328. originalIndex = forwardPoints[diagonal + 1];
  329. modifiedIndex = originalIndex - diagonalRelative - diagonalForwardOffset;
  330. if (originalIndex < lastOriginalIndex) {
  331. changeHelper.MarkNextChange();
  332. }
  333. lastOriginalIndex = originalIndex;
  334. changeHelper.AddModifiedElement(originalIndex + 1, modifiedIndex);
  335. diagonalRelative = (diagonal + 1) - diagonalForwardBase; //Setup for the next iteration
  336. }
  337. else {
  338. // Horizontal line (the element is a deletion)
  339. originalIndex = forwardPoints[diagonal - 1] + 1;
  340. modifiedIndex = originalIndex - diagonalRelative - diagonalForwardOffset;
  341. if (originalIndex < lastOriginalIndex) {
  342. changeHelper.MarkNextChange();
  343. }
  344. lastOriginalIndex = originalIndex - 1;
  345. changeHelper.AddOriginalElement(originalIndex, modifiedIndex + 1);
  346. diagonalRelative = (diagonal - 1) - diagonalForwardBase; //Setup for the next iteration
  347. }
  348. if (historyIndex >= 0) {
  349. forwardPoints = this.m_forwardHistory[historyIndex];
  350. diagonalForwardBase = forwardPoints[0]; //We stored this in the first spot
  351. diagonalMin = 1;
  352. diagonalMax = forwardPoints.length - 1;
  353. }
  354. } while (--historyIndex >= -1);
  355. // Ironically, we get the forward changes as the reverse of the
  356. // order we added them since we technically added them backwards
  357. forwardChanges = changeHelper.getReverseChanges();
  358. if (quitEarlyArr[0]) {
  359. // TODO: Calculate a partial from the reverse diagonals.
  360. // For now, just assume everything after the midOriginal/midModified point is a diff
  361. let originalStartPoint = midOriginalArr[0] + 1;
  362. let modifiedStartPoint = midModifiedArr[0] + 1;
  363. if (forwardChanges !== null && forwardChanges.length > 0) {
  364. const lastForwardChange = forwardChanges[forwardChanges.length - 1];
  365. originalStartPoint = Math.max(originalStartPoint, lastForwardChange.getOriginalEnd());
  366. modifiedStartPoint = Math.max(modifiedStartPoint, lastForwardChange.getModifiedEnd());
  367. }
  368. reverseChanges = [
  369. new DiffChange(originalStartPoint, originalEnd - originalStartPoint + 1, modifiedStartPoint, modifiedEnd - modifiedStartPoint + 1)
  370. ];
  371. }
  372. else {
  373. // Now walk backward through the reverse diagonals history
  374. changeHelper = new DiffChangeHelper();
  375. diagonalMin = diagonalReverseStart;
  376. diagonalMax = diagonalReverseEnd;
  377. diagonalRelative = (midOriginalArr[0] - midModifiedArr[0]) - diagonalReverseOffset;
  378. lastOriginalIndex = 1073741824 /* MAX_SAFE_SMALL_INTEGER */;
  379. historyIndex = (deltaIsEven) ? this.m_reverseHistory.length - 1 : this.m_reverseHistory.length - 2;
  380. do {
  381. // Get the diagonal index from the relative diagonal number
  382. const diagonal = diagonalRelative + diagonalReverseBase;
  383. // Figure out where we came from
  384. if (diagonal === diagonalMin || (diagonal < diagonalMax && reversePoints[diagonal - 1] >= reversePoints[diagonal + 1])) {
  385. // Horizontal line (the element is a deletion))
  386. originalIndex = reversePoints[diagonal + 1] - 1;
  387. modifiedIndex = originalIndex - diagonalRelative - diagonalReverseOffset;
  388. if (originalIndex > lastOriginalIndex) {
  389. changeHelper.MarkNextChange();
  390. }
  391. lastOriginalIndex = originalIndex + 1;
  392. changeHelper.AddOriginalElement(originalIndex + 1, modifiedIndex + 1);
  393. diagonalRelative = (diagonal + 1) - diagonalReverseBase; //Setup for the next iteration
  394. }
  395. else {
  396. // Vertical line (the element is an insertion)
  397. originalIndex = reversePoints[diagonal - 1];
  398. modifiedIndex = originalIndex - diagonalRelative - diagonalReverseOffset;
  399. if (originalIndex > lastOriginalIndex) {
  400. changeHelper.MarkNextChange();
  401. }
  402. lastOriginalIndex = originalIndex;
  403. changeHelper.AddModifiedElement(originalIndex + 1, modifiedIndex + 1);
  404. diagonalRelative = (diagonal - 1) - diagonalReverseBase; //Setup for the next iteration
  405. }
  406. if (historyIndex >= 0) {
  407. reversePoints = this.m_reverseHistory[historyIndex];
  408. diagonalReverseBase = reversePoints[0]; //We stored this in the first spot
  409. diagonalMin = 1;
  410. diagonalMax = reversePoints.length - 1;
  411. }
  412. } while (--historyIndex >= -1);
  413. // There are cases where the reverse history will find diffs that
  414. // are correct, but not intuitive, so we need shift them.
  415. reverseChanges = changeHelper.getChanges();
  416. }
  417. return this.ConcatenateChanges(forwardChanges, reverseChanges);
  418. }
  419. /**
  420. * Given the range to compute the diff on, this method finds the point:
  421. * (midOriginal, midModified)
  422. * that exists in the middle of the LCS of the two sequences and
  423. * is the point at which the LCS problem may be broken down recursively.
  424. * This method will try to keep the LCS trace in memory. If the LCS recursion
  425. * point is calculated and the full trace is available in memory, then this method
  426. * will return the change list.
  427. * @param originalStart The start bound of the original sequence range
  428. * @param originalEnd The end bound of the original sequence range
  429. * @param modifiedStart The start bound of the modified sequence range
  430. * @param modifiedEnd The end bound of the modified sequence range
  431. * @param midOriginal The middle point of the original sequence range
  432. * @param midModified The middle point of the modified sequence range
  433. * @returns The diff changes, if available, otherwise null
  434. */
  435. ComputeRecursionPoint(originalStart, originalEnd, modifiedStart, modifiedEnd, midOriginalArr, midModifiedArr, quitEarlyArr) {
  436. let originalIndex = 0, modifiedIndex = 0;
  437. let diagonalForwardStart = 0, diagonalForwardEnd = 0;
  438. let diagonalReverseStart = 0, diagonalReverseEnd = 0;
  439. // To traverse the edit graph and produce the proper LCS, our actual
  440. // start position is just outside the given boundary
  441. originalStart--;
  442. modifiedStart--;
  443. // We set these up to make the compiler happy, but they will
  444. // be replaced before we return with the actual recursion point
  445. midOriginalArr[0] = 0;
  446. midModifiedArr[0] = 0;
  447. // Clear out the history
  448. this.m_forwardHistory = [];
  449. this.m_reverseHistory = [];
  450. // Each cell in the two arrays corresponds to a diagonal in the edit graph.
  451. // The integer value in the cell represents the originalIndex of the furthest
  452. // reaching point found so far that ends in that diagonal.
  453. // The modifiedIndex can be computed mathematically from the originalIndex and the diagonal number.
  454. const maxDifferences = (originalEnd - originalStart) + (modifiedEnd - modifiedStart);
  455. const numDiagonals = maxDifferences + 1;
  456. const forwardPoints = new Int32Array(numDiagonals);
  457. const reversePoints = new Int32Array(numDiagonals);
  458. // diagonalForwardBase: Index into forwardPoints of the diagonal which passes through (originalStart, modifiedStart)
  459. // diagonalReverseBase: Index into reversePoints of the diagonal which passes through (originalEnd, modifiedEnd)
  460. const diagonalForwardBase = (modifiedEnd - modifiedStart);
  461. const diagonalReverseBase = (originalEnd - originalStart);
  462. // diagonalForwardOffset: Geometric offset which allows modifiedIndex to be computed from originalIndex and the
  463. // diagonal number (relative to diagonalForwardBase)
  464. // diagonalReverseOffset: Geometric offset which allows modifiedIndex to be computed from originalIndex and the
  465. // diagonal number (relative to diagonalReverseBase)
  466. const diagonalForwardOffset = (originalStart - modifiedStart);
  467. const diagonalReverseOffset = (originalEnd - modifiedEnd);
  468. // delta: The difference between the end diagonal and the start diagonal. This is used to relate diagonal numbers
  469. // relative to the start diagonal with diagonal numbers relative to the end diagonal.
  470. // The Even/Oddn-ness of this delta is important for determining when we should check for overlap
  471. const delta = diagonalReverseBase - diagonalForwardBase;
  472. const deltaIsEven = (delta % 2 === 0);
  473. // Here we set up the start and end points as the furthest points found so far
  474. // in both the forward and reverse directions, respectively
  475. forwardPoints[diagonalForwardBase] = originalStart;
  476. reversePoints[diagonalReverseBase] = originalEnd;
  477. // Remember if we quit early, and thus need to do a best-effort result instead of a real result.
  478. quitEarlyArr[0] = false;
  479. // A couple of points:
  480. // --With this method, we iterate on the number of differences between the two sequences.
  481. // The more differences there actually are, the longer this will take.
  482. // --Also, as the number of differences increases, we have to search on diagonals further
  483. // away from the reference diagonal (which is diagonalForwardBase for forward, diagonalReverseBase for reverse).
  484. // --We extend on even diagonals (relative to the reference diagonal) only when numDifferences
  485. // is even and odd diagonals only when numDifferences is odd.
  486. for (let numDifferences = 1; numDifferences <= (maxDifferences / 2) + 1; numDifferences++) {
  487. let furthestOriginalIndex = 0;
  488. let furthestModifiedIndex = 0;
  489. // Run the algorithm in the forward direction
  490. diagonalForwardStart = this.ClipDiagonalBound(diagonalForwardBase - numDifferences, numDifferences, diagonalForwardBase, numDiagonals);
  491. diagonalForwardEnd = this.ClipDiagonalBound(diagonalForwardBase + numDifferences, numDifferences, diagonalForwardBase, numDiagonals);
  492. for (let diagonal = diagonalForwardStart; diagonal <= diagonalForwardEnd; diagonal += 2) {
  493. // STEP 1: We extend the furthest reaching point in the present diagonal
  494. // by looking at the diagonals above and below and picking the one whose point
  495. // is further away from the start point (originalStart, modifiedStart)
  496. if (diagonal === diagonalForwardStart || (diagonal < diagonalForwardEnd && forwardPoints[diagonal - 1] < forwardPoints[diagonal + 1])) {
  497. originalIndex = forwardPoints[diagonal + 1];
  498. }
  499. else {
  500. originalIndex = forwardPoints[diagonal - 1] + 1;
  501. }
  502. modifiedIndex = originalIndex - (diagonal - diagonalForwardBase) - diagonalForwardOffset;
  503. // Save the current originalIndex so we can test for false overlap in step 3
  504. const tempOriginalIndex = originalIndex;
  505. // STEP 2: We can continue to extend the furthest reaching point in the present diagonal
  506. // so long as the elements are equal.
  507. while (originalIndex < originalEnd && modifiedIndex < modifiedEnd && this.ElementsAreEqual(originalIndex + 1, modifiedIndex + 1)) {
  508. originalIndex++;
  509. modifiedIndex++;
  510. }
  511. forwardPoints[diagonal] = originalIndex;
  512. if (originalIndex + modifiedIndex > furthestOriginalIndex + furthestModifiedIndex) {
  513. furthestOriginalIndex = originalIndex;
  514. furthestModifiedIndex = modifiedIndex;
  515. }
  516. // STEP 3: If delta is odd (overlap first happens on forward when delta is odd)
  517. // and diagonal is in the range of reverse diagonals computed for numDifferences-1
  518. // (the previous iteration; we haven't computed reverse diagonals for numDifferences yet)
  519. // then check for overlap.
  520. if (!deltaIsEven && Math.abs(diagonal - diagonalReverseBase) <= (numDifferences - 1)) {
  521. if (originalIndex >= reversePoints[diagonal]) {
  522. midOriginalArr[0] = originalIndex;
  523. midModifiedArr[0] = modifiedIndex;
  524. if (tempOriginalIndex <= reversePoints[diagonal] && 1447 /* MaxDifferencesHistory */ > 0 && numDifferences <= (1447 /* MaxDifferencesHistory */ + 1)) {
  525. // BINGO! We overlapped, and we have the full trace in memory!
  526. return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
  527. }
  528. else {
  529. // Either false overlap, or we didn't have enough memory for the full trace
  530. // Just return the recursion point
  531. return null;
  532. }
  533. }
  534. }
  535. }
  536. // Check to see if we should be quitting early, before moving on to the next iteration.
  537. const matchLengthOfLongest = ((furthestOriginalIndex - originalStart) + (furthestModifiedIndex - modifiedStart) - numDifferences) / 2;
  538. if (this.ContinueProcessingPredicate !== null && !this.ContinueProcessingPredicate(furthestOriginalIndex, matchLengthOfLongest)) {
  539. // We can't finish, so skip ahead to generating a result from what we have.
  540. quitEarlyArr[0] = true;
  541. // Use the furthest distance we got in the forward direction.
  542. midOriginalArr[0] = furthestOriginalIndex;
  543. midModifiedArr[0] = furthestModifiedIndex;
  544. if (matchLengthOfLongest > 0 && 1447 /* MaxDifferencesHistory */ > 0 && numDifferences <= (1447 /* MaxDifferencesHistory */ + 1)) {
  545. // Enough of the history is in memory to walk it backwards
  546. return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
  547. }
  548. else {
  549. // We didn't actually remember enough of the history.
  550. //Since we are quitting the diff early, we need to shift back the originalStart and modified start
  551. //back into the boundary limits since we decremented their value above beyond the boundary limit.
  552. originalStart++;
  553. modifiedStart++;
  554. return [
  555. new DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1)
  556. ];
  557. }
  558. }
  559. // Run the algorithm in the reverse direction
  560. diagonalReverseStart = this.ClipDiagonalBound(diagonalReverseBase - numDifferences, numDifferences, diagonalReverseBase, numDiagonals);
  561. diagonalReverseEnd = this.ClipDiagonalBound(diagonalReverseBase + numDifferences, numDifferences, diagonalReverseBase, numDiagonals);
  562. for (let diagonal = diagonalReverseStart; diagonal <= diagonalReverseEnd; diagonal += 2) {
  563. // STEP 1: We extend the furthest reaching point in the present diagonal
  564. // by looking at the diagonals above and below and picking the one whose point
  565. // is further away from the start point (originalEnd, modifiedEnd)
  566. if (diagonal === diagonalReverseStart || (diagonal < diagonalReverseEnd && reversePoints[diagonal - 1] >= reversePoints[diagonal + 1])) {
  567. originalIndex = reversePoints[diagonal + 1] - 1;
  568. }
  569. else {
  570. originalIndex = reversePoints[diagonal - 1];
  571. }
  572. modifiedIndex = originalIndex - (diagonal - diagonalReverseBase) - diagonalReverseOffset;
  573. // Save the current originalIndex so we can test for false overlap
  574. const tempOriginalIndex = originalIndex;
  575. // STEP 2: We can continue to extend the furthest reaching point in the present diagonal
  576. // as long as the elements are equal.
  577. while (originalIndex > originalStart && modifiedIndex > modifiedStart && this.ElementsAreEqual(originalIndex, modifiedIndex)) {
  578. originalIndex--;
  579. modifiedIndex--;
  580. }
  581. reversePoints[diagonal] = originalIndex;
  582. // STEP 4: If delta is even (overlap first happens on reverse when delta is even)
  583. // and diagonal is in the range of forward diagonals computed for numDifferences
  584. // then check for overlap.
  585. if (deltaIsEven && Math.abs(diagonal - diagonalForwardBase) <= numDifferences) {
  586. if (originalIndex <= forwardPoints[diagonal]) {
  587. midOriginalArr[0] = originalIndex;
  588. midModifiedArr[0] = modifiedIndex;
  589. if (tempOriginalIndex >= forwardPoints[diagonal] && 1447 /* MaxDifferencesHistory */ > 0 && numDifferences <= (1447 /* MaxDifferencesHistory */ + 1)) {
  590. // BINGO! We overlapped, and we have the full trace in memory!
  591. return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
  592. }
  593. else {
  594. // Either false overlap, or we didn't have enough memory for the full trace
  595. // Just return the recursion point
  596. return null;
  597. }
  598. }
  599. }
  600. }
  601. // Save current vectors to history before the next iteration
  602. if (numDifferences <= 1447 /* MaxDifferencesHistory */) {
  603. // We are allocating space for one extra int, which we fill with
  604. // the index of the diagonal base index
  605. let temp = new Int32Array(diagonalForwardEnd - diagonalForwardStart + 2);
  606. temp[0] = diagonalForwardBase - diagonalForwardStart + 1;
  607. MyArray.Copy2(forwardPoints, diagonalForwardStart, temp, 1, diagonalForwardEnd - diagonalForwardStart + 1);
  608. this.m_forwardHistory.push(temp);
  609. temp = new Int32Array(diagonalReverseEnd - diagonalReverseStart + 2);
  610. temp[0] = diagonalReverseBase - diagonalReverseStart + 1;
  611. MyArray.Copy2(reversePoints, diagonalReverseStart, temp, 1, diagonalReverseEnd - diagonalReverseStart + 1);
  612. this.m_reverseHistory.push(temp);
  613. }
  614. }
  615. // If we got here, then we have the full trace in history. We just have to convert it to a change list
  616. // NOTE: This part is a bit messy
  617. return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
  618. }
  619. /**
  620. * Shifts the given changes to provide a more intuitive diff.
  621. * While the first element in a diff matches the first element after the diff,
  622. * we shift the diff down.
  623. *
  624. * @param changes The list of changes to shift
  625. * @returns The shifted changes
  626. */
  627. PrettifyChanges(changes) {
  628. // Shift all the changes down first
  629. for (let i = 0; i < changes.length; i++) {
  630. const change = changes[i];
  631. const originalStop = (i < changes.length - 1) ? changes[i + 1].originalStart : this._originalElementsOrHash.length;
  632. const modifiedStop = (i < changes.length - 1) ? changes[i + 1].modifiedStart : this._modifiedElementsOrHash.length;
  633. const checkOriginal = change.originalLength > 0;
  634. const checkModified = change.modifiedLength > 0;
  635. while (change.originalStart + change.originalLength < originalStop
  636. && change.modifiedStart + change.modifiedLength < modifiedStop
  637. && (!checkOriginal || this.OriginalElementsAreEqual(change.originalStart, change.originalStart + change.originalLength))
  638. && (!checkModified || this.ModifiedElementsAreEqual(change.modifiedStart, change.modifiedStart + change.modifiedLength))) {
  639. const startStrictEqual = this.ElementsAreStrictEqual(change.originalStart, change.modifiedStart);
  640. const endStrictEqual = this.ElementsAreStrictEqual(change.originalStart + change.originalLength, change.modifiedStart + change.modifiedLength);
  641. if (endStrictEqual && !startStrictEqual) {
  642. // moving the change down would create an equal change, but the elements are not strict equal
  643. break;
  644. }
  645. change.originalStart++;
  646. change.modifiedStart++;
  647. }
  648. let mergedChangeArr = [null];
  649. if (i < changes.length - 1 && this.ChangesOverlap(changes[i], changes[i + 1], mergedChangeArr)) {
  650. changes[i] = mergedChangeArr[0];
  651. changes.splice(i + 1, 1);
  652. i--;
  653. continue;
  654. }
  655. }
  656. // Shift changes back up until we hit empty or whitespace-only lines
  657. for (let i = changes.length - 1; i >= 0; i--) {
  658. const change = changes[i];
  659. let originalStop = 0;
  660. let modifiedStop = 0;
  661. if (i > 0) {
  662. const prevChange = changes[i - 1];
  663. originalStop = prevChange.originalStart + prevChange.originalLength;
  664. modifiedStop = prevChange.modifiedStart + prevChange.modifiedLength;
  665. }
  666. const checkOriginal = change.originalLength > 0;
  667. const checkModified = change.modifiedLength > 0;
  668. let bestDelta = 0;
  669. let bestScore = this._boundaryScore(change.originalStart, change.originalLength, change.modifiedStart, change.modifiedLength);
  670. for (let delta = 1;; delta++) {
  671. const originalStart = change.originalStart - delta;
  672. const modifiedStart = change.modifiedStart - delta;
  673. if (originalStart < originalStop || modifiedStart < modifiedStop) {
  674. break;
  675. }
  676. if (checkOriginal && !this.OriginalElementsAreEqual(originalStart, originalStart + change.originalLength)) {
  677. break;
  678. }
  679. if (checkModified && !this.ModifiedElementsAreEqual(modifiedStart, modifiedStart + change.modifiedLength)) {
  680. break;
  681. }
  682. const touchingPreviousChange = (originalStart === originalStop && modifiedStart === modifiedStop);
  683. const score = ((touchingPreviousChange ? 5 : 0)
  684. + this._boundaryScore(originalStart, change.originalLength, modifiedStart, change.modifiedLength));
  685. if (score > bestScore) {
  686. bestScore = score;
  687. bestDelta = delta;
  688. }
  689. }
  690. change.originalStart -= bestDelta;
  691. change.modifiedStart -= bestDelta;
  692. const mergedChangeArr = [null];
  693. if (i > 0 && this.ChangesOverlap(changes[i - 1], changes[i], mergedChangeArr)) {
  694. changes[i - 1] = mergedChangeArr[0];
  695. changes.splice(i, 1);
  696. i++;
  697. continue;
  698. }
  699. }
  700. // There could be multiple longest common substrings.
  701. // Give preference to the ones containing longer lines
  702. if (this._hasStrings) {
  703. for (let i = 1, len = changes.length; i < len; i++) {
  704. const aChange = changes[i - 1];
  705. const bChange = changes[i];
  706. const matchedLength = bChange.originalStart - aChange.originalStart - aChange.originalLength;
  707. const aOriginalStart = aChange.originalStart;
  708. const bOriginalEnd = bChange.originalStart + bChange.originalLength;
  709. const abOriginalLength = bOriginalEnd - aOriginalStart;
  710. const aModifiedStart = aChange.modifiedStart;
  711. const bModifiedEnd = bChange.modifiedStart + bChange.modifiedLength;
  712. const abModifiedLength = bModifiedEnd - aModifiedStart;
  713. // Avoid wasting a lot of time with these searches
  714. if (matchedLength < 5 && abOriginalLength < 20 && abModifiedLength < 20) {
  715. const t = this._findBetterContiguousSequence(aOriginalStart, abOriginalLength, aModifiedStart, abModifiedLength, matchedLength);
  716. if (t) {
  717. const [originalMatchStart, modifiedMatchStart] = t;
  718. if (originalMatchStart !== aChange.originalStart + aChange.originalLength || modifiedMatchStart !== aChange.modifiedStart + aChange.modifiedLength) {
  719. // switch to another sequence that has a better score
  720. aChange.originalLength = originalMatchStart - aChange.originalStart;
  721. aChange.modifiedLength = modifiedMatchStart - aChange.modifiedStart;
  722. bChange.originalStart = originalMatchStart + matchedLength;
  723. bChange.modifiedStart = modifiedMatchStart + matchedLength;
  724. bChange.originalLength = bOriginalEnd - bChange.originalStart;
  725. bChange.modifiedLength = bModifiedEnd - bChange.modifiedStart;
  726. }
  727. }
  728. }
  729. }
  730. }
  731. return changes;
  732. }
  733. _findBetterContiguousSequence(originalStart, originalLength, modifiedStart, modifiedLength, desiredLength) {
  734. if (originalLength < desiredLength || modifiedLength < desiredLength) {
  735. return null;
  736. }
  737. const originalMax = originalStart + originalLength - desiredLength + 1;
  738. const modifiedMax = modifiedStart + modifiedLength - desiredLength + 1;
  739. let bestScore = 0;
  740. let bestOriginalStart = 0;
  741. let bestModifiedStart = 0;
  742. for (let i = originalStart; i < originalMax; i++) {
  743. for (let j = modifiedStart; j < modifiedMax; j++) {
  744. const score = this._contiguousSequenceScore(i, j, desiredLength);
  745. if (score > 0 && score > bestScore) {
  746. bestScore = score;
  747. bestOriginalStart = i;
  748. bestModifiedStart = j;
  749. }
  750. }
  751. }
  752. if (bestScore > 0) {
  753. return [bestOriginalStart, bestModifiedStart];
  754. }
  755. return null;
  756. }
  757. _contiguousSequenceScore(originalStart, modifiedStart, length) {
  758. let score = 0;
  759. for (let l = 0; l < length; l++) {
  760. if (!this.ElementsAreEqual(originalStart + l, modifiedStart + l)) {
  761. return 0;
  762. }
  763. score += this._originalStringElements[originalStart + l].length;
  764. }
  765. return score;
  766. }
  767. _OriginalIsBoundary(index) {
  768. if (index <= 0 || index >= this._originalElementsOrHash.length - 1) {
  769. return true;
  770. }
  771. return (this._hasStrings && /^\s*$/.test(this._originalStringElements[index]));
  772. }
  773. _OriginalRegionIsBoundary(originalStart, originalLength) {
  774. if (this._OriginalIsBoundary(originalStart) || this._OriginalIsBoundary(originalStart - 1)) {
  775. return true;
  776. }
  777. if (originalLength > 0) {
  778. const originalEnd = originalStart + originalLength;
  779. if (this._OriginalIsBoundary(originalEnd - 1) || this._OriginalIsBoundary(originalEnd)) {
  780. return true;
  781. }
  782. }
  783. return false;
  784. }
  785. _ModifiedIsBoundary(index) {
  786. if (index <= 0 || index >= this._modifiedElementsOrHash.length - 1) {
  787. return true;
  788. }
  789. return (this._hasStrings && /^\s*$/.test(this._modifiedStringElements[index]));
  790. }
  791. _ModifiedRegionIsBoundary(modifiedStart, modifiedLength) {
  792. if (this._ModifiedIsBoundary(modifiedStart) || this._ModifiedIsBoundary(modifiedStart - 1)) {
  793. return true;
  794. }
  795. if (modifiedLength > 0) {
  796. const modifiedEnd = modifiedStart + modifiedLength;
  797. if (this._ModifiedIsBoundary(modifiedEnd - 1) || this._ModifiedIsBoundary(modifiedEnd)) {
  798. return true;
  799. }
  800. }
  801. return false;
  802. }
  803. _boundaryScore(originalStart, originalLength, modifiedStart, modifiedLength) {
  804. const originalScore = (this._OriginalRegionIsBoundary(originalStart, originalLength) ? 1 : 0);
  805. const modifiedScore = (this._ModifiedRegionIsBoundary(modifiedStart, modifiedLength) ? 1 : 0);
  806. return (originalScore + modifiedScore);
  807. }
  808. /**
  809. * Concatenates the two input DiffChange lists and returns the resulting
  810. * list.
  811. * @param The left changes
  812. * @param The right changes
  813. * @returns The concatenated list
  814. */
  815. ConcatenateChanges(left, right) {
  816. let mergedChangeArr = [];
  817. if (left.length === 0 || right.length === 0) {
  818. return (right.length > 0) ? right : left;
  819. }
  820. else if (this.ChangesOverlap(left[left.length - 1], right[0], mergedChangeArr)) {
  821. // Since we break the problem down recursively, it is possible that we
  822. // might recurse in the middle of a change thereby splitting it into
  823. // two changes. Here in the combining stage, we detect and fuse those
  824. // changes back together
  825. const result = new Array(left.length + right.length - 1);
  826. MyArray.Copy(left, 0, result, 0, left.length - 1);
  827. result[left.length - 1] = mergedChangeArr[0];
  828. MyArray.Copy(right, 1, result, left.length, right.length - 1);
  829. return result;
  830. }
  831. else {
  832. const result = new Array(left.length + right.length);
  833. MyArray.Copy(left, 0, result, 0, left.length);
  834. MyArray.Copy(right, 0, result, left.length, right.length);
  835. return result;
  836. }
  837. }
  838. /**
  839. * Returns true if the two changes overlap and can be merged into a single
  840. * change
  841. * @param left The left change
  842. * @param right The right change
  843. * @param mergedChange The merged change if the two overlap, null otherwise
  844. * @returns True if the two changes overlap
  845. */
  846. ChangesOverlap(left, right, mergedChangeArr) {
  847. Debug.Assert(left.originalStart <= right.originalStart, 'Left change is not less than or equal to right change');
  848. Debug.Assert(left.modifiedStart <= right.modifiedStart, 'Left change is not less than or equal to right change');
  849. if (left.originalStart + left.originalLength >= right.originalStart || left.modifiedStart + left.modifiedLength >= right.modifiedStart) {
  850. const originalStart = left.originalStart;
  851. let originalLength = left.originalLength;
  852. const modifiedStart = left.modifiedStart;
  853. let modifiedLength = left.modifiedLength;
  854. if (left.originalStart + left.originalLength >= right.originalStart) {
  855. originalLength = right.originalStart + right.originalLength - left.originalStart;
  856. }
  857. if (left.modifiedStart + left.modifiedLength >= right.modifiedStart) {
  858. modifiedLength = right.modifiedStart + right.modifiedLength - left.modifiedStart;
  859. }
  860. mergedChangeArr[0] = new DiffChange(originalStart, originalLength, modifiedStart, modifiedLength);
  861. return true;
  862. }
  863. else {
  864. mergedChangeArr[0] = null;
  865. return false;
  866. }
  867. }
  868. /**
  869. * Helper method used to clip a diagonal index to the range of valid
  870. * diagonals. This also decides whether or not the diagonal index,
  871. * if it exceeds the boundary, should be clipped to the boundary or clipped
  872. * one inside the boundary depending on the Even/Odd status of the boundary
  873. * and numDifferences.
  874. * @param diagonal The index of the diagonal to clip.
  875. * @param numDifferences The current number of differences being iterated upon.
  876. * @param diagonalBaseIndex The base reference diagonal.
  877. * @param numDiagonals The total number of diagonals.
  878. * @returns The clipped diagonal index.
  879. */
  880. ClipDiagonalBound(diagonal, numDifferences, diagonalBaseIndex, numDiagonals) {
  881. if (diagonal >= 0 && diagonal < numDiagonals) {
  882. // Nothing to clip, its in range
  883. return diagonal;
  884. }
  885. // diagonalsBelow: The number of diagonals below the reference diagonal
  886. // diagonalsAbove: The number of diagonals above the reference diagonal
  887. const diagonalsBelow = diagonalBaseIndex;
  888. const diagonalsAbove = numDiagonals - diagonalBaseIndex - 1;
  889. const diffEven = (numDifferences % 2 === 0);
  890. if (diagonal < 0) {
  891. const lowerBoundEven = (diagonalsBelow % 2 === 0);
  892. return (diffEven === lowerBoundEven) ? 0 : 1;
  893. }
  894. else {
  895. const upperBoundEven = (diagonalsAbove % 2 === 0);
  896. return (diffEven === upperBoundEven) ? numDiagonals - 1 : numDiagonals - 2;
  897. }
  898. }
  899. }