@maxinimize/

reverseString-exercise

JavaScript

No description

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//Implement a function that reverses a string using iteration...and then recursion!
// function reverseString(str) {
//   let arr = str.split('')
//   let res = [];
//   for (let i = arr.length - 1; i >= 0; i-- ) {
//     res.push(arr[i])
//   }
//   return res.join('')
// }

// function reverseString(str) {
//   let arr = [...str]
//   for (let i = 0; i < Math.floor(arr.length / 2); i++ ) {
//     [arr[i], arr[arr.length - 1 - i]] = [arr[arr.length - 1 - i], arr[i]]
//   }
//   return arr.join('')
// }

function reverseString(str) {
  let arr = [...str]
  for (let i = 0; i < Math.floor(arr.length / 2); i++ ) {
    [arr[i], arr[arr.length - 1 - i]] = [arr[arr.length - 1 - i], arr[i]]
  }
  return arr.join('')
}

reverseString('-yoyo mastery')
//should return: 'yretsam oyoy'
Native Browser JavaScript