run length encoding javascript

Solutions on MaxInterview for run length encoding javascript by the best coders in the world

showing results for - "run length encoding javascript"
Harry
14 Sep 2019
1function encode(code) {
2    if (!code) return '';
3    let encode = '';
4
5    for (let i = 0; i < code.length; i++) {
6      let count = 1;
7      for (let j = i; j < code.length; j++) {
8        if (code[i] !== code[j+1]) break;
9        count++;
10        i++;
11      }
12      encode += count === 1 ? code[i] : count + code[i];
13    }
14
15    return encode
16  }
17  
18 encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB"); // "12WB12W3B24WB"
19 encode("AABBBCCCC"); // "2A3B4C"
20 encode(""); // ""