2

I want to create a function to compare two strings and return changes in string (like Stack Overflow shows changes in answer which was edited).

Expected results should be.

console.log(detectChange("SHANTI DEVI","SHANT DEVI"));    // SHANT_I_ DEVI
console.log(detectChange("MOHAN SINGH","MOHAN SINGH"));   // MOHAN SINGH
console.log(detectChange("SURESH SINGH","MOHAN SINGH"));  // -MOHAN-_SURESH_ SINGH
console.log(detectChange("SEETA DEVI","SITA SINGH"));     // S-I-_EE_TA -SINGH-_DEVI_
  • First parameter is the new value and second parameter is the old value.
  • Bracket letter or word using "-" if that word or letter was removed
  • The word or letter that was added should be bracketed using "_"

The below code was unsuccessful for me.

function detectChange(name1, name2) {
  name1 = name1.split("");
  name2 = name2.split("");
  var visit = 0;
  var final_name = [];
  if (name2.length > name1.length) {
    nameTmp = name1;
    name1 = name2;
    name2 = nameTmp;
  }

  for (i = 0; i <= name1.length; i++) {
    if (name1[i] == name2[visit]) {
      final_name.push(name1[i]);
      visit++;

    } else if (name1[i] !== null) {
      final_name.push("_" + name1[i] + "_");
      visit++;
    }
  }
  return final_name.join("");
}

// Getting unexpected results
console.log(detectChange("SHANTI DEVI", "SHANT DEVI")); // SHANT_I__ __D__E__V__I_
console.log(detectChange("MOHAN SINGH", "MOHAN SINGH")); // MOHAN SINGH
console.log(detectChange("SURESH SINGH", "MOHAN SINGH")); // _S__U__R__E__S__H__ __S__I__N__G__H_
console.log(detectChange("SEETA DEVI", "SITA SINGH")); // S_E__E__T__A__ __D__E__V__I_

Here every single output is invalid, please help me regarding this how can I handle this.

maraaaaaaaa
  • 7,749
  • 2
  • 22
  • 37
Harendra Chauhan
  • 262
  • 2
  • 12

1 Answers1

0

You probably want to read this paper, "An O(ND) Difference Algorithm and Its Variations". Here's the abstract:

Abstract The problems of finding a longest common subsequence of two sequences A and B and a shortest edit script for transforming A into B have long been known to be dual problems. In this paper, they are shown to be equivalent to finding a shortest/longest path in an edit graph. Using this perspective, a simple O(ND) time and space algorithm is developed where N is the sum of the lengths of A and B and D is the size of the minimum edit script for A and B. The algorithm performs well when differences are small (sequences are similar) and is consequently fast in typical applications. The algorithm is shown to have O(N + D2) expected-time performance under a basic stochastic model. A refinement of the algorithm requires only O(N) space, and the use of suffix trees leads to an O(NlgN + D2) time variation.

And then implement the algorithm.

But no... you don't actually want to do that, because it's already been done for you: See the npm package diff.

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135