JoeBro
JoeBro

Reputation: 43

Convert Number To String (Charset Supplied) JavaScript

Update:

The following code works perfectly until $char.to_text encounters an integer greater than 55,834,574,847.

alpha="abcdefghijklmnopqrstuvwxyz";
$char={
    to_num:function(s,c){
        var l=c.length,o={};
        c.split('').forEach(function(a,i){
            o[a]=i
        });
        return s.split('').reduce(function(r,a){
            return r*l+o[a]
        },0)
    },
    to_text:function(i,c){
        var l=c.length,s='';
        do{
            s=c[i%l]+s; // i%l
            i/=l;
            i|=0
        }while(i!==0);
        return s
    }
};

Here is a quick snip:

$char.to_num("military",alpha) => 98987733674
$char.to_text(98987733674,alpha) => "undefinedundefinedundefinedundefinedundefinedundefinedundefinedy"

Manually iterating the above code should generate a normal response, why does it yield this "undefined..." string, is it simply because it's a large number operation for JS?

Upvotes: 4

Views: 181

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386560

This is a proposal with a rewritten hash function, which uses an object o as simplified indexOf and a simple loop for the return value.

The wanted function ihash uses a single do ... until loop. It uses the remainder of the value and the length as index of the given charcter set. The value is then divided by the lenght of the caracter set and the integer part is taken for the next iteration, if not equal zero.

function hash(s) {
    var c = '0abcdefghijklmnopqrstuvwxyz',
        l = c.length,
        o = {};

    c.split('').forEach(function (a, i) {
        o[a] = i;
    });
    return s.split('').reduce(function (r, a) {
        return r * l + o[a];
    }, 0);
}

function ihash(i) {
    var c = '0abcdefghijklmnopqrstuvwxyz',
        l = c.length,
        s = '';

    do {
        s = c[i % l] + s;
        i = Math.floor(i / l);
    } while (i !== 0);
    return s;
}

document.write(hash('0') + '<br>');          // => 0
document.write(hash('a') + '<br>');          // => 1
document.write(hash('hi') + '<br>');         // => 225
document.write(hash('world') + '<br>');      // => 12531838
document.write(hash('freecode') + '<br>');   // => 69810159857

document.write(ihash(0) + '<br>');           // => '0'
document.write(ihash(1) + '<br>');           // => 'a'
document.write(ihash(225) + '<br>');         // => 'hi'
document.write(ihash(12531838) + '<br>');    // => 'world'
document.write(ihash(69810159857) + '<br>'); // => 'freecode'

Upvotes: 2

user1177008
user1177008

Reputation: 41

Here is a pseudo code for getting the string back. It's similar to convert numbers of different base.

   var txt = function(n, charset) {
        var s =""
        while (n > 0) {
            var r = n % charset.length;
            n = n / charset.length;
            s += charset[r];
         }
         return s;
     }

Upvotes: 0

Related Questions