Skip to content

Instantly share code, notes, and snippets.

@jcpsimmons
Created April 22, 2020 21:12
Show Gist options
  • Save jcpsimmons/6f388f0ccb54e0d1f56500145aa58f19 to your computer and use it in GitHub Desktop.
Save jcpsimmons/6f388f0ccb54e0d1f56500145aa58f19 to your computer and use it in GitHub Desktop.
Simple compression function
// Takes a sequence of letters and returns a compressed output
// input = abcaaabbb
// expected = abca3b3
const compressor = (str) => {
if (typeof str !== "string" || !/^[A-Za-z]+$/.test(str)) {
return "Input must be a string";
}
if (str.length > 5000) {
return "Input must be less than 5000 chars.";
}
const arr = str.split("");
let outputStr = "";
for (let i = 0; i < arr.length; i++) {
let sameLetter = false;
if (i > 0) {
sameLetter = arr[i] == arr[i - 1];
}
if (sameLetter) {
let sameCount = 1;
let iterCount = 1;
while (arr[i] == arr[i + iterCount]) {
sameCount++;
iterCount++;
}
outputStr += sameCount + 1;
i = i + iterCount - 1;
} else {
outputStr += arr[i];
}
}
return outputStr;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment