-3

I'm basically trying to write a function which when called, performs the action of the endsWith() method

I've tried iterating through the original string and the string to be tested using for loops

function confirmEnding(str, target) {
  let strWord = '';
  let targetWord = '';
  for (let i = (target.length - 1); i >= 0; i--) {
    targetWord.concat(target.charAt(i))
    for (let j = (str.length - 1); j >= 0; j--) {
      strWord.concat(str.charAt(j));

    }
  }
  if (strWord == targetWord) {
    return true
  } else {
    return false
  }
}

Now anytime i call the function, it returns true, what's wrong with my code?

Ori Drori
  • 183,571
  • 29
  • 224
  • 209
RogueCode
  • 1
  • 3
  • 4
    strings are immutable. So, `targetWord.concat` doesn't change the original string – adiga Nov 08 '19 at 13:02
  • 5
    [String.concat()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat) like other string methods returns a new string it doesnt modify the original string – Patrick Evans Nov 08 '19 at 13:02

2 Answers2

0

Primarily, what's wrong with it is that you're using nested loops. There's no need to do that.

The simple, easy way (other than using endsWith!) is to grab the end of str (using the length of target), then compare that substring against target:

function confirmEnding(str, target) {
    return str.length >= target.length && str.slice(-target.length) === target;
}

Re your actual code:

  1. concat doesn't modify the string you call it on, it returns a new string (it has to; strings are immutable [unchangeable] in JavaScript)

  2. If you fix #1, your outer loop just copies target to targetWord but in reverse order. Your inner loop copies str to strWord in reverse order repeatedly, so you'll end up with target.length copies of it in strWord.

  3. Nothing in the function tries to take only part of str (the last part, with the same length as target). You end up comparing the full strings (if you fix #1 and #2), not the substring at the end of str.

Finally, just a side note: Any time you find yourself writing:

if (a == b) {
    return true;
} else {
    return false;
}

you can more concisely and idiomatically write

return a == b;

which does exactly the same thing. :-)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

concat returns the new string.

Use strWord += whatever; instead.

Mika Feiler
  • 474
  • 3
  • 17