Reputation: 19
My code
When i use word cat the function doesn't return anything.
function reverse(str) {
let result = '';
let i = str.length-1;
while ( i < 0) {
result = result + str[i];
i--;
}
return result;
}// END```
Upvotes: 0
Views: 42
Reputation: 21638
You could use reduce
const reverse = str => str.split('').reduce((result, char) => char + result);
console.log(reverse('cat'));
Upvotes: 0
Reputation: 1195
You had a typo and a logic error:
function reverse(str) {
let result = '';
let i = str.length - 1; // str.length
while (i >= 0) { // greater than equal to :)
result = result + str[i];
i--;
}
return result;
}
Upvotes: 0
Reputation: 12152
Use str.length;
instead of str.legth-1;
legth
is not a function. The function in length
function reverse(str) {
let result = '';
let i = str.length;
while (i--) {
result = result + str[i];
}
return result;
}
console.log(reverse('ellipsis'))
Upvotes: 0
Reputation: 386570
You need to take length
and the check for greater or equal than zero for the loop.
function reverse(str) {
let result = '';
let i = str.length - 1;
while (i >= 0) {
result = result + str[i];
i--;
}
return result;
}
console.log(reverse('cat'));
A slightly shorter approach with decrementing and check in one.
function reverse(str) {
let result = '',
i = str.length;
while (i--) result = result + str[i];
return result;
}
console.log(reverse('cat'));
Upvotes: 1