Can anyone explain what's the mistake in the below code?
function reverseString(str) {
let reversedStr = "";
for (let i = 0; i < str.length; i++) {
reversedStr.unshift(str[i]);
return str;
}
}
console.log(
reverseString("hello")
)
You need an array to do unshift and the return outside the loop
const reverseString = str => {
const rev = [];
for (let i = 0; i < str.length; i++) rev.unshift(str[i])
return rev.join("")
};
console.log(
reverseString("hello")
)
but here is a oneliner
const reverseString = str => str ? [...str].reverse().join("") : str;
console.log(
reverseString("hello")
)
function reverseString(str) {
let arr = [];
for (let i = 0; i < str.length; i++) {
arr.unshift(str[i]);
}
return arr.join("");
}
console.log(reverseString("hello"));
If you meant to do the string reverse without using a util function, you can do it like below. If the string length is n then the time complexity of the below code is O(n/2).
function reverseString(str) {
// get single characters into array
const arrOfChars = str.split("");
// get the half size of the array
const halfLengthOfArr = Math.floor(arrOfChars.length / 2);
// start index
let i = 0;
// swap chars until reach the middle of the array
// h e l l o
// ^ ^
// o e l l h
// ^ ^
// o l l e h
while (i < halfLengthOfArr) {
// swap coupterparts from start and end with same distance
const start = arrOfChars[i];
arrOfChars[i] = arrOfChars[arrOfChars.length - (i + 1)];
arrOfChars[arrOfChars.length - (i + 1)] = start;
i++;
}
// return the output array as a string
return arrOfChars.join("");
}
console.log(reverseString("hello"));
I recommend completely going away from the unshift approach based on your requirement.
Therefore, I've designed two versions of your function for you and all are based purely on array functions.
Compact version:
function reverseString(str) {
return str.split("").reverse().join("")
}
console.log(
reverseString("hello")
)
Longer version (easier to understand):
function reverseString(str) {
const characters = str.split("")
const charactersReversed = characters.reverse()
return charactersReversed.join("")
}
console.log( reverseString("hello") )
I hope that helped, even if I don't address your unshift request.
Last but not least, I've also reworked your initial code with your unshift function, even if I don't recommend this code in production:
function reverseString(str) {
const reversedStr = [];
for (let i = 0; i < str.length; i++) {
reversedStr.unshift(str[i]);
}
return reversedStr.join("");
}
console.log(
reverseString("hello")
)