scramble

    0

    0

    /*
    Complete the function scramble(str1, str2) that returns true if a portion of str1 characters
    can be rearranged to match str2, otherwise returns false.
    */
    
    //less efficient:
    
    function scramble(str1, str2) {
      var splitString1 = str1.split('');
      var splitString2 = str2.split('');
      var results = [];
      
        for(let i=0; i < splitString1.length; i++) {
          if(splitString2.indexOf(splitString1[i]) !== -1) {
            results.push(splitString1[i]);
            splitString2.splice(splitString2.indexOf(splitString1[i]), 1);
    
            if(results.length === str2.length) return true;
          }
        }
      
      if(results.length !== str2.length) return false;
    }
    
    
    //more efficient
    
    function scramble(str1, str2) {
      
      const reducer = (container, element) => {
        if(container[element] === undefined) {
          container[element] = 1;
          return container;
        } else {
          container[element] += 1;
          return container;
        }
      }
      
      var container1 = str1.split('').reduce(reducer,{});
      
      var container2 = str2.split('').reduce(reducer,{});
      
      for (var prop in container2) {
        if(!container1[prop]) return false;
        
        if(container1[prop] < container2[prop]) return false;
      }
      return true;
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.