scratch/2021-07-05/michael/index.html

67 lines
1.5 KiB
HTML
Raw Permalink Normal View History

2021-07-07 01:48:49 +00:00
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>How many Letters?</title>
</head>
<body>
<textarea id="input" name="input" id="" cols="30" rows="10"></textarea>
<button id="submit" type="submit">Submit</button>
<h3>Output</h3>
<table id="output"></table>
</body>
<style>
table,
th,
td {
border: 1px solid black;
}
</style>
<script>
const btn = document.querySelector("#submit");
const textarea = document.querySelector("#input");
const table = document.querySelector("#output");
btn.addEventListener("click", () => {
let frequency = getFrequency(textarea.value);
output.innerHTML = mapToTableCells(frequency);
});
function mapToTableCells(map) {
let str = "<tr><th>Character</th><th>Times Appeared</th></tr>";
for (const pair of map[Symbol.iterator]()) {
str += `<tr><td>${pair[0]}</td><td>${pair[1]}</td></tr>`
}
return str;
}
function getFrequency(str) {
const freq = new Map();
for (let i = 0; i < str.length; i++) {
const char = str.charAt(i);
if (freq.has(char)) {
let count = freq.get(char);
freq.set(char, count + 1);
} else {
freq.set(char, 1);
}
}
return freq;
}
</script>
</html>