Search code examples
javascriptloopsobject

How to check if a str2 can be made from str1 using objects


I've been struggling to find out how to return false when the count goes below 0, tried playing with the 2nd loop, however I don't know how to stop the count as soon as it reaches 0

let char = {}

function charCount(str1, str2) {
  str1 = str1.toLowerCase()
  str2 = str2.toLowerCase()

  for (i = 0; i < str1.length; i++) {
    if (str1[i] in char) {
      char[str1[i]]++
    } else {
      char[str1[i]] = 1
    }
  }

  for (i = 0; i < str2.length; i++) {
    // Error is found here
    if (str2[i] in char) {
      char[str2[i]]--
    } else {
      return false
    }
  }
  console.log(char)
  return true
}
console.log(charCount("hello", "helllo"))

Output

{h: 0, e: 0, l: -1, o: 0}
true

Solution

  • You could check if the property has a truthy value , then decrement, otherwise exit the loop with false.

    BTW, you should declare varaibles, otherwise you get global variables which may lead to confusions.

    function charCount(str1, str2) {
        let char = {};
        str1 = str1.toLowerCase();
        str2 = str2.toLowerCase();
    
        for (let i = 0; i < str1.length; i++) {
            if (str1[i] in char) char[str1[i]]++;
            else char[str1[i]] = 1;
        }
    
        for (let i = 0; i < str2.length; i++) {
            if (char[str2[i]]) char[str2[i]]--;
            else return false;
        }
        return true;
    }
    
    console.log(charCount("hello", "helllo"));