Basic Algorithm Scripting: Confirm the Ending [Alternate Way of Solving]

Hi guys,

I’ve been trying to tackle this problem without using built-in functions, but by using some of the knowledge I have in data-structures. With the following code:

function getToLastWord(str) {
  let result = []
  let garbage = []
  
  let strToLst = str.split(" ");
  
  for(let i = 0; i < strToLst.length + 1; i++){
    if (strToLst.length === 1){
      result.push(strToLst[0]);
      strToLst.shift();
    }
    else{
      garbage.push(strToLst[0]);
      strToLst.shift();
    }
  }
  return result.join("").split("");
}




function confirmEnding(str, target) {
  // "Never give up and good luck will find you."
  // -- Falcor
  const builder = []
  const garbage = []
  
  let strLst = getToLastWord(str);
  let targetLst = target.split("");
  let x = 0;
  
  for(let i = 0; i < strLst.length; i++){
    console.log(strLst[i])
    console.log(strLst[i].toLowerCase() == targetLst[0].toLowerCase())
    
    if(target.length > 1){
      if(strLst[i].toLowerCase() == targetLst[x].toLowerCase()){
        builder.push(strLst[i])
        targetLst.shift();
      } else{
        garbage.unshift(strLst[i]);
        strLst.shift();
      }
    } 
    
    else{
      if(strLst[i].toLowerCase() == targetLst[0].toLowerCase()){
        builder.push(strLst[i])
      } else{
        garbage.unshift(strLst[i]);
        strLst.shift();
      }
    }
  }
  
  console.log(builder);
  console.log(garbage);
  console.log(strLst);
  return builder.join('').toLowerCase() == target.toLowerCase('');
}

I was able to get all test cases done, except two. I was aware that my logic has the flaw that it doesn’t take into account what consecutive is to confirm that whatever it’s looking for is a sub-string. In other words, how was the built-in substring() method created? At a glance it seems impossible trying to quantify what “consecutive” means in code, however it seems possible considering the method exists.

Your getLastWord function is completely unnecessary. You really don’t care about the last word in str. Instead, you should only care about the last characters of str.

One approach to solving this challenge is to get a count of the current characters of the target string (think about using length property of the string) and then use the count obtained earlier to only compare the last count characters with target. If they match, you return true, otherwise you return false.

Solving it in the way I have described does not use substring or substr or any built-in string method.

oh ok, that makes so much more sense. Thank you!