Skip to content
  • Sponsor TheAlgorithms/JavaScript

  • Notifications You must be signed in to change notification settings
  • Fork 5.7k

Commit 5f8d4d4

Browse files
ddaniel27appgurueu
andauthoredJun 23, 2024··
[Compressor] RLE Compressor implementation (#1671)
* [Solution] Project euler challenge 19 with tests * update leap year function * Remove unnecessary, confusingly placed comments * [COMPRESSOR] RLE * [COMPRESSOR] RLE style fixed --------- Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
1 parent 5844242 commit 5f8d4d4

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
 

‎Compression/RLE.js

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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 { Compress, Decompress }

‎Compression/test/RLE.test.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
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+
})

0 commit comments

Comments
 (0)
Please sign in to comment.