-1

I want to learn how to clean my code up and I feel like the reverse string function can be turned into a variable. Is this possible?

function reverseString(str) {
  return str.split('').reduce((revString, char) => char + revString, '');
}
const reverse = reverseString('Cornell');
console.log(reverse);


const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Nellz
  • 29
  • 6
  • Make it a variable `const reverseStr = 'Cornell'.split('').reduce((revString, char) => char + revString, '');` ? – Nick Parsons Sep 24 '19 at 05:41
  • I came back with an error `const reverseStr = str.split('').reduce((revString, char) => char + revString, ''); console.log(reverseStr);` the error is saying str is not defined! – Nellz Sep 24 '19 at 05:47
  • See my updated comment. But I think what you currently have is better as you can reverse any string without needing to repeat your logic – Nick Parsons Sep 24 '19 at 05:47
  • I'm assuming cause numbers is previously set it is called in the variable, unlike **reverseString** it has to be in a function with an argument maybe. just what I'm thinking – Nellz Sep 24 '19 at 05:49
  • 1
    Gotcha. Thanks @NickParsons – Nellz Sep 24 '19 at 05:51
  • If you create a variable `const str = "Cornell";` then you can reference it like you did with `numbers`: `str.split('').reduce...` – Nick Parsons Sep 24 '19 at 05:51
  • `const reverseStr = (str) => str.split('').reduce((revString, char) => char + revString, ''); console.log(reverseStr('Nick'));` – Nellz Sep 24 '19 at 06:06

2 Answers2

1

Why the reduce?

"As long as you're dealing with simple ASCII characters, and you're happy to use built-in functions, this will work:"

console.log(
  'Cornell'.split("").reverse().join("")
)


// as a const:

const rev = str => str.split("").reverse().join("")
console.log(rev('Cornell'))
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    There's a popular [comment](https://stackoverflow.com/a/16776621/989121) here about `split.reverse` being wrong, however, in my personal opinion that comment is wrong and your solution is (the only) right. – georg Sep 24 '19 at 07:11
  • For the same question: "As long as you're dealing with simple ASCII characters, and you're happy to use built-in functions, this will work" – mplungjan Sep 24 '19 at 07:21
0
const reverseStr = (str) => str.split('').reduce((revString, char) => char + 
revString, '');
console.log(reverseStr('Name'));
Nellz
  • 29
  • 6