-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunlength.js
More file actions
93 lines (71 loc) · 2.55 KB
/
Copy pathrunlength.js
File metadata and controls
93 lines (71 loc) · 2.55 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
const performance = require('./performance');
(
() => {
const inputs = process.argv.slice(2);
const command = inputs[0];
const withP = inputs[2];
if( !(command === 'c' || command === 'uc') ) throw Error("Expteced either 'c' or 'uc' as command");
const input = inputs[1];
compress = ( array ) => {
const _length = array.length;
let compressed = '';
let current = array[0];
let previousIndex = 0;
array.forEach( (element, index ) => {
if( current !== element ){
compressed += `${index - previousIndex}${current}`;
current = element;
previousIndex = index;
}
else if( _length - 1 === index ){
compressed += `${_length - previousIndex}${current}`
}
});
console.log(`Input: ${input}.`)
console.log(`Output: compressed: ${compressed}`);
}
uncompress = ( string_ ) => {
let uncompressed = [];
let stringWithSplit = string_.split(/([A-Za-z])/);
for( let i = 0; i < stringWithSplit.length; i += 2 ){
const times = stringWithSplit[i];
const letter = stringWithSplit[i + 1];
if( times ){
uncompressed = uncompressed.concat( buildChunk( letter, times ) );
}
}
console.log(`Input: ${stringWithSplit.join('')}.`)
console.log(`Output: uncompressed: ${uncompressed.join('')}.`);
}
buildChunk = ( letter, times ) => {
let result = [];
let count = 0
while( count < times ){
result.push( letter );
count++;
}
return result;
}
let run = null;
//main
switch( command ){
case 'c':
run = () => {
const asArray = input.split('');
compress( asArray );
}
if( withP === '-p' ) performance( run );
else run();
break;
case 'uc':
run = () => {
uncompress( input );
}
if( withP === '-p' ) performance( run );
else run();
break;
default:
return 'should never come here but if it does.... oh well';
}
}
)()