compare-null-or-undef.js (1836B)
1 // Test relational comparison when one operand is null or undefined. 2 3 function test(xs) { 4 for (let i = 0; i < 200; ++i) { 5 let x = xs[i % xs.length]; 6 7 // The result is equal when compared to the result with explicit ToNumber conversions. 8 9 // Test when null-or-undefined is on the right-hand side. 10 assertEq(x < nullOrUndef, (+x) < (+nullOrUndef)); 11 assertEq(x <= nullOrUndef, (+x) <= (+nullOrUndef)); 12 assertEq(x >= nullOrUndef, (+x) >= (+nullOrUndef)); 13 assertEq(x > nullOrUndef, (+x) > (+nullOrUndef)); 14 15 // Test when null-or-undefined is on the left-hand side. 16 assertEq(nullOrUndef < x, (+nullOrUndef) < (+x)); 17 assertEq(nullOrUndef <= x, (+nullOrUndef) <= (+x)); 18 assertEq(nullOrUndef >= x, (+nullOrUndef) >= (+x)); 19 assertEq(nullOrUndef > x, (+nullOrUndef) > (+x)); 20 } 21 } 22 23 function runTest(inputs) { 24 let fNull = Function(`return ${test}`.replaceAll("nullOrUndef", "null"))(); 25 fNull(inputs); 26 27 let fUndefined = Function(`return ${test}`.replaceAll("nullOrUndef", "undefined"))(); 28 fUndefined(inputs); 29 } 30 31 // Null inputs. 32 runTest([ 33 null, 34 ]); 35 36 // Undefined inputs. 37 runTest([ 38 undefined, 39 ]); 40 41 // Null or undefined inputs. 42 runTest([ 43 null, 44 undefined, 45 ]); 46 47 // Int32 inputs 48 runTest([ 49 -0x8000_0000, 50 -0x7fff_ffff, 51 -0x7fff_fffe, 52 -2, 53 -1, 54 0, 55 1, 56 2, 57 0x7fff_fffe, 58 0x7fff_ffff, 59 ]); 60 61 // Number inputs 62 runTest([ 63 Number.NEGATIVE_INFINITY, 64 -Number.MAX_VALUE, 65 Number.MIN_SAFE_INTEGER, 66 -1.5, 67 -0.5, 68 -Number.EPSILON, 69 -Number.MIN_VALUE, 70 -0, 71 0, 72 Number.MIN_VALUE, 73 Number.EPSILON, 74 0.5, 75 1.5, 76 Number.MAX_SAFE_INTEGER, 77 Number.MAX_VALUE, 78 Number.POSITIVE_INFINITY, 79 NaN, 80 ]); 81 82 // Boolean inputs. 83 runTest([ 84 true, false, 85 ]); 86 87 // String inputs 88 runTest([ 89 "", 90 "0", "-0", "0.0", "0e100", 91 "1", "1.5", "-1234", "-1e0", 92 "Infinity", "NaN", "not-a-number", 93 ]);