Calculator Tutorial2. Convert to Javascript |
|
Join the DiscussionMore of this FeatureThe second step in creating a calculator script now that we have the formula that the calculator is to use is to convert that formula into Javascript. In the case of the Easter Calculator that I am building as we go through this example, the formula as written discards the fractional part after each division and so I need to add Math.floor functions around each division in the calculation. Apart from that the only other change I needed to make to the formula in my book (apart from correcting the code for the misprint) was to add var on the front of each declaration in order to let Javascript know that each is a new variable. So here is the Easter Calculator Formula rewritten from my book into Javascript:
var a = year % 19;
var b = Math.floor(year/100); var c = year % 100; var d = Math.floor(b/4); var e = b % 4; var f = Math.floor((b+8) / 25); var g = Math.floor((b-f+1) / 3); var h = (19*a + b - d - g + 15) % 30; var i = Math.floor(c/4); var j = c % 4; var k = (32 + 2*e + 2*i - h - j) % 7; var m = Math.floor((a + 11*h + 22*k) / 451); var month = Math.floor((h + k - 7*m + 114) / 31); var day = ((h + k - 7*m +114) % 31) + 1; Now that we have our formula (your's may not be anywhere near this complex) the next step is to test the formula to make sure that you haven't made any errors in setting it up. |

