Search code examples
javascriptstringreplaceparentheses

Avoid replacement of previous letters with string.replace


I'm doing a CodeWars kata that encodes words to open or closed parentheses based on the repetition of its letters. Here is the link.

My code it's working with all the tests but one, when word equals to " ( ( )".

I think I figured out that on the last ")", the first "(" is being changed to ")" due to replace's match, changing the expected output. Is there any way to prevent this unwanted change on my output?

const duplicateEncode = (word) => {
  let words = word.toLowerCase();
  let obj = {};
  for (let i of words) {
    obj[i] = obj[i] ? obj[i] + 1 : 1;
  }
  for (let i of words) {
    obj[i] === 1
      ? (words = words.replace(i, "("))
      : (words = words.replace(i, ")"));
  }
  return words;
};

Expected output

duplicateEncode(" ( ( )")); // )))))(

My output

duplicateEncode(" ( ( )")); // ()))))

Solution

  • Don't use String.replace on the whole word, you should modify each character directly, or better yet just construct a new string to return.

    const duplicateEncode = (word) => {
      let words = word.toLowerCase();
      let obj = {};
      for (let i of words) {
        obj[i] = obj[i] ? obj[i] + 1 : 1;
      }
      let out = "";
      for (let i of words) {
        out += obj[i] === 1 ? "(" : ")";
      }
      return out;
    };
    
    console.log(duplicateEncode(" ( ( )"));
    // )))))(