import initial from "lodash/initial"; import last from "lodash/last"; export const group = (stack, value) => { const [letter, total] = last(stack) || [null, 0]; const chained = letter === value; const next = [[value, chained ? total + 1 : 1]]; return chained ? initial(stack).concat(next) : stack.concat(next); }; export const format = (stack, [letter, total]) => stack.concat(total > 1 ? `${total}x` : [], letter); export const compress = (object) => { const collection = String(object).split(""); const groups = collection.reduce(group, []); return groups.reduce(format, ""); }; console.log(compress("coooooobalt")) console.log(compress("stttartuuuup"))