Skip to content

Instantly share code, notes, and snippets.

@showmeyourhits
Created December 5, 2017 16:23
Show Gist options
  • Save showmeyourhits/7a7d54b1a9179a4e6875eecc122bce61 to your computer and use it in GitHub Desktop.
Save showmeyourhits/7a7d54b1a9179a4e6875eecc122bce61 to your computer and use it in GitHub Desktop.
const isNotValidRE = /[^A-Za-z]/;
const matchRLE = /([A-Za-z])\1*/g;
function RLE(str) {
if (str && isNotValidRE.test(str)){
throw new Error('Not valid string: ' + str);
}
return str.replace(
matchRLE,
match => match.length === 1 ? match : `${match[0]}${match.length}`
);
}
try {
RLE('AS-');
} catch (e) {
console.log('should throw %s', e.message);
}
console.log('empty str %s', RLE('') === '');
console.log('single char %s', RLE('A') === 'A');
console.log('couple char %s', RLE('Aa') === 'Aa');
console.log('couple of diffchar %s', RLE('AB') === 'AB');
console.log('real test %s', RLE('AAAABBQWEEEE') === 'A4B2QWE4');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment