blob: ccdaee0087177f9c1b91c2fd97f957bb9e35e1f6 (
plain)
| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
 | function setErrorBox() {
  const main = document.querySelector(".main");
  const form = document.querySelector(".form");
  const errorBox = document.createElement("div");
  errorBox.classList.add("error-box");
  main.insertBefore(errorBox, form);
}
function getErrorBox() {
  let errorBox = document.querySelector(".error-box");
  if (!errorBox) {
    setErrorBox();
    errorBox = document.querySelector(".error-box");
  }
  return errorBox;
}
function removeErrorBox() {
  const errorBox = getErrorBox();
  errorBox.remove();
}
function printError(error) {
  const errorBox = getErrorBox();
  errorBox.textContent = error;
}
function isValidInput(key) {
  return key === "0" || key === "1";
}
function hasInvalidChar(string) {
  const regex = /(?![01])./g;
  const invalid = string.search(regex);
  return invalid === -1 ? false : true;
}
function handleInput(value) {
  if (hasInvalidChar(value)) {
    const error = "Error: valid characters are 0 or 1.";
    printError(error);
  } else {
    removeErrorBox();
  }
}
function convertBinToDec(bin) {
  let result = 0;
  for (const char of bin) {
    result = result * 2 + Number(char);
  }
  return result;
}
function handleSubmit(e) {
  e.preventDefault();
  const input = document.querySelector(".form__input");
  const result = document.getElementById("result");
  result.textContent = convertBinToDec(input.value);
}
function init() {
  const form = document.querySelector(".form");
  const input = document.querySelector(".form__input");
  handleInput(input.value);
  form.addEventListener("submit", handleSubmit);
  input.addEventListener("keyup", (e) => handleInput(e.target.value));
}
init();
 |