forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseString.js
More file actions
Latest commit
39 lines (32 loc) · 929 Bytes
/
Copy pathReverseString.js
File metadata and controls
39 lines (32 loc) · 929 Bytes
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.
*/
functionReverseStringIterative(string){
if(typeofstring!=='string'){
thrownewTypeError('The given value is not a string')
}
letreversedString=''
letindex
for(index=string.length-1;index>=0;index--){
reversedString+=string[index]
}
returnreversedString
}
/**
* JS disallows string mutation so we're actually a bit slower.
*
* @complexity O(n)
*/
functionReverseStringIterativeInplace(string){
if(typeofstring!=='string'){
thrownewTypeError('The given value is not a string')
}
const_string=string.split('')
for(leti=0;i<Math.floor(_string.length/2);i++){
constfirst=_string[i]
_string[i]=_string[_string.length-1-i]
_string[_string.length-1-i]=first
}
return_string.join('')
}
export{ReverseStringIterative,ReverseStringIterativeInplace}