Implement a compression algorithm that will count letters, e.g. coooooobalt => c6xobalt (or: 1xc6xo1xb1xa1xl1xt) stttartuuuup => s3xtart4xup (or: 1xs3xt1xa1xr1xt4xu1xp)
Use the language/technology you feel strong in.
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")) |