function compress(string) {
if (typeof string !== 'string') return null;
if (string === '') return '';
let trackingChar = string[0];
let charCount = 0;
let compressed = '';
for (let i = 0; i < string.length; i++) {
const char = string[i];
if (char === trackingChar) {
charCount++;
} else if (char !== trackingChar) {
compressed += trackingChar + (charCount === 1 ? '' : '' + charCount);
trackingChar = char;
charCount = 1;
}
}
compressed += trackingChar + (charCount === 1 ? '' : '' + charCount);
return compressed.length < string.length ? compressed : string;
}
function runTests(func) {
const inputOutput = [[null, null], ['', ''], ['AABBCC', 'AABBCC'], ['AAABCCDDDD', 'A3BC2D4'], ['BAAACCDDDD', 'BA3C2D4'], ['AAABAACCDDDD', 'A3BA2C2D4']];
for (let i = 0; i < inputOutput.length; i++) {
const input = inputOutput[i].slice(0, inputOutput[i].length-1);
const expected = inputOutput[i][inputOutput[i].length-1];
const result = func(...input);
if (result !== expected) {
return `Test failed: Expected - ${expected}. Got ${result}`;
}
}
return 'All tests passed!'
}
runTests(compress);