Skip to content

Instantly share code, notes, and snippets.

@sempostma
Created May 17, 2020 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sempostma/68a3b55b880b2593b56e2c45c6152d58 to your computer and use it in GitHub Desktop.
Save sempostma/68a3b55b880b2593b56e2c45c6152d58 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Programmer Benchmark</title>
</head>
<body>
<form autocomplete="off" autocapitalize="off" action="#" id="decimal-to-binary-form">
Decimal: <ins id="decimal-to-binary-input"></ins>
<br />
<label for="decimal-to-binary-output">Binary:</label>
<input type="text" name="binary" id="decimal-to-binary-output">
Preview: <ins id="decimal-to-binary-preview"></ins>
<br>
<button type="submit">Submit</button>
</form>
<script>
var q = document.querySelector.bind(document)
var qa = document.querySelectorAll.bind(document)
let decimalToBinaryInput;
function renderDecimalToBinaryQuestion() {
decimalToBinaryInput = Math.floor(Math.random() * 256);
q('#decimal-to-binary-input').innerText = decimalToBinaryInput
}
q('#decimal-to-binary-output').addEventListener('input', function(event) {
const binary = parseInt((event.target.value + '00000000').slice(0, 8), 2)
// q('#decimal-to-binary-preview').innerText = binary
})
q('#decimal-to-binary-form').addEventListener('submit', function(event) {
event.preventDefault();
const correct = ('00000000' + decimalToBinaryInput.toString(2)).slice(-8)
const result = q('#decimal-to-binary-output').value
if (correct.trim() !== result.trim()) {
alert('Wrong. Try again.')
console.log(`Correct: ${correct} does not equal ${result}`)
} else {
event.target.reset()
q('#decimal-to-binary-preview').innerText = ''
renderDecimalToBinaryQuestion()
}
})
renderDecimalToBinaryQuestion()
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment