peterolson / BigInteger.js

An arbitrary length integer library for Javascript
The Unlicense
1.12k stars 187 forks source link

Need for higher digits alphabet #160

Closed ppKrauss closed 5 years ago

ppKrauss commented 5 years ago

Hi, it is possible a better representation for "higher digits", a standard (e.g. RFC 3548) or custom alphabet... It is very very better tham angle brackets. Why not implemented custom alphabet?


See also #109

peterolson commented 5 years ago

I'm open to this now, since it isn't the first time it's been requested.

It might take me a while to get around to doing this, but definitely feel free to open a pull request if you want to give it a shot yourself.

ppKrauss commented 5 years ago

Thanks @peterolson !

Well, we need some code polishing, the algorithims are only drafts, but good clues for methods to be implemented. There are also some "need for other alphabet", illustrated below by base32.

function tr( text, search, replace ) {
    // copy from https://stackoverflow.com/a/10727555/287948
    var regex = RegExp( '[' + search + ']', 'g' );
    var t = text.replace( regex, 
            function( chr ) {
                var ind = search.indexOf( chr );
                var r = replace.charAt( ind );
                return r;
            } );
    return t;
}

// adapted from https://gist.github.com/sclark39/9daf13eea9c0b381667b61e3d2e7bc11

var lower = 'abcdefghijklmnopqrstuvwxyz';
var upper = lower.toUpperCase();
var numbers = '0123456789'
var ig_alphabet =  upper + lower + numbers + '-_'
var b32_alphabet = upper+'2345679';
var bigint_alphabet = numbers + lower

function toBase64_rfc3548( o ) {
        //if type(o)!=string them o = bigint( longid ).toString( 64 )
        return o.replace( /<(\d+)>|(\w)/g, (m,m1,m2) => {
                return ig_alphabet.charAt( ( m1 )
                  ? parseInt( m1 )
                  : bigint_alphabet.indexOf( m2 ) )
        });
}

function toBase32_rfc3548( o ) {
  return tr(
   o,
   '0123456789abcdefghijklmnopqrstuv',
   'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
  );
}

function show_DigitsAlphabet( list) {
  list.forEach(function(b) {
    var s='';
    for(var i=0;i<b;i++)
         s=s+bigInt(i).toString(b);
    if (b==32) { s = toBase32_rfc3548(s); } else
    if (b>36) { s = toBase64_rfc3548(s); }
    console.log('Base '+b+' alphabet: '+s);
  });
}
// example show_DigitsAlphabet( [4,16,32,64] );
peterolson commented 5 years ago

Fixed in version 1.6.38.