Convert number to string (comes with encoding) JavaScript

Update:

The following code works fine 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 snapshot:

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

In manually repeating the above code, it should generate a normal answer, why does it return this string "undefined ...", simply because it is a large number operation for JS?

+5
source share
2 answers

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

The required ihash function uses a single do ... until . It uses the remainder of the value and length as the index of the given charcter set. Then the value is divided by the length of the character set, and the integer part is taken for the next iteration, if not equal to 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' 
+2
source

Here is the pseudo code to return the string. This is similar to converting numbers from a 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; } 
0
source

Source: https://habr.com/ru/post/1246116/


All Articles