-
-
Save samundrak/be07fd4cbd7c2e9221b469ac891edd30 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function insertInArray(string, index, arr) { | |
const sliceBefore = arr.slice(0, index); | |
const sliceAfter = arr.slice(index, arr.length); | |
return sliceBefore.concat([string], sliceAfter); | |
} | |
function differ(arr1, arr2) { | |
const diff = []; | |
arr2.forEach((element, index) => { | |
if (element !== arr1[index]) { | |
diff.push({ matched: false, element, index }); | |
} | |
}); | |
return diff; | |
} | |
function insert(s, t) { | |
const string1 = s.split(''); | |
const string2 = t.split(''); | |
const diff = differ(string1, string2); | |
let insertion = null; | |
diff.every((item) => { | |
if ( | |
String(insertInArray(item.element, item.index, string1)) === | |
String(string2) | |
) { | |
insertion = item; | |
return false; | |
} | |
return true; | |
}); | |
return insertion; | |
} | |
function replace(s, t) { | |
const string1 = s.split(''); | |
const string2 = t.split(''); | |
const diffs = differ(string1, string2); | |
let replacer = null; | |
diffs.every((item) => { | |
const copyOfString1 = [...string1]; | |
copyOfString1.splice(item.index, 1, item.element); | |
if (String(copyOfString1) === String(string2)) { | |
replacer = item; | |
replacer.toBeReplaced = string1[item.index]; | |
return false; | |
} | |
return true; | |
}); | |
return replacer; | |
} | |
function solution(S, T) { | |
const normalizedS = (S || '').toLowerCase(); | |
const normalizedT = (T || '').toLowerCase(); | |
const si = insert(normalizedS, normalizedT); | |
if (si) { | |
return `INSERT ${si.element}`; | |
} | |
const sr = replace(normalizedS, normalizedT); | |
if (sr) { | |
return `REPLACE ${sr.toBeReplaced} ${sr.element}`; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment