Skip to content

Instantly share code, notes, and snippets.

@dsetzer
Created May 24, 2023 02:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsetzer/d54b12dd3307cd8b6c8490b28fa494ab to your computer and use it in GitHub Desktop.
Save dsetzer/d54b12dd3307cd8b6c8490b28fa494ab to your computer and use it in GitHub Desktop.
RunLength Encoding (RLE) text compression using Unicode symbols
/**
* 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: ￲W￳L￱W￱L￴W￱L￳W￲L￱W￳L￳W￲L￳W￱L￱W￵L￱W￳L￱W￱L￲W￳L￳W
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