Here is an alternative method using destructuring
const reversedString = ([firstChar,...remainingChars]) =>
firstChar === undefined
? ''
: reversedString(remainingChars) + firstChar
console.log (reversedString('hello world'))
// 'dlrow olleh'
console.log (reversedString(''))
// ''
Now let's optimize it with a tail call
const reversedString = ([firstChar,...remainingChars], callback = char => char) =>
firstChar === undefined
? callback('')
: reversedString(remainingChars, nextChar =>
callback(nextChar + firstChar))
console.log(reversedString('hello world'))
// 'dlrow olleh'
console.log(reversedString(''))
// ''
Next, we'll attempt the same without using destructuring
const reversedString = characters =>
characters.length === 0
? ''
: reversedString(characters.slice(1)) + characters.slice(0, 1)
console.log(reversedString('hello world'))
// 'dlrow olleh'
console.log(reversedString(''))
// ''
Let's try implementing it with a tail call as well
const reversedString = (characters, callback = char => char) =>
characters.length === 0
? callback('')
: reversedString(characters.slice(1), nextChar =>
callback(nextChar + characters.slice(0,1)))
console.log(reversedString('hello world'))
// 'dlrow olleh'
console.log(reversedString(''))
// ''
Some may prefer to use .substr
instead of .slice
and .concat
instead of +
– the choice is yours
const reversedString = (characters, callback = char => char) =>
characters.length === 0
? callback('')
: reversedString(characters.substr(1), nextChar =>
callback(nextChar.concat(characters.substr(0,1))))
console.log(reversedString('hello world'))
// 'dlrow olleh'
console.log(reversedString(''))
// ''