Skip to content

Instantly share code, notes, and snippets.

@jgrahamc jgrahamc/babbage.js
Last active Oct 8, 2018

Embed
What would you like to do?
addEventListener('fetch', event => {
event.respondWith(getLogarithm(event))
})
async function getLogarithm(event) {
const url = new URL(event.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 LOGCARD.get(paddedInt)
if (retrieved === null) {
const logarithm = Math.log10(intInt)
const value = Math.round((logarithm - Math.floor(logarithm))*10000000)
const paddedValue = padTo(7, value)
event.waitUntil(LOGCARD.put(paddedInt, paddedValue))
return makeCard(paddedInt, paddedValue, false)
}
return makeCard(paddedInt, retrieved.toString(), 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?'&#9679;':'&#9675;'
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
You can’t perform that action at this time.