Created
May 24, 2023 02:50
-
-
Save dsetzer/d54b12dd3307cd8b6c8490b28fa494ab to your computer and use it in GitHub Desktop.
RunLength Encoding (RLE) text compression using Unicode symbols
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
/** | |
* Run-Length Encoding (RLE) text compression using Unicode symbols. | |
* | |
* This algorithm compresses text by counting the number of consecutive identical | |
* characters in the input string and representing them in a compact format within | |
* the compressed string using Unicode characters. The encoded and decoded parts | |
* are separated by a Unicode private-use character, U+FFF0. | |
* | |
* @param {string} inputText - The text to be compressed. | |
* @returns {string} - The compressed text. | |
*/ | |
function compress(inputText) { | |
let compressedText = ''; | |
let count = 1; | |
for (let i = 1; i <= inputText.length; i++) { | |
if (inputText[i] === inputText[i - 1]) { | |
count++; | |
} else { | |
compressedText += String.fromCharCode(count + 0xFFF0) + inputText[i - 1]; | |
count = 1; | |
} | |
} | |
return compressedText; | |
} | |
/** | |
* Decompresses text that has been compressed using the RLE compression function. | |
* | |
* @param {string} compressedText - The compressed text to be decompressed. | |
* @returns {string} - The decompressed, original text. | |
*/ | |
function decompress(compressedText) { | |
let decompressedText = ''; | |
for (let i = 0; i < compressedText.length; i += 2) { | |
let count = compressedText.charCodeAt(i) - 0xFFF0; | |
let character = compressedText[i + 1]; | |
decompressedText += character.repeat(count); | |
} | |
return decompressedText; | |
} | |
// Usage example: | |
const originalText = "WWLLLWLWWWWLWWWLLWLLLWWWLLWWWLWLLLLLWLLLWLWWLLLWWW"; | |
// Original Text: WWLLLWLWWWWLWWWLLWLLLWWWLLWWWLWLLLLLWLLLWLWWLLLWWW | |
const compressed = compress(originalText); | |
console.log("Compressed:", compressed); | |
// Compressed: WLWLWLWLWLWLWLWLWLWLWLW | |
const decompressed = decompress(compressed); | |
console.log("Decompressed:", decompressed); | |
// Decompressed: WWLLLWLWWWWLWWWLLWLLLWWWLLWWWLWLLLLLWLLLWLWWLLLWWW |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment