Intermediate Algorithm Scripting: Search and Replace

Intermediate Algorithm Scripting: Search and Replace
0

#1

I was looking through the “Code Solutions” for this challenge, and noticed that none of the solutions presented use the same methods I did. My solution is below. I am wondering if my solution is sub-standard in some way, and if I should be using different methods than the ones I used for some reason.

(Solution is blurred as it is a working solution)

function myReplace(str, before, after) {
  if(before[0] == before[0].toUpperCase()) {
    let split = after.split('');
    split[0] = split[0].toUpperCase()
    after = split.join('');
  }
  return str.replace(before, after);
}

Thank you, in advance, for your thoughts.

Search and Replace


#2

Your solution is basically the same as the basic solution.

A few tiny things I’d change are:

if (before[0] == before[0].toUpperCase()) {

It is generally better to use === if you can. The == is for when you don’t know what the type is and don’t care. But here we know the type so we don’t need the operator to go through and check all the possible types.

I that the logic inside the if block could be a little better. Here you are splitting into and array and joining. That takes time and memory. Does it matter much in this particular solution? Probably not. But it’s good to learn to think that way and at least be aware of it. I think something like:

if(before[0] == before[0].toUpperCase()) {

does the same thing in fewer lines, is easier to read, and faster:

after = after[0].toUpperCase() + after.slice(1)

I don’t really see any advantage that your logic has over this.

As for the intermediate and advanced solutions, I don’t particularly like them.

The intermediate solution is just your with regex. Regex is “sexy” and everyone drools over it. Don’t get me wont, it is a powerful tool. But I think it is overkill here.

I think it would be worthwhile to look at those others and see what they are doing. But unless someone shows me that they are somehow superior in some way other than, “It’s cool, bro!” then I prefer the very clear basic solution. And yours, with those two tweaks is basically the same thing.

Keep up the good work.


#3

One difference between your solution and the basic one is that you are checking if the before is capitalized and it is checking if that word is capitalized in the text. The problem definition is not clear on which to check and yours passes the tests so I guess it’s alright.


#4

Thank you for your changes!

I did noticed that the problem is technically asking for a solution that searches through the text, but if you are passing the “before” as an argument, it seems a bit redundant to search through the text as well.


#5

It depends on what they want. Do they want the after capitalized if the text is capitalized? If the before is capitalized? Or either?