forked from TheAlgorithms/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseString.js
39 lines (32 loc) · 929 Bytes
/
ReverseString.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
29
30
31
32
33
34
35
36
37
38
39
/**
* A short example showing how to reverse a string.
*/
function ReverseStringIterative (string) {
if (typeof string !== 'string') {
throw new TypeError('The given value is not a string')
}
let reversedString = ''
let index
for (index = string.length - 1; index >= 0; index--) {
reversedString += string[index]
}
return reversedString
}
/**
* JS disallows string mutation so we're actually a bit slower.
*
* @complexity O(n)
*/
function ReverseStringIterativeInplace (string) {
if (typeof string !== 'string') {
throw new TypeError('The given value is not a string')
}
const _string = string.split('')
for (let i = 0; i < Math.floor(_string.length / 2); i++) {
const first = _string[i]
_string[i] = _string[_string.length - 1 - i]
_string[_string.length - 1 - i] = first
}
return _string.join('')
}
export { ReverseStringIterative, ReverseStringIterativeInplace }