S
S
Sergey Alekseev2018-08-12 09:03:28
JavaScript
Sergey Alekseev, 2018-08-12 09:03:28

How to reverse a string with recursion?

How to reverse a string recursively using the length of the string and getting a substring?
I do not understand how to set a condition for recursion?

const reverse = (str) => {
  let res = '';
  const index = str.length-1;
  if (index === 0 || index === 1) return str;
  else {
    res += iter(str, index)
  }
};

const iter = (str, index) => {
  if (index !== 0) return iter(str, index-1);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-08-12
@serj2000

const reverse = str => str.length < 2 ? str : reverse(str.slice(1)) + str[0];

or
const reverse = ([ c, ...str ]) => c ? reverse(str) + c : '';

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question