-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray.compress.js
More file actions
42 lines (36 loc) · 926 Bytes
/
array.compress.js
File metadata and controls
42 lines (36 loc) · 926 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
40
41
42
/*
* @title: compress array
* @description: Simple function to compress an array
* @author: Thorsten Kober
* @email: [email protected]
*/
/*
* input: [1, 2, 3, 10, 25, 26, 30, 31, 32, 33];
* output: '1-3,10,25-26,30-33'
*/
function compressArray(arr) {
const result = [];
if (arr.length === 0) return result;
let start = 0;
let end = start;
// notice that we loop one additional time
for (let i = 1; i <= arr.length; i++) {
if (arr[i] === arr[end] + 1) {
end++;
} else {
if (start === end) {
result.push(`${arr[start]}`);
} else {
result.push(`${arr[start]}-${arr[end]}`);
}
start = i;
end = start;
}
}
return result.join(',').toString();
}
// npx jest algorithms/array/array.compress.js
test('compressArray()', () => {
expect(compressArray([1, 2, 3, 10, 25, 26, 30, 31, 32, 33]))
.toEqual('1-3,10,25-26,30-33');
});