hrthimrn commited on
Commit
4052150
·
1 Parent(s): 566409b

Refactor substitution logic in substituteCipherText function

Browse files
Files changed (1) hide show
  1. main.js +4 -8
main.js CHANGED
@@ -77,15 +77,11 @@ function countTrigrams(str) {
77
  }
78
 
79
  function substituteCipherText(cipherText, substitutionMap) {
80
- let substitutedText = '';
81
  substitutionMap = constructMapFromInput(substitutionMap);
82
- for (let i = 0; i < cipherText.length; i++) {
83
- const letter = cipherText[i];
84
- if (substitutionMap.has(letter)) {
85
- substitutedText += substitutionMap.get(letter);
86
- } else {
87
- substitutedText += letter;
88
- }
89
  }
90
  console.log(substitutedText);
91
  return substitutedText;
 
77
  }
78
 
79
  function substituteCipherText(cipherText, substitutionMap) {
 
80
  substitutionMap = constructMapFromInput(substitutionMap);
81
+ let substitutedText = cipherText;
82
+ for (let [key, value] of substitutionMap) {
83
+ let regex = new RegExp(key, "g"); //global regex meaning it will replace all matching string, not just the first one
84
+ substitutedText = substitutedText.replace(regex, value);
 
 
 
85
  }
86
  console.log(substitutedText);
87
  return substitutedText;