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.

Revisions

  1. fernandocamargo created this gist Jul 12, 2022.
    5 changes: 5 additions & 0 deletions README.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    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.
    23 changes: 23 additions & 0 deletions solution.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    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"))