Ask coding questions

← Back to all posts
Encoding and Decoding JS
h
Coder2195Text (35)

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?

Answered by 19wintersp (1120) [earned 5 cycles]
View Answer
Comments
hotnewtop
19wintersp (1120)
function encode(data) {
  let last = "";
  let count = 0;
  let out = [];
  for (char of data) {
    if (last == char) count += 1;
    else {
      if (last) out.push(last + count);
      last = char;
      count = 1;
    }
  }
  if (last) out.push(last + count);
  return out.join(" ");
}

function decode(data) {
  let out = "";
  for (part of data.split(" "))
    out += part[0].repeat(parseInt(part.substring(1), 10));
  return out;
}

Edit: if you want excessive shorthand:

const encode = d => Array.from(d).reduce(((a, v) => (a[a.length - 2] == v) ? (a.substring(0, a.length - 1) + (parseInt(a.substring(a.length - 1), 10) + 1)) : `${ a } ${ v }1`), "").substring(1);
const decode = d => d.split(" ").reduce(((a, v) => a + v[0].repeat(parseInt(v.substring(1), 10))), "");
Coder2195Text (35)

@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...

19wintersp (1120)

@Coder2195Text I'm confused, what? That code works, has proper syntax, and has both functions...

Coder2195Text (35)

nice job editing it but now it works @19wintersp

Coder2195Text (35)

@19wintersp do you have codesandbox account? I need to give you credit on my game

19wintersp (1120)

@Coder2195Text You can just give credit in a code comment if you'd like.

Coder2195Text (35)

@19wintersp U are gud at coding so Im asking you to collab...

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;
}