min-max-foldsTo-1.js (1164B)
1 with ({}); // Don't inline anything into the top-level script. 2 3 function args() { return arguments; } 4 5 for (let xs of [ 6 // Array 7 [[], [1, 2, 3]], 8 9 // String 10 ["", "asdf"], 11 12 // ArrayBufferView 13 [new Int32Array(0), new Int32Array(10)], 14 15 // Arguments 16 [args(), args(1, 2, 3)], 17 ]) { 18 for (let cst of [0, -1]) { 19 // Fold `Math.min(length ≥ 0, constant ≤ 0)` to `constant`. 20 let min = Function("x", `return Math.min(x.length, ${cst})`); 21 for (let i = 0; i < 100; ++i) { 22 let x = xs[i & 1]; 23 assertEq(min(x), cst); 24 } 25 26 // Reverse operands. 27 min = Function("x", `return Math.min(${cst}, x.length)`); 28 for (let i = 0; i < 100; ++i) { 29 let x = xs[i & 1]; 30 assertEq(min(x), cst); 31 } 32 33 // Fold `Math.max(length ≥ 0, constant ≤ 0)` to `length`. 34 let max = Function("x", `return Math.max(x.length, ${cst})`); 35 for (let i = 0; i < 100; ++i) { 36 let x = xs[i & 1]; 37 assertEq(max(x), x.length); 38 } 39 40 // Reverse operands. 41 max = Function("x", `return Math.max(${cst}, x.length)`); 42 for (let i = 0; i < 100; ++i) { 43 let x = xs[i & 1]; 44 assertEq(max(x), x.length); 45 } 46 } 47 }