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 :)