I've written 2 functions to determine a leap year. The first function "isLeapYear()" is a 25 liner that evaluates and prints to DOM. The second function "leapYear()" is a one liner and only returns true or false. I used console.time() to test them and strangely enough, the "leapYear()" takes about 10 times longer than the 25 liner. Can anyone tell me why that happens?
I've created a pen [here link to codepen][1] so you can see.
[1]: https://codepen.io/akaasap77/pen/jOVyJNZ
const result5 = document.getElementById('result5')
// testing
function isLeapYear() {
console.time('isLeapYear')
const ex5year = document.getElementById('ex5year').value
let result = 'is not a leap year'
var x = ex5year
if( x % 4 == 0 ){
if( x % 100 != 0 ) {
console.timeEnd('isLeapYear')
const answer = document.getElementById('answer')
answer.innerHTML = `${ex5year} is a leap year stage one`
return result
}
if( x % 100 === 0 && x % 400 === 0) {
console.timeEnd('isLeapYear')
answer.innerHTML = `${ex5year} is a leap year stage two`
return result
}
}
console.timeEnd('isLeapYear')
answer.innerHTML = `${ex5year} ${result}`
return result
}
//////////// FUNCTION TWO //////////
function leapYear(year) {
console.time('leapYear')
return ( year % 100 === 0 ) ? ( year % 400 === 0) : ( year % 4 === 0)
}
console.log(leapYear(2000))
console.timeEnd('leapYear')
body {
font-family: system-ui;
background: #f06d06;
color: white;
text-align: center;
}
<div class="result" id="result5">
<label for="year">Insert a year to evaluate</label>
<input type="text" name="year" id="ex5year" />
<input type="submit" value="Submit" onclick="isLeapYear()" />
<p id="answer"></p>
</div>
Aucun commentaire:
Enregistrer un commentaire