foxts
Version:
Opinionated collection of common TypeScript utils by @SukkaW
1 lines • 1.23 kB
JavaScript
;exports.base=function(r){if(r.length>=255)throw TypeError("Alphabet too long");const t=new Uint8Array(256);for(let r=0;r<256;r++)t[r]=255;const o=r.length;for(let e=0;e<o;e++){const o=r.charAt(e),n=o.charCodeAt(0);if(255!==t[n])throw TypeError("Alphabet contains ambiguous characters: "+o);t[n]=e}const e=r.charAt(0),n=Math.log(o)/Math.log(256),l=Math.log(256)/Math.log(o);return{encode:function(t){if(0===t.length)return"";let n=0,a=0,c=0;const h=t.length;for(;c!==h&&0===t[c];)c++,n++;const f=(h-c)*l+1>>>0,i=new Uint8Array(f);for(;c!==h;){let r=t[c],e=0;for(let t=f-1;-1!==t&&(0!==r||e<a);t--,e++)r+=256*i[t]>>>0,i[t]=r%o>>>0,r=r/o>>>0;if(0!==r)throw Error("Non-zero carry");a=e,c++}let s=f-a;for(;s!==f&&0===i[s];)s++;let g=e.repeat(n);for(;s<f;++s)g+=r.charAt(i[s]);return g},decode:function(r){if(0===r.length)return new Uint8Array(0);let l=0,a=0,c=0;for(;r[l]===e;)a++,l++;const h=(r.length-l)*n+1>>>0,f=new Uint8Array(h);for(;l<r.length;){let e=t[r.charCodeAt(l)],n=0;for(let r=h-1;-1!==r&&(0!==e||n<c);r--,n++)e+=o*f[r]>>>0,f[r]=e%256>>>0,e=e/256>>>0;if(0!==e)throw Error("Non-zero carry");c=n,l++}let i=h-c;for(;i!==h&&0===f[i];)i++;const s=new Uint8Array(a+(h-i));let g=a;for(;i!==h;)s[g++]=f[i++];return s}}};