Skip to content

Instantly share code, notes, and snippets.

@al-ivanov
Created February 11, 2019 13:11
Show Gist options
  • Select an option

  • Save al-ivanov/4f9c55619bed28f8945503cfd3a1ad10 to your computer and use it in GitHub Desktop.

Select an option

Save al-ivanov/4f9c55619bed28f8945503cfd3a1ad10 to your computer and use it in GitHub Desktop.
Алгоритм сжатия RLE
function getRLEStringLength(str) {
if(!str)
return 0;
let length = 0,
tempCount = 0,
symbol = str[0];
for(let i = 0; i < str.length; i++) {
if(symbol == str[i]) {
tempCount++;
}
if(symbol != str[i] || i === str.length - 1) {
length += tempCount.toString().length + 1;
symbol = str[i];
tempCount = 0
}
}
return length;
}
function getRLEString(str) {
length = str != null ? str.length : 0;
compressStrLength = getRLEStringLength(str);
if (length == 1 || compressStrLength >= str.length) {
return str;
}
let tempCount = 0,
symbol = str[0],
compressStr = "";
for(let i = 0; i < str.length; i++) {
if(symbol == str[i]) {
tempCount++;
}
if(symbol != str[i] || i === str.length - 1) {
compressStr += symbol.toString() + tempCount;
symbol = str[i];
tempCount = 1
}
}
return compressStr.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment