In JavaScript I have a simple function I used to reverse a string, but my trainer at work says that I can cut the processing time in half within my for loop. My trainer doesn’t want me to use the split/reverse/join functions. So that is why I am doing this in a for loop.
At first I thought using the charAT() function was the best way to achieve this, then I switched to just using brackets + the index position.
Currently scratching my head on how to make this more optimal and am wondering if it is maybe not a problem of the contents of the for loop, but maybe how I structured it in the first place?
function reversalFunct(initString) {
let reverseString = '';
for (let i = initString.length - 1; i >= 0; i--){
reverseString += initString[i];
}
return reverseString;
}
2
Answers
Even within the training context, an array based collector for aggregating the reversed string data does not contradict the algorithm, the trainer/teacher might have in mind.
Thus, create a
result
array of same length of string and initialize a counter value of rounded half the length of the string’s length. Count down this value to zero while separately incrementing a left side index starting from -1 and decrementing a right side index starting from the string’s length.Then assign the string’s right index related character to the array’s left index position and the string’s left index related character to the arrays right index position. The iteration steps have been cut to half and the
result
array gets returned as its ownjoin
ed string value representation.You can think of the inversion problem as mirroring the string.
The first letter of the input string should end up at the last position in the result. In the same way, the last letter of the input string should end up at the first position in the result.
Therefore, you can iterate your input string only until half of its length and build the result from the middle part adding to the left and to the right of that center as you go.
You will have to take into account that if the length of the string is odd you have to start the result string with the letter in the middle: