forked from TheAlgorithms/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Compressor] RLE Compressor implementation (TheAlgorithms#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 <[email protected]>
- Loading branch information
Showing
2 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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) | ||
*/ | ||
|
||
function Compress(str) { | ||
let compressed = '' | ||
let count = 1 | ||
|
||
for (let i = 0; i < str.length; i++) { | ||
if (str[i] !== str[i + 1]) { | ||
compressed += count + str[i] | ||
count = 1 | ||
continue | ||
} | ||
|
||
count++ | ||
} | ||
|
||
return compressed | ||
} | ||
|
||
function Decompress(str) { | ||
let decompressed = '' | ||
let match = [...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) | ||
}) | ||
|
||
return decompressed | ||
} | ||
|
||
export { Compress, Decompress } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
import { Compress, Decompress } from '../RLE' | ||
|
||
describe('Test RLE Compressor/Decompressor', () => { | ||
it('Test - 1, Pass long repetitive strings', () => { | ||
expect(Compress('AAAAAAAAAAAAAA')).toBe('14A') | ||
expect(Compress('AAABBQQQQQFG')).toBe('3A2B5Q1F1G') | ||
}) | ||
|
||
it('Test - 2, Pass compressed strings', () => { | ||
expect(Decompress('14A')).toBe('AAAAAAAAAAAAAA') | ||
expect(Decompress('3A2B5Q1F1G')).toBe('AAABBQQQQQFG') | ||
}) | ||
}) |