User Paulius
User Paulius

Reputation: 257

Count duplicated symbols in string and group them using Javascript

I need to create a function that executes text compression. Function takes one parameter x - text and returns text composed of character and it's duplicate count consecutively.

Example

x = "aaavvvfdff"

Output

a3v3f1d1f2

I tried this code:

const randomText = 'aaavvvfdff'

function getTextCompression(x) {
  const chars = x.split('')

  const duplicatesCount = chars.reduce((count, char) => {
    count[char] = (count[char] || 0) + 1;
    return count;
  }, {});

  console.log(duplicatesCount)
}

getTextCompression(randomText);

Getting output: { a: 3, v: 3, f: 3, d: 1 }

Don't know what to do next or is it good aproach?

So how to write a function which returns that output?

Upvotes: 2

Views: 285

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51896

You can use a simple regular expression and a String.prototype.replace() to implement this function, which is a run-length encoding:

function rle (str) {
  return str.replace(/([^])\1*/g, (match, p) => `${p}${match.length}`)
}

let x = 'aaavvvfdff'

console.log(rle(x))

Just for fun I'll throw in an inverse function using a similar approach:

function rld (str) {
  return str.replace(/([^])(\d+)/g, (_, p1, p2) => p1.repeat(p2))
}

let x = 'a3v3f1d1f2'

console.log(rld(x))

Upvotes: 4

Related Questions