toint32_2.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. function isnegativezero(x)
  6. {
  7. // this is a quick way to check if a number is -0
  8. return !(x != 0 || 1/x >= 0)
  9. }
  10. function test(value, expected)
  11. {
  12. var result = value | 0; // ToInt32
  13. if (!(result === expected && isnegativezero(result) === isnegativezero(expected)))
  14. {
  15. throw new Error(`toInt32 failed on ${value}`);
  16. }
  17. }
  18. var negZero = -0.0;
  19. test(0.0, 0.0);
  20. test(-0.0, 0.0);
  21. test(0.1, 0);
  22. test(-0.1, 0);
  23. test(1.1, 1);
  24. test(-1.1, -1);
  25. test(4294967295.5, -1);
  26. test(-4294967295.5, 1);
  27. test(4294967296, 0);
  28. test(-4294967296, 0);
  29. test(4294967297.1, 1);
  30. test(-4294967297.1, -1);
  31. test(2147483647, 2147483647);
  32. test(2147483648, -2147483648);
  33. test(Number.NEGATIVE_INFINITY, 0);
  34. test(Number.POSITIVE_INFINITY, 0);
  35. test(Number.NaN, 0);
  36. // We start losing precision here
  37. test(2147483647 * 2147483647 + 1024, 1024);
  38. // MAX 64-bit integer - 1024
  39. test(9223372036854775000, -1024);
  40. test(-9223372036854775000, 1024);
  41. // > 64-bit
  42. test(9223372036854776000, 0);
  43. test(9223372036854777000, 2048);
  44. test(9223372036854778000, 2048);
  45. test(-9223372036854776000, 0);
  46. test(-9223372036854777000, -2048);
  47. test(-9223372036854778000, -2048);
  48. print("pass");