Skip to content

Instantly share code, notes, and snippets.

@Risyandi
Created June 23, 2022 15:31
Show Gist options
  • Save Risyandi/f65d27e474be8bb18dd04ab279c3dbb9 to your computer and use it in GitHub Desktop.
Save Risyandi/f65d27e474be8bb18dd04ab279c3dbb9 to your computer and use it in GitHub Desktop.
code challenge to encode a string
/**
* Risyandi - 2022
* how to create string to encode :
* first we have a data array as input
* for the example : [a, a, b, b, b, c, c]
* and for the expected result should be appear like this
* for the expected result : a2b3c2
*/
function stringEncode(input) {
let lengthInput = input.length;
let result = [];
let counter = 1;
for (let index = 0; index < lengthInput; index++) {
if (input[index] === input[index + 1]) {
counter++;
} else {
let resultString = input[index] + "" + counter
result.push(resultString);
counter = 1;
}
}
result = result.join("");
return result;
}
let input = ["a", "a", "c", "b", "b", "b", "c", "c"];
stringEncode(input);
/**
* result will appear like this : a2c1b3c2
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment