Skip to content

Instantly share code, notes, and snippets.

@lisovskyvlad
Created August 26, 2019 18:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lisovskyvlad/ff2d894e556827a107485dca9b4a1eff to your computer and use it in GitHub Desktop.
Save lisovskyvlad/ff2d894e556827a107485dca9b4a1eff to your computer and use it in GitHub Desktop.
const counterIncrement = (collector, char) => {
const lastItemIndex = collector.length - 1;
if(lastItemIndex === -1) {
return [[char, 1]];
}
if(collector[lastItemIndex][0] == char) {
collector[lastItemIndex][1] += 1
} else {
collector.push([char, 1]);
}
return collector;
}
const charCounters = (input) => input.split('').reduce(counterIncrement, []);
const output = (charCounters) => (
charCounters.map(([char, counter]) => `${char}${counter}`).join(' ')
);
const assert = require('assert');
assert(output(charCounters('aaaaabbvva')) == "a5 b2 v2 a1");
assert(
output(charCounters('aaaaaaaaaqqqqqqqfewfv')) == "a9 q7 f1 e1 w1 f1 v1"
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment