test_bignum.js (2423B)
1 "use strict"; 2 3 function assert(actual, expected, message) { 4 if (arguments.length == 1) 5 expected = true; 6 7 if (actual === expected) 8 return; 9 10 if (actual !== null && expected !== null 11 && typeof actual == 'object' && typeof expected == 'object' 12 && actual.toString() === expected.toString()) 13 return; 14 15 throw Error("assertion failed: got |" + actual + "|" + 16 ", expected |" + expected + "|" + 17 (message ? " (" + message + ")" : "")); 18 } 19 20 function assertThrows(err, func) 21 { 22 var ex; 23 ex = false; 24 try { 25 func(); 26 } catch(e) { 27 ex = true; 28 assert(e instanceof err); 29 } 30 assert(ex, true, "exception expected"); 31 } 32 33 // load more elaborate version of assert if available 34 try { __loadScript("test_assert.js"); } catch(e) {} 35 36 /*----------------*/ 37 38 function bigint_pow(a, n) 39 { 40 var r, i; 41 r = 1n; 42 for(i = 0n; i < n; i++) 43 r *= a; 44 return r; 45 } 46 47 /* a must be < b */ 48 function test_less(a, b) 49 { 50 assert(a < b); 51 assert(!(b < a)); 52 assert(a <= b); 53 assert(!(b <= a)); 54 assert(b > a); 55 assert(!(a > b)); 56 assert(b >= a); 57 assert(!(a >= b)); 58 assert(a != b); 59 assert(!(a == b)); 60 } 61 62 /* a must be numerically equal to b */ 63 function test_eq(a, b) 64 { 65 assert(a == b); 66 assert(b == a); 67 assert(!(a != b)); 68 assert(!(b != a)); 69 assert(a <= b); 70 assert(b <= a); 71 assert(!(a < b)); 72 assert(a >= b); 73 assert(b >= a); 74 assert(!(a > b)); 75 } 76 77 function test_bigint1() 78 { 79 var a, r; 80 81 test_less(2n, 3n); 82 test_eq(3n, 3n); 83 84 test_less(2, 3n); 85 test_eq(3, 3n); 86 87 test_less(2.1, 3n); 88 test_eq(Math.sqrt(4), 2n); 89 90 a = bigint_pow(3n, 100n); 91 assert((a - 1n) != a); 92 assert(a == 515377520732011331036461129765621272702107522001n); 93 assert(a == 0x5a4653ca673768565b41f775d6947d55cf3813d1n); 94 95 r = 1n << 31n; 96 assert(r, 2147483648n, "1 << 31n === 2147483648n"); 97 98 r = 1n << 32n; 99 assert(r, 4294967296n, "1 << 32n === 4294967296n"); 100 } 101 102 function test_bigint2() 103 { 104 assert(BigInt(""), 0n); 105 assert(BigInt(" 123"), 123n); 106 assert(BigInt(" 123 "), 123n); 107 assertThrows(SyntaxError, () => { BigInt("+") } ); 108 assertThrows(SyntaxError, () => { BigInt("-") } ); 109 assertThrows(SyntaxError, () => { BigInt("\x00a") } ); 110 assertThrows(SyntaxError, () => { BigInt(" 123 r") } ); 111 } 112 113 test_bigint1(); 114 test_bigint2();