String Compression

String Compression

Write a method that takes a string as input and returns a compressed version of it, as shown in the example below:
Input: aaabbddd
Output: a3b2d3


Program: 

/*
String can also contain single characters 
For example : ab
then the output would be : ab and not a1b1
*/

process.stdin.setEncoding('utf-8');

console.log('Enter a series of characters to compress. 1 to quit');

process.stdin.on('data', (data) => {
    if (data == '1\n') {
        process.exit();
    }
    if (!isNaN(data)) {
        console.log('Please enter characters only');
        process.exit();
    }
    let str = data;
    let count = 1; // to check the number of repeated characters
    let strCopy = '' // to store output

    for (let index = 0; index < str.length; index++) {
        // if characters are uppercase then we have to compare then using toLowercase function
        if (str[index].toLowerCase() == str[index + 1] && str[index + 1].toLowerCase()) {
            count++;
        } else {
            strCopy += count > 1 ? str[index] + count : str[index];
            count = 1; // reset the count
        }
    }

    // Print the result string
    console.log(strCopy);
})

Comments

Popular Posts