Right, so don't use the reverse()
helper because it would make the algorithm solution too easy.
Every solution thus far has made use of the for
loop, excellent. I don't like using it anyway.
I was going to use the reduce()
helper, but that was taken.
Alright, so instead I will use a different type of for
loop introduced with ES2015, called the for...of
syntax.
- Create an empty string called
reversed
.
for
each character
in the provided string
- Take the
character
and add it to the start of reversed
return
the variable of reversed
You are dying to see the code aren't you.
function reverse(str) {
let reversed = '';
for (let character of str) {
reversed = character + reversed;
}
return reversed;
}
reverse('abc');
So what's going on here? We say for
a variable declaration, I am creating a temporary variable that is redeclared every single time through this loop of character
:
for (let character of str) {
reversed = character + reversed;
}
Then we say of
and then the iterable object we want to iterate through, in this case its all the character
s of str
variable.
So we iterate through each character
of str
, one by one, and set each character
equal to the temporary variable of character
.
We then take that character
, add it to the start of the string reversed
and after the entire for
loop, we return
the string reversed
.
function reverse(str) {
let reversed = '';
for (let character of str) {
reversed = character + reversed;
}
return reversed;
}
reverse('abc');