0

I have the following string:

SigV1i8njyrAGrbAfHRNdM3fmEu3kd7keGsqTTDG3Wt3tXqT153eFya2JsEigrK7Pjmh6HhEQLp5bmNXyeHsKNELW7cD3

Is there a javascript string compression function that can shorten this somehow?

I also need a way to extract it back to its original string state.

lepe
  • 24,677
  • 9
  • 99
  • 108
Patoshi パトシ
  • 21,707
  • 5
  • 29
  • 47

1 Answers1

1

The idea is to convert the available base62 string into a higher base string. This way you save space. But doing this in vanilla JS (or using Jquery) is difficult because JS doesn't handle big numbers very well. With the help of an external library bigint.js, it is possible. You can test it here. This code was not written by me, but its quite useful:

var base_symbols = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~`!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?¿¡";

function baseConvert(src, from_base, to_base, src_symbol_table, dest_symbol_table) {
    // From: convert.js: http://rot47.net/_js/convert.js
    // Modified by MLM to work with BigInteger: https://github.com/peterolson/BigInteger.js

    src_symbol_table = src_symbol_table ? src_symbol_table : base_symbols;
    dest_symbol_table = dest_symbol_table ? dest_symbol_table : src_symbol_table;

    if(from_base > src_symbol_table.length || to_base > dest_symbol_table.length) {
        console.warn("Can't convert", src, "to base", to_base, "greater than symbol table length. src-table:", src_symbol_table.length, "dest-table:", dest_symbol_table.length);
        return false;
    }

    var val = bigInt(0);
    for(var i = 0; i < src.length; i ++) {
        val = val.multiply(from_base).add(src_symbol_table.indexOf(src.charAt(i)));
    }
    if(val.lesser(0)) {
        return 0;
    }

    var r = val.mod(to_base);
    var res = dest_symbol_table.charAt(r);
    var q = val.divide(to_base);
    while(!q.equals(0)) {
        r = q.mod(to_base);
        q = q.divide(to_base);
        res = dest_symbol_table.charAt(r) + res;
    }

    return res;
}

var input = 'SigV1i8njyrAGrbAfHRNdM3fmEu3kd7keGsqTTDG3Wt3tXqT153eFya2JsEigrK7Pjmh6HhEQLp5bmNXyeHsKNELW7cD3';
var a = baseConvert(input, 62, 80);
baseConvert(a, 80, 62);

The resultant output converts 94 characters into 82 characters:

SigV1i8njyrAGrbAfHRNdM3fmEu3kd7keGsqTTDG3Wt3tXqT153eFya2JsEigrK7Pjmh6HhEQLp5bmNXyeHsKNELW7cD3 
$sIn3@WAto¿rf<zVn"+:Pkgq;&x.fciVZC7O)`0ii+sf/\X¿CM9Ad!0Z^q?t6uK=w}S8=JZhboIHd'fY\]Qf
SigV1i8njyrAGrbAfHRNdM3fmEu3kd7keGsqTTDG3Wt3tXqT153eFya2JsEigrK7Pjmh6HhEQLp5bmNXyeHsKNELW7cD3

To get better compression, just chanage the base_symbols to include a lot more characters and then convert the input into an even higher base.

TheChetan
  • 4,440
  • 3
  • 32
  • 41