Skip to content

Instantly share code, notes, and snippets.

@unilecs
Created October 8, 2017 17:53
Show Gist options
  • Save unilecs/6d8ba5998b7d05f08606aa55ba9f86ef to your computer and use it in GitHub Desktop.
Save unilecs/6d8ba5998b7d05f08606aa55ba9f86ef to your computer and use it in GitHub Desktop.
Compression of string
function compressString(inputStr) {
if (inputStr) {
// частный случай: если строка состоит из 1го символа
// или сжатие приведет к увеличению строки
let length = inputStr.length, inputStrArr = [...inputStr];
let compressStrLength = getCompressionStringLength(inputStrArr);
if (length === 1 || compressStrLength >= length) {
return inputStr;
}
let currentSymbol = inputStr[0], count = 0, result = "";
inputStrArr.forEach((symbol, index) => {
if (symbol === currentSymbol) {
count++;
}
// если предыдущий символ не равен текущему ИЛИ итерация является последней
// то обнуляем счетчик
if (symbol !== currentSymbol || index === length - 1) {
result += currentSymbol + count;
count = 1;
currentSymbol = symbol;
}
});
return result;
}
return "";
}
// функция возвращает размер "сжатой" строки
function getCompressionStringLength(inputStrArr) {
let resultLength = 0, curSymbol = inputStrArr[0], count = 0;
inputStrArr.forEach((symbol, index) => {
if (curSymbol === symbol) {
count++;
}
// если предыдущий символ не равен текущему ИЛИ итерация является последней
// то обнуляем счетчик
if (curSymbol !== symbol || index === inputStrArr.length - 1) {
resultLength += 1 + count.toString().length;
curSymbol = symbol;
count = 1;
}
});
return resultLength;
}
console.info("Compression of string: ", compressString("ZZZABBEEE")); // Z3A1B2E3
console.info("Compression of string: ", compressString("abcca")); // abcca, т.к. после сжатия (a1b1c2a1) строка будет большего размера
@artrainbow
Copy link

const compressString = (string) => {

let result = [];
let counter = 0;
let tmp;

[...string].map((item, index, arr) => {
    if (item === arr[index + 1]) {
        tmp = counter++;
    } else if (item === arr[index - 1]) {
        counter = 0;
        result.push(item + Number.parseInt(tmp + 2));
    } else {
        result.push(item + 1);
    }
});

return (result.join('').length < string.length) ? result.join('') : string;

};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment