JSFiddle - React, Tailwind, and code Playground
by kkdaily
HTML
<h3>
(CTCI 1.6) implement a method to perform basic string compression using the counts of repeated characters. for example, the string aabcccccaaa would become a2b1c5a3. if the "compressed" string would not become smaller than the original string, your method should return the original string. you can assume the string has only uppercase and lowercase letters
</h3>
<div id="message"></div>
CSS
#message {
padding: 10px;
}
.success {
background-color: lightgreen;
}
.failure {
background-color: pink;
}
JavaScript
// 1. if str.length < 3, then return the str
// 2. split str into array of chars (str.split(''))
// 3. let counter = 1
// 3. let compressedString = ''
// 3. let currentChar be the current char and nextChar be set to the first char in the string initially
// 4. compare currentChar and nextChar ( if (currentChar === nextChar))
// 5. if they match, then increment counter by 1.
// 6. if they don't match, then do compressedStr += currentChar + counter
// 7. if the compressedStr.length >= str.length, return str. Else return compressedStr
compressStr = (str) => {
if (str.length < 3) {
return str
}
const chars = str.split('')
let counter = 1
let compressedStr = ''
let nextChar = chars[0]
for (let i = 0; i < chars.length; i++) {
nextChar = chars[i + 1]
if (chars[i] === nextChar) {
counter++
} else {
compressedStr += chars[i] + counter
counter = 1
}
}
return compressedStr.length >= str.length ? str : compressedStr
}
// TESTS
test = (method, inputs, expected) => {
const messageEl = document.getElementById('message')
let status = 'success'
let actual
if (inputs.length > 1) {
actual = method(...inputs)
} else {
actual = method(inputs[0])
}
if (actual !== expected) {
messageEl.innerText = `Test failed for input ${inputs}. Expected: ${expected}. Actual: ${actual}`
messageEl.classList.add('failure')
status = 'fail'
}
if (status === 'success') {
messageEl.innerText = 'All tests passed!'
messageEl.classList.add('success')
}
}
test(compressStr, ['a'], 'a')
test(compressStr, ['ab'], 'ab')
test(compressStr, ['aaa'], 'a3')
test(compressStr, ['aaabbaccc'], 'a3b2a1c3')
test(compressStr, ['abc'], 'abc')