diffStrings.js
 1  'use strict';
 2  
 3  Object.defineProperty(exports, '__esModule', {
 4    value: true
 5  });
 6  exports.default = void 0;
 7  
 8  var _diffSequences = _interopRequireDefault(require('diff-sequences'));
 9  
10  var _cleanupSemantic = require('./cleanupSemantic');
11  
12  function _interopRequireDefault(obj) {
13    return obj && obj.__esModule ? obj : {default: obj};
14  }
15  
16  /**
17   * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
18   *
19   * This source code is licensed under the MIT license found in the
20   * LICENSE file in the root directory of this source tree.
21   */
22  const diffStrings = (a, b) => {
23    const isCommon = (aIndex, bIndex) => a[aIndex] === b[bIndex];
24  
25    let aIndex = 0;
26    let bIndex = 0;
27    const diffs = [];
28  
29    const foundSubsequence = (nCommon, aCommon, bCommon) => {
30      if (aIndex !== aCommon) {
31        diffs.push(
32          new _cleanupSemantic.Diff(
33            _cleanupSemantic.DIFF_DELETE,
34            a.slice(aIndex, aCommon)
35          )
36        );
37      }
38  
39      if (bIndex !== bCommon) {
40        diffs.push(
41          new _cleanupSemantic.Diff(
42            _cleanupSemantic.DIFF_INSERT,
43            b.slice(bIndex, bCommon)
44          )
45        );
46      }
47  
48      aIndex = aCommon + nCommon; // number of characters compared in a
49  
50      bIndex = bCommon + nCommon; // number of characters compared in b
51  
52      diffs.push(
53        new _cleanupSemantic.Diff(
54          _cleanupSemantic.DIFF_EQUAL,
55          b.slice(bCommon, bIndex)
56        )
57      );
58    };
59  
60    (0, _diffSequences.default)(a.length, b.length, isCommon, foundSubsequence); // After the last common subsequence, push remaining change items.
61  
62    if (aIndex !== a.length) {
63      diffs.push(
64        new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_DELETE, a.slice(aIndex))
65      );
66    }
67  
68    if (bIndex !== b.length) {
69      diffs.push(
70        new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_INSERT, b.slice(bIndex))
71      );
72    }
73  
74    return diffs;
75  };
76  
77  var _default = diffStrings;
78  exports.default = _default;