forked from TheAlgorithms/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathReverseString.js
77 lines (70 loc) · 1.76 KB
/
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* A short example showing how to reverse a string
* @flow
*/
/**
* Create a new string and append
* @complexity O(n)
*
* Doctests
*
* > ReverseStringIterative('some')
* 'emos'
* > ReverseStringIterative('string')
* 'gnirts'
* > ReverseStringIterative('The Algorithms Javascript')
* 'tpircsavaJ smhtiroglA ehT'
* > ReverseStringIterative([])
* ! TypeError
* > ReverseStringIterative({})
* ! TypeError
* > ReverseStringIterative(null)
* ! TypeError
*/
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)
*
* 'some' -> 'eoms' -> 'emos'
*
* Doctests
*
* > ReverseStringIterativeInplace('some')
* 'emos'
* > ReverseStringIterativeInplace('string')
* 'gnirts'
* > ReverseStringIterativeInplace('The Algorithms Javascript')
* 'tpircsavaJ smhtiroglA ehT'
* > ReverseStringIterativeInplace([])
* ! TypeError
* > ReverseStringIterativeInplace({})
* ! TypeError
* > ReverseStringIterativeInplace(null)
* ! TypeError
*/
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]
const second = _string[_string.length - 1 - i]
_string[i] = second
_string[_string.length - 1 - i] = first
}
return _string.join('')
}
export { ReverseStringIterative, ReverseStringIterativeInplace }