g1lib
Version:
An ubiquitous static javascript toolbox lib for Ǧ1 / Duniter ecosystem with reliability in mind.
2 lines (1 loc) • 1.72 kB
JavaScript
const d="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",E=l(d),u=l("0123456789abcdef"),h=l(s),B={encode:r=>{const t=typeof r=="string"?new TextEncoder().encode(r):new Uint8Array(r),e=Math.ceil(t.length/3)*3,o=new Uint8Array(e);o.set(t);const n=h.encode(o).split(""),c=e*4/3;for(;n.length<c;)n.unshift(s[0]);for(let A=0;A<e-t.length;A++)n[n.length-1-A]="=";return n.join("")},decode:r=>{const t=h.decode(r.replace(/=/g,"A")),e=Math.ceil(3*r.length/4),o=(r.match(/=/g)||[]).length,n=t.length-e;return t.slice(n,t.length-o)}};function l(r){const t={ALPHABET_MAP:{},BASE:r.length,LEADER:r.charAt(0),ALPHABET:r};for(let e=0;e<t.ALPHABET.length;e++){const o=t.ALPHABET.charAt(e);if(t.ALPHABET_MAP[o]!==void 0)throw new TypeError(o+" is ambiguous");t.ALPHABET_MAP[o]=e}return{encode:e=>a(e,t),decode:e=>i(e,t)}}function a(r,t){if(r.length===0)return"";const e=[0];for(let n of r){for(let c=0;c<e.length;++c)n+=e[c]<<8,e[c]=n%t.BASE,n=n/t.BASE|0;for(;n>0;)e.push(n%t.BASE),n=n/t.BASE|0}let o="";for(let n=0;r[n]===0&&n<r.length-1;++n)o+=t.LEADER;for(let n=e.length-1;n>=0;--n)o+=t.ALPHABET[e[n]];return o}function f(r,t){if(typeof r!="string")throw new TypeError("Expected String");if(r.length===0)return new Uint8Array(0);const e=[0];for(const o of r){const n=t.ALPHABET_MAP[o];if(n===void 0)return;let c=n;for(let A=0;A<e.length;++A)c+=e[A]*t.BASE,e[A]=c&255,c>>=8;for(;c>0;)e.push(c&255),c>>=8}for(let o=0;r[o]===t.LEADER&&o<r.length-1;++o)e.push(0);return new Uint8Array(e.reverse())}function i(r,t){const e=f(r,t);if(e)return e;throw new Error("Non-base"+t.BASE+" character")}export{u as b16,E as b58,B as b64,l as basex,l as default};