DEV Community

Cover image for JavaScript 🐲 challenges_6 ⚔️
Mahmoud EL-kariouny
Mahmoud EL-kariouny

Posted on

JavaScript 🐲 challenges_6 ⚔️

Scramblies

  • Complete the function scramble(str1, str2) that returns true.
  • If a portion of str1 characters can be rearranged to match str2,
  • otherwise returns false.

Note:

  • Only lower case letters will be used (a-z).
  • No punctuation or digits will be included.
  • Performance needs to be considered.

Example:

scramble('rkqodlw', 'world') ==> True
scramble('cedewaraaossoqqyt', 'codewars') ==> True
scramble('katas', 'steak') ==> False
Enter fullscreen mode Exit fullscreen mode

Task URL

My solution:

function scramble(str1, str2) {

    const stringOne = str1.split('');
    const stringTwo = str2.split('');
    const charCounts = {};

    for (let i = 0; i < stringOne.length; i++) {

        const char = stringOne[i];

        if (charCounts[char]) { // character already seen

            charCounts[char]++;

        } else {  // first time seeing character

            charCounts[char] = 1;
        }
    };

    for (let i = 0; i < stringTwo.length; i++) {

        const char = stringTwo[i]

        if (!charCounts[char]) {

            return false;
        }
        charCounts[char]--;
    };

    return true;

};

Enter fullscreen mode Exit fullscreen mode

Code Snapshot:

Image description

10 JavaScript Games to learn-Totally Cool & Fun 🚀✨🔥

🎥

Connect with Me 😊

🔗 Links

linkedin

twitter

Top comments (2)

Collapse
 
vupadhayayx86 profile image
vupadhayayx86

You can simply use for..of loop

function scramble(str1,str2){
for(let x of str2){
if(!str1.includes(x)){
return false
}
}
return true;
}

console.log(scramble('rkqodlw', 'world'))
console.log(scramble('cedewaraaossoqqyt', 'codewars'))
console.log(scramble('katas', 'steak'))

Collapse
 
mahmoudessam profile image
Mahmoud EL-kariouny

Thank you :)