Reverse Conversion of Levenshtein Code to JavaScript


There is such a Levenshtein Code .

Converting a number to Levenshtein code is very easy:

const encode=n=>n.toString(2).replace(1,_=>1+encode(~~Math.log2([]+n)));

    // => "1111100100010011010001111011010000000011010100011010000101011111001001000010010010001110"

There is a stream of bytes, consisting of Levinstein codes of different lengths. Something like:

let response = await fetch(fileURL);
let reader = response.body.getReader();
let {value: chunk, done: readerDone} = await;

It is necessary from this stream of bytes to decode the codes back into numbers.

It seems that the decoding function should be simple, as well as for encoding. And most likely, as I sleep, I will figure it out myself. The whole problem is that the numbers are not separated by anything and their border runs between bytes. And this ArrayBuffer my whole brain.


const encode=n=>n.toString(2).replace(1,_=>1+encode(~~Math.log2([]+n)));

const decode = function* (str) {
    let o = 0;
    while (str.substr(o,1)=='1') o++;
    let n = 1, _o = o + 1;
    if(o == 0) n=0;
    else for(let i=1;i<o;i++)[n,_o]=[parseInt('1'+str.substring(_o,_o+n),2),_o+n];
    yield n;
    str = str.substr(_o);

//  Использование
let array = [0, 1001, 0, 2002, 0];
let str =``;
for(let num of decode(str)){
Scroll to Top