My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Tuesday, October 02, 2007

Extended parseInt and toString with radix

With JavaScript You can parse a Number using its toString native function.
This one supports a radix argument, an integer between 1 and 37.

(10).toString(16) // a

(35).toString(36) // z

This method should be really useful but should be used to reduce integer size too.
The limit of this function is its max usable radix, 36, but is possible to extend this one? Of course :-)

(35).toString(63), // z
(61).toString(63), // Z
(62).toString(63) // _

My Base63 implementation allows both toString(radix) and parseInt functions to be compatible with maximum possible radix.

For possible I mean only these chars: [0-9] [a-z] [A-Z] plus last special char _

These chars are compatible with \w RegExp syntax and this means that You can use less than 60% of chars to rappresent an integer value.

var myInt = 123456789012345,
myTinyInt = myInt.toString(63);

String(myInt).length, // 15
myTinyInt.length, // 8
myInt, // 123456789012345
myTinyInt // vlzFV_Fx

At this point, with a small code overload, You could quickly trasform every \w match into original integer value.

function(s){var b="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_",l=s.length,p=0,r=0;while(l--)r+=Math.pow(63,l)*b.indexOf(s.charAt(p++));return r}
); // 123456789012345.36280109005

Interesting? Just think, for example, about an array of integers and a JSON like client/server interaction.

I hope this will be useful, regards.

No comments: