Created
September 21, 2018 14:48
-
-
Save jgrahamc/9811cdc25db6ea6226255e9f4913ff45 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
addEventListener('fetch', event => { | |
event.respondWith(getLogarithm(event.request)) | |
}) | |
async function getLogarithm(request) { | |
const url = new URL(request.url) | |
if (!url.searchParams.has("int")) { | |
return new Response("Missing query parameter 'int'", {status: 403}) | |
} | |
const stringInt = url.searchParams.get("int") | |
const paddedInt = padTo(4, stringInt) | |
const intInt = parseInt(stringInt) | |
if ((intInt < 1) || (intInt > 9999)) { | |
return new Response("'int' must be between 1 and 9999", {status: 403}) | |
} | |
const retrieved = await CARD.get(paddedInt) | |
if (retrieved === null) { | |
const logarithm = Math.log10(intInt) | |
const value = Math.round((logarithm - Math.floor(logarithm))*10000000) | |
const paddedValue = padTo(7, value) | |
CARD.put(paddedInt, paddedValue) | |
return makeCard(paddedInt, paddedValue, false) | |
} | |
const parsed = JSON.parse(retrieved) | |
return makeCard(paddedInt, parsed.value, true) | |
} | |
async function makeCard(l, r, found) { | |
var html = '<html><body style="font-family: monospace;"><table style="width: 320px; border: 2px solid black"><thead><tr><td></td><td colspan="4" align="center">Number.</td><td></td><td></td><td></td><td colspan="7" align="center">Table.</td><td></td></tr></thead><tbody>' | |
html += '<tr style="outline: solid 1px;"><td></td>' | |
html += perDigit(l) | |
html += "<td></td><td></td><td></td>" | |
html += perDigit(r) | |
html += "<td></td></tr>" | |
for (var j = 0; j < 9; j++) { | |
html += "<tr><td></td>" | |
html += circles(j, l) | |
html += "<td></td><td></td><td></td>" | |
html += circles(j, r) | |
html += "<td></td></tr>" | |
} | |
html += "</tbody></table>" | |
html += "<br>Card was " | |
html += found?"retrieved":"added" | |
html += "</body></html>" | |
return new Response(html, {headers: {"Content-Type": "text/html"}}) | |
} | |
function perDigit(s) { | |
var html = '' | |
for (var i = 0; i < s.length; i++) { | |
html += "<td>" | |
html += s.substr(i, 1) | |
html += "</td>" | |
} | |
return html | |
} | |
function circles(j, s) { | |
var html = '' | |
for (var i = 0; i < s.length; i++) { | |
html += "<td>" | |
html += parseInt(s.substr(i, 1)) > j?'●':'○' | |
html += "</td>" | |
} | |
return html | |
} | |
function padTo(n, s) { | |
return ("0".repeat(n-1) + s).substr(-n) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment