big_ints.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* vim: set expandtab sw=4 ts=4 sts=4: */
  2. /**
  3. * phpMyAdmin's BigInts library
  4. */
  5. /**
  6. * @var BigInts object to handle big integers (in string)
  7. * as JS can handle upto 53 bits of precision only.
  8. */
  9. var BigInts = {
  10. /**
  11. * Compares two integer strings
  12. *
  13. * @param int1 the string representation of 1st integer
  14. * @param int2 the string representation of 2nd integer
  15. *
  16. * @return int 0 if equal, < 0 if int1 < int2, else > 0
  17. */
  18. compare: function(int1, int2) {
  19. // trim integers
  20. int1 = int1.trim();
  21. int2 = int2.trim();
  22. // length of integer strings
  23. var len1 = int1.length;
  24. var len2 = int2.length;
  25. // integer is -ve or not
  26. var isNeg1 = (int1[0] === '-');
  27. var isNeg2 = (int2[0] === '-');
  28. // Sign of int1 != int2 then no actual comparison
  29. // is needed we can return result directly
  30. if (isNeg1 !== isNeg2) {
  31. return (isNeg1 === true ? -1 : 1);
  32. }
  33. // replace - sign with 0
  34. int1[0] = isNeg1 ? '0' : int1[0];
  35. int2[0] = isNeg2 ? '0' : int2[0];
  36. // pad integers with 0 to make them
  37. // equal length
  38. int1 = BigInts.lpad(int1, len2);
  39. int2 = BigInts.lpad(int2, len1);
  40. // Now they are good to compare as strings
  41. if (int1 !== int2) {
  42. return (int1 < int2 ? -1 : 1);
  43. }
  44. return 0;
  45. },
  46. /**
  47. * Adds leading zeros to a integer given a total length
  48. *
  49. * @param int the string representation of the integer
  50. * @param total the total length required
  51. *
  52. * @return int the integer of length given with added leading
  53. * zeros if necessary
  54. */
  55. lpad: function(int, total){
  56. var len = int.length;
  57. var pad = '';
  58. while(len < total) {
  59. pad += '0';
  60. len++;
  61. }
  62. return (pad + int);
  63. }
  64. };