-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.compress.js
More file actions
67 lines (58 loc) · 1.35 KB
/
string.compress.js
File metadata and controls
67 lines (58 loc) · 1.35 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
/*
* @title: compress string
* @description: Simple function to compress string
* @author: Thorsten Kober
* @email: [email protected]
*/
// one extra iteration in loop - str[i] will be undefined
// therefore won't equal str[start] and will trigger else statement
function stringCompression(str) {
let result = '';
let start = 0;
let end = 0;
for (let i = 1; i <= str.length; i++) {
if (str[i] === str[start]) {
end++;
} else {
if (start === end) {
result += str[start] + 1;
} else {
result += str[start] + (end - start + 1);
}
start = i;
end = i;
}
}
return result;
}
/* function stringCompression(str) {
let start = 0;
let end = 0;
let count = 1;
let result = '';
for (let i = 1; i < str.length; i++) {
if (str[i] === str[i - 1]) {
end++;
} else {
count = (end - start + 1);
if (start === end) {
result += str[start] + count;
} else {
result += str[start] + count;
}
start = i;
end = i;
}
}
count = (end - start + 1);
if (start === end) {
result += str[start] + count;
} else {
result += str[start] + count;
}
return result;
} */
// npx jest algorithms/string/string.compress.js
test('stringCompression()', () => {
expect(stringCompression('aabcccccaaa')).toEqual('a2b1c5a3');
});