UNPKG

@thi.ng/rle-pack

Version:

Binary run-length encoding packer w/ flexible repeat bit widths and a naive RLE encoder/decoder for arrays of arbitrary typed values

33 lines (32 loc) 768 B
import { illegalArgs } from "@thi.ng/errors/illegal-arguments"; const encodeSimple = (src, equiv = (a, b) => a === b) => { const result = []; const n = src.length; if (!n) return result; let val = src[0]; let start = 0; for (let i = 1; i < n; i++) { if (!equiv(src[i], val)) { result.push(val, i - start); val = src[i]; start = i; } } result.push(val, n - start); return result; }; const decodeSimple = (src) => { const n = src.length; if (n & 1) illegalArgs(`input length must be even`); const result = []; for (let i = 0; i < n; i += 2) { const val = src[i]; const count = src[i + 1]; for (let j = 0; j < count; j++) result.push(val); } return result; }; export { decodeSimple, encodeSimple };