I've written an algo to compress a string
eg. aabcbbba to a2bcb3a
I'm pretty new to functional programming, I feel it's easier to debug and learn from functional code if you're good at it already, but total opposite if you're not.
I'm wondering how I can make this code cleaner and more functional.
I feel like there's gotta be a better way to do compressCharacters without the need of an array or a result variable (perhaps substituting forEach with something else) as well as reducing the lines of code in groupCharacters
const signature = `aabcbbba`;
const compressString = signature => {
return compressCharacters(groupCharacters(signature));
}
const groupCharacters = signature => {
let newSignature = "", arr = [];
// convert signature to an array
let result = [...signature].reduce((accumulator, element, index) => {
// check if last letter in accumulator matches the current element
if (accumulator[accumulator.length -1] !== element) {
// add the accumulator string into an array
arr.push(accumulator);
// clear the newSignature string and set it to current element
newSignature = element;
} else {
// if it doesn't match, add it to the accumulator
newSignature = accumulator += element;
}
// check if it's the last item - add to array
if (index === signature.length - 1) arr.push(element);
// return newSignature to accumulator
return newSignature;
})
return arr;
}
const compressCharacters = arr => {
let newArray = [];
let result = arr.forEach(e => e.length > 1 ? newArray.push(`${e[0]}${e.length}`) : newArray.push(e))
return newArray.join("");
}
compressString(signature);