-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrle-encode.js
40 lines (34 loc) · 868 Bytes
/
rle-encode.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
"use strict";
var fs = require("fs");
var transformStream = require("./transform-stream.js");
var MAX = 9;
/* run length encoding JS
*
* encoded data stored in an array with [number, string] pairs
* where the length of string is always 1 digit
*
*/
module.exports = encode;
function encode(val) {
var result = [];
var arr = [...val];
var counter = 1;
var prev = arr[0];
for (var i = 1; i <= arr.length; i++) {
if (arr[i] == prev && counter < MAX) {
counter++;
}
else {
result.push(counter);
result.push(prev);
prev = arr[i];
counter = 1;
}
}
return prettyPrint(result);
}
function prettyPrint(rleData) {
return [...rleData].join("");
}
var transform = transformStream.create( encode );
process.stdin.pipe(transform).pipe(process.stdout);