Created
April 22, 2020 21:12
-
-
Save jcpsimmons/6f388f0ccb54e0d1f56500145aa58f19 to your computer and use it in GitHub Desktop.
Simple compression function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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