Skip to content

Instantly share code, notes, and snippets.

@strickvl
Created July 29, 2020 06:21
Show Gist options
  • Save strickvl/7ca16a1233083748ced164c8a2eb1328 to your computer and use it in GitHub Desktop.
Save strickvl/7ca16a1233083748ced164c8a2eb1328 to your computer and use it in GitHub Desktop.
function sameChars(str1, str2) {
let str1Arr = str1.split('');
let str2Arr = str2.split('');
for (let index = 0; index < str2Arr.length; index += 1) {
let char = str2Arr[index];
if (!str1.includes(char)) return false;
}
return true;
}
function isMerge(string, part1, part2) {
let stringArr = string.split('');
let part1Arr = part1.split('');
let part2Arr = part2.split('');
let placeInString = 0;
let regexstring = `[${string}]`
let regex = new RegExp(regexstring, 'gi');
if (sameChars(string, part1) === false || sameChars(string, part2) === false) return false;
if ((part1.length + part2.length) !== string.length) return false;
for (let index = 0; index < part1Arr.length; index += 1) {
let char = part1Arr[index];
let charIndexInString = stringArr.indexOf(char);
if (charIndexInString >= placeInString) {
stringArr.splice(charIndexInString, 1);
placeInString = charIndexInString;
} else {
return false;
}
}
placeInString = 0;
for (let index = 0; index < part2Arr.length; index += 1) {
let char = part2Arr[index];
let charIndexInString = stringArr.indexOf(char);
if (charIndexInString >= placeInString) {
stringArr.splice(charIndexInString, 1);
placeInString = charIndexInString;
} else {
return false;
}
}
if (stringArr.length !== 0) return false;
return true;
}
console.log(isMerge('codewars', 'code', 'wars')); // true
console.log(isMerge('codewars', 'cdw', 'oears')); // true
console.log(isMerge('codewars', 'oears', 'cdw')); // true
console.log(isMerge('codewars', 'cod', 'wars')); // false
console.log(isMerge('codewars', 'cod', 'war%')); // false
console.log(isMerge('codewars', 'co3', 'wars')); // false
console.log(isMerge('codewars', 'dcw', 'oears')); // false
console.log(isMerge('codewars', 'cdw', 'eoars')); // false
console.log(isMerge('codewars', 'cod', 'ewars')); // true
console.log(isMerge('codewars', 'coe', 'dwars')); // true
console.log(isMerge('codewars', 'codd', 'ewars')); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment