File tree 2 files changed +54
-0
lines changed
2 files changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * RLE (Run Length Encoding) is a simple form of data compression.
3
+ * The basic idea is to represent repeated successive characters as a single count and character.
4
+ * For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".
5
+ *
6
+ * @author - [ddaniel27](https://github.com/ddaniel27)
7
+ */
8
+
9
+ function Compress ( str ) {
10
+ let compressed = ''
11
+ let count = 1
12
+
13
+ for ( let i = 0 ; i < str . length ; i ++ ) {
14
+ if ( str [ i ] !== str [ i + 1 ] ) {
15
+ compressed += count + str [ i ]
16
+ count = 1
17
+ continue
18
+ }
19
+
20
+ count ++
21
+ }
22
+
23
+ return compressed
24
+ }
25
+
26
+ function Decompress ( str ) {
27
+ let decompressed = ''
28
+ let match = [ ...str . matchAll ( / ( \d + ) ( \D ) / g) ] // match all groups of digits followed by a non-digit character
29
+
30
+ match . forEach ( item => {
31
+ let [ count , char ] = [ item [ 1 ] , item [ 2 ] ]
32
+ decompressed += char . repeat ( count )
33
+ } )
34
+
35
+ return decompressed
36
+ }
37
+
38
+ export {
39
+ Compress ,
40
+ Decompress
41
+ }
Original file line number Diff line number Diff line change
1
+ import { Compress , Decompress } from '../RLE'
2
+
3
+ describe ( 'Test RLE Compressor/Decompressor' , ( ) => {
4
+ it ( 'Test - 1, Pass long repetitive strings' , ( ) => {
5
+ expect ( Compress ( 'AAAAAAAAAAAAAA' ) ) . toBe ( '14A' )
6
+ expect ( Compress ( 'AAABBQQQQQFG' ) ) . toBe ( '3A2B5Q1F1G' )
7
+ } )
8
+
9
+ it ( 'Test - 2, Pass compressed strings' , ( ) => {
10
+ expect ( Decompress ( '14A' ) ) . toBe ( 'AAAAAAAAAAAAAA' )
11
+ expect ( Decompress ( '3A2B5Q1F1G' ) ) . toBe ( 'AAABBQQQQQFG' )
12
+ } )
13
+ } )
You can’t perform that action at this time.
0 commit comments