run-length encoding algorithm js code example

Example: run length encoding javascript

function encode(code) {
    if (!code) return '';
    let encode = '';

    for (let i = 0; i < code.length; i++) {
      let count = 1;
      for (let j = i; j < code.length; j++) {
        if (code[i] !== code[j+1]) break;
        count++;
        i++;
      }
      encode += count === 1 ? code[i] : count + code[i];
    }

    return encode
  }
  
 encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB"); // "12WB12W3B24WB"
 encode("AABBBCCCC"); // "2A3B4C"
 encode(""); // ""