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

Time:12-17

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

CodePudding user response:

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"));

CodePudding user response:

Reverse your if condition and add a check for the count reaching 0.

    if (str2[i] not in char || str2[i] == 0) {
      return false;
    } else {
      char[str2[i]]--;
    }
  • Related