-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.reverse.js
More file actions
70 lines (59 loc) · 1.64 KB
/
string.reverse.js
File metadata and controls
70 lines (59 loc) · 1.64 KB
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
/*
* @title: Reverse String
* @description: Simple function to reverse string
* @author: Thorsten Kober
* @email: [email protected]
*/
function reverseStringOne(str) {
let result = '';
for (let i = str.length - 1; i >= 0; i--) {
result += str[i];
}
return result;
}
function reverseStringTwo(str) {
const middle = Math.floor(str.length / 2);
const chars = str.split('');
for (let i = 0; i < middle; i++) {
const temp = chars[i];
chars[i] = chars[chars.length - 1 - i];
chars[chars.length - 1 - i] = temp;
}
return chars.join('');
}
function reverseStringThree(str) {
const chars = str.split('');
let left = 0;
let right = chars.length - 1;
while (left < right) {
const temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
return chars.join('');
}
function reverseStringFour(str) {
if (str === '') {
return '';
}
return reverseStringFour(str.substr(1)) + str.charAt(0);
// return str.charAt(str.length - 1) + reverseStringFour(str.substr(0, str.length - 1));
}
function reverseStringFive(str) {
if (str.length <= 1) {
return str;
}
const left = str[0];
const right = str[str.length - 1];
return right + reverseStringFive(str.substring(1, str.length - 1)) + left;
}
// npx jest algorithms/string/string.reverse.js
test('test reverse string', () => {
expect(reverseStringOne('hello')).toEqual('olleh');
expect(reverseStringTwo('hello')).toEqual('olleh');
expect(reverseStringThree('hello')).toEqual('olleh');
expect(reverseStringFour('hello')).toEqual('olleh');
expect(reverseStringFive('hello')).toEqual('olleh');
});