How to compress and decompress repeated string characters by storing the repeated length (RLE) in JavaScript

1 Answer

0 votes
// ---------------------------------------------------------
//   Compress: turn "aaabbcccc" into "a3b2c4"
//   This is run-length encoding (RLE)
// ---------------------------------------------------------
function compress(s) {
    if (!s) {
        return "";   // Edge case: empty string
    }

    let out = [];        // Result string (array for efficiency)
    let count = 1;       // Count of repeated characters

    // Start from index 1 and compare with previous character
    for (let i = 1; i <= s.length; i++) {

        // If still repeating the same character, increase count
        if (i < s.length && s[i] === s[i - 1]) {
            count++;
        } else {
            // Character changed OR reached end of string
            out.push(s[i - 1]);     // Add the character
            out.push(String(count)); // Add how many times it repeated
            count = 1;               // Reset counter
        }
    }

    return out.join("");
}


// ---------------------------------------------------------
//   Decompress: turn "a3b2c4" into "aaabbcccc"
//   Reads a letter, then reads digits, expands them.
// ---------------------------------------------------------
function decompress(s) {
    let out = [];                 // Result string
    let currentChar = null;       // The character being processed
    let number = [];              // Digits representing the count

    for (const c of s) {

        if (/[A-Za-z]/.test(c)) { // Found a letter
            // If we already have a previous letter + number, expand it
            if (currentChar !== null && number.length > 0) {
                const count = Number(number.join(""));
                out.push(currentChar.repeat(count));
            }

            currentChar = c;      // Start new character
            number = [];          // Reset number buffer

        } else if (/\d/.test(c)) { // Found a digit
            number.push(c);        // Build multi-digit number
        }
    }

    // Handle the last character + number pair
    if (currentChar !== null && number.length > 0) {
        const count = Number(number.join(""));
        out.push(currentChar.repeat(count));
    }

    return out.join("");
}


function main() {
    const s = "wwwwwwwwwwwwbwwwwwwwwwwbbbwwwwwwccccwwwwwwwwwwww";

    const c = compress(s);
    const d = decompress(c);

    console.log("Original:   ", s);
    console.log("Compressed: ", c);
    console.log("Decompressed:", d);
}

main();


/*
run:

Original:    wwwwwwwwwwwwbwwwwwwwwwwbbbwwwwwwccccwwwwwwwwwwww
Compressed:  w12b1w10b3w6c4w12
Decompressed: wwwwwwwwwwwwbwwwwwwwwwwbbbwwwwwwccccwwwwwwwwwwww

*/

 



answered 1 day ago by avibootz

Related questions

...