游乐场测试
HTML
<html>
<body>
<div id="price1">别急,先等个几秒钟的~~</div>
<div id="price2"></div>
</body>
<script>
function price1(n)
{
if(n >= 1 && n <= 5) return 5;
else if(n >= 6 && n <= 10) return 4;
else if(n >= 11 && n <= 20) return 3;
else if(n >= 21) return 2.5;
}
function price2(n)
{
const price_map = [{
min: 1,
max: 5,
price: 5,
},{
min: 6,
max: 10,
price: 4,
},{
min: 11,
max: 20,
price: 3,
},{
min: 21,
max: Infinity,
price: 2.5,
}];
for(const item of price_map)
{
if(n >= item.min && n <= item.max)
{
return item.price;
}
}
}
function getRandomInts(min, max, n)
{
return Array.from({length: n}, () => {
//The maximum is exclusive and the minimum is inclusive
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min);
});
}
const counts1 = getRandomInts(1, 15, 100000000);
var start = performance.now();
for(const count of counts1)
{
price1(count);
}
var stop = performance.now();
document.getElementById('price1').innerHTML = `Price1 time is ${stop - start} ms.`
const counts2 = getRandomInts(1, 15, 100000000);
var start = performance.now();
for(const count of counts2)
{
price2(count);
}
var stop = performance.now();
document.getElementById('price2').innerHTML = `Price2 time is
${stop - start} ms.`
</script>
</html>