Word Scrambler
by marakoss
TypeScript
/* Minimal, but easilly readable & understandable code, but also wrong */
function isScrambleWrong(scrambled: string, needle: string) {
for (var i = 0; i < needle.length; i++) {
if (scrambled.indexOf(needle[i]) === -1)
return false;
}
return true;
}
console.log(isScrambleWrong('rekqodlw', 'world')) // true
console.log(isScrambleWrong('cedewaraaossoqqyt', 'codewars')) // true
console.log(isScrambleWrong('katas', 'steak')) // false
console.log(isScrambleWrong('bol', 'bool')) // returns true, should return false
/* Version that fixes repeating letters edge-case */
const isScramble = (scrambled: string, needle: string): boolean => {
let isScrambled = true;
let current = needle[ 0 ];
let index = scrambled.indexOf( current );
if ( index === -1 )
return false;
if ( needle.length > 1 ) {
let dropout = scrambled.slice( 0, index ).concat( scrambled.slice( index + 1 ) );
isScrambled = isScramble( dropout, needle.slice( 1 ) );
}
return isScrambled;
}
console.log(isScramble('rekqodlw', 'world')) // true
console.log(isScramble('cedewaraaossoqqyt', 'codewars')) // true
console.log(isScramble('katas', 'steak')) // false
console.log(isScramble('bol', 'bool')) // false
console.log(isScramble('loob', 'bool')) // true