Skip to content

Instantly share code, notes, and snippets.

@fernandocamargo
Created July 12, 2022 13:56
Show Gist options
  • Save fernandocamargo/03a2bd841bd3f0f6a0e6f0c64f5db3f2 to your computer and use it in GitHub Desktop.
Save fernandocamargo/03a2bd841bd3f0f6a0e6f0c64f5db3f2 to your computer and use it in GitHub Desktop.

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"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment