forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRLE.js
More file actions
Latest commit
38 lines (30 loc) · 893 Bytes
/
Copy pathRLE.js
File metadata and controls
38 lines (30 loc) · 893 Bytes
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
/*
* RLE (Run Length Encoding) is a simple form of data compression.
* The basic idea is to represent repeated successive characters as a single count and character.
* For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".
*
* @author - [ddaniel27](https://github.com/ddaniel27)
*/
functionCompress(str){
letcompressed=''
letcount=1
for(leti=0;i<str.length;i++){
if(str[i]!==str[i+1]){
compressed+=count+str[i]
count=1
continue
}
count++
}
returncompressed
}
functionDecompress(str){
letdecompressed=''
letmatch=[...str.matchAll(/(\d+)(\D)/g)]// match all groups of digits followed by a non-digit character
match.forEach((item)=>{
let[count,char]=[item[1],item[2]]
decompressed+=char.repeat(count)
})
returndecompressed
}
export{Compress,Decompress}