Skip to content

Instantly share code, notes, and snippets.

@vinayverghese
Forked from rvbsanjose/runLength.js
Created August 15, 2018 16:46
Show Gist options
  • Select an option

  • Save vinayverghese/033136ccd461727c2891635438b48233 to your computer and use it in GitHub Desktop.

Select an option

Save vinayverghese/033136ccd461727c2891635438b48233 to your computer and use it in GitHub Desktop.
// Using the JavaScript language, have the function RunLength(str) take the str parameter being passed and return a compressed // version of the string using the Run-length encoding algorithm. This algorithm works by taking the occurrence of each
// repeating character and outputting that number along with a single character of the repeating sequence.
// For example: "wwwggopp" would return 3w2g1o2p. The string will not contain any numbers, punctuation, or symbols.
// Input = "aabbcde" Output = "2a2b1c1d1e"
// Input = "wwwbbbw" Output = "3w3b1w"
function RunLength( str ) {
var output = '';
while ( str.length > 0 ) {
var current = new RegExp( str[0] + '+' );
var length = str.match( current ).toString().split( '' ).length;
output += length.toString() + str.match( current )[0][0];
str = str.replace( str.match( current )[0], '' );
}
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment