Encoding and Decoding JS
I'm making a 2d Minecraft with JS (don't ask where it is)
I need this encoding and decoding system (I don't know how to describe it with words so I'm going to show examples).
Like this:
aaaaaaaaa --> a9
abbcccc --> a1 b2 c4 (yes there are spaces to separate different characters)
aaabba --> a3 b2 a1
AND
a4 t5 --> aaaattttt
Does anyone know how to make these functions to decode and encode?
programmeruser (571)
function encode(data) {
let count = 0;
let currChar;
let str = '';
for (const ch of data) {
if (ch === currChar) {
count += 1;
} else {
if (currChar) {
str += currChar + count.toString() + ' ';
}
currChar = ch, count = 1;
}
}
str += currChar + count.toString();
return str;
}
function decode(data) {
let str = '';
for (const ch of data.split(' ')) {
str += ch[0].repeat(Number(ch[1]));
}
return str;
}
Edit: if you want excessive shorthand:
@19wintersp doesn't work returns "" on the console and your code has python syntax
Here:
function encode(data): should be
function encode(data){
and I also need the decoding function...
@Coder2195Text I'm confused, what? That code works, has proper syntax, and has both functions...
nice job editing it but now it works @19wintersp
@19wintersp do you have codesandbox account? I need to give you credit on my game
@Coder2195Text You can just give credit in a code comment if you'd like.
@19wintersp i got a way
@Coder2195Text LOL I will never know..
@19wintersp U are gud at coding so Im asking you to collab...