You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
1.6 KiB
63 lines
1.6 KiB
const IS_SUCCESS = 'is-success';
|
|
const IS_ERROR = 'is-error';
|
|
const DELAY = 1000;
|
|
const CODE = generateCode(4);
|
|
let builder = '';
|
|
|
|
const display = /** @type {HTMLDivElement} */ (document.getElementById('display'));
|
|
const light = /** @type {HTMLDivElement} */ (document.getElementById('light'));
|
|
const keypad = /** @type {HTMLDivElement} */ (document.getElementById('keypad'));
|
|
|
|
/** @type {number|null} */
|
|
let taskId = null;
|
|
|
|
/**
|
|
* @param {number} len
|
|
* @returns {string}
|
|
*/
|
|
function generateCode(len) {
|
|
let code = '';
|
|
for (let i = 0; i < len; i++) {
|
|
code += Math.floor(Math.random() * 10).toString();
|
|
}
|
|
return code;
|
|
}
|
|
|
|
function resetCode() {
|
|
builder = '';
|
|
display.innerText = '_'.repeat(CODE.length);
|
|
light.classList.remove(IS_SUCCESS, IS_ERROR);
|
|
}
|
|
|
|
/**
|
|
* @param {number} digit
|
|
*/
|
|
function composeDigit(digit) {
|
|
if (taskId !== null) {
|
|
clearTimeout(taskId);
|
|
taskId = null;
|
|
}
|
|
builder += digit.toString();
|
|
display.innerText = builder + '_'.repeat(CODE.length - builder.length);
|
|
light.classList.remove(IS_SUCCESS, IS_ERROR);
|
|
if (CODE.startsWith(builder)) {
|
|
light.classList.add(IS_SUCCESS);
|
|
} else {
|
|
light.classList.add(IS_ERROR);
|
|
taskId = setTimeout(resetCode, DELAY);
|
|
}
|
|
}
|
|
|
|
for (let i = 1; i < 11; i++) {
|
|
const digit = i % 10;
|
|
const button = document.createElement('button');
|
|
button.innerText = digit.toString();
|
|
button.onclick = () => composeDigit(digit);
|
|
keypad.appendChild(button);
|
|
}
|
|
const reset = document.createElement('button');
|
|
reset.innerText = 'C';
|
|
reset.onclick = resetCode;
|
|
keypad.appendChild(reset);
|
|
resetCode();
|