Skip to content

Commit 8a8f653

Browse files
committed
Run-length added
1 parent 4ae7e52 commit 8a8f653

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
var str = 'Sample';
2+
3+
/**
4+
* Run-length encoding.
5+
* The idea of this algorithm is to remove the usless zeros and
6+
* give us representation of string in binary which in which the
7+
* zeros will be stripped and replaced with their count.
8+
*/
9+
var runLengthEncoding = (function () {
10+
11+
'use strict';
12+
13+
function convertToAscii(str) {
14+
var result = '',
15+
currentChar = '',
16+
i = 0;
17+
for (; i < str.length; i += 1) {
18+
currentChar = str[i].charCodeAt(0).toString(2);
19+
if (currentChar.length < 8) {
20+
while (8 - currentChar.length) {
21+
currentChar = '0' + currentChar;
22+
}
23+
}
24+
result += currentChar;
25+
}
26+
return result;
27+
}
28+
29+
function runLength(vector) {
30+
var result = '',
31+
zeros = 0,
32+
zerosTemp = '',
33+
wordLength = 0,
34+
i = 0;
35+
for (; i < vector.length; i += 1) {
36+
if (vector[i] === '0') {
37+
zeros += 1;
38+
} else {
39+
zerosTemp = zeros.toString(2);
40+
wordLength = zerosTemp.length - 1;
41+
while (wordLength) {
42+
result = result + '1';
43+
wordLength -= 1;
44+
}
45+
result += '0' + zerosTemp;
46+
zeros = 0;
47+
}
48+
}
49+
return result;
50+
}
51+
52+
return function (str) {
53+
var asciiString = convertToAscii(str);
54+
return runLength(asciiString);
55+
}
56+
57+
}());
58+
59+
console.log(runLengthEncoding(str));

0 commit comments

Comments
 (0)