File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed
src/compression/runlength Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change 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 ) ) ;
You can’t perform that action at this time.
0 commit comments