This commit is contained in:
Claudio Maggioni 2019-09-27 14:35:08 +02:00
parent 0af248a3d6
commit 6388526c01
2 changed files with 58 additions and 7 deletions

View file

@ -0,0 +1,6 @@
# HW2
Optional features implemented:
- bullet points in `mkIndenter()`
- clock (exercise 3)

View file

@ -173,23 +173,21 @@ function mkIndenter(line_size, level=0) {
} else if (param === true) {
return level;
} else if (typeof param === 'string') {
console.log(param);
let words = mkPrettyPrinter(line_size - level)(param);
words = words.map(e => ' ' * level + e);
words = words.map(e => ' '.repeat(level) + e);
state.push(...words);
console.log(line_size, level, param, state);
} else if (Array.isArray(param)) {
for (const e of param) {
if (typeof e !== 'string') {
return;
}
const words = mkPrettyPrinter(line_size - level - 2)(param);
state.push('* ' + words[0]);
const words = mkPrettyPrinter(line_size - level - 2)(e);
state.push(' '.repeat(level) + '* ' + words[0]);
for (let i = 1; i < words.length; i++) {
state.push(' ' + words[i]);
state.push(' '.repeat(level + 2) + words[i]);
}
}
} else if (param === void(0)) {
@ -210,6 +208,12 @@ function mkIndenter(line_size, level=0) {
* @return {number[]} An array indexed by the letter characters found in the string.
*/
function letter_frequency(s) {
if (typeof s !== 'string') {
return;
}
const a = [];
Array.from(s.toLowerCase()).forEach(c => a[c] = !a[c] ? 1 : a[c] + 1);
return a;
}
/**
@ -221,6 +225,21 @@ function letter_frequency(s) {
* @return {undefined}
*/
function display_letter_frequency(a, dom) {
if (typeof a !== 'object' || typeof dom !== 'object' || !dom) {
return;
}
const t = document.createElement('table');
for (const x in a) {
const r = document.createElement('tr');
const letter = document.createElement('td');
const element = document.createElement('td');
r.appendChild(letter);
r.appendChild(element);
letter.innerText = x;
element.innerText = '' + a[x];
t.appendChild(r);
}
dom.innerHTML = t.outerHTML;
}
/**
@ -229,11 +248,37 @@ function display_letter_frequency(a, dom) {
* @return {undefined}
*/
function online_frequency_analysis(inputEl) {
const a = letter_frequency(inputEl.value);
display_letter_frequency(a, document.getElementById('frequency_table'));
}
/**
* JavaScript Exercise 3
*/
function clock() {
const SECOND = 1000;
const MINUTE = SECOND * 60;
const HOUR = MINUTE * 60;
const digit = d => (d < 10 ? '0' : '') + d;
const format = (h, m, s) => digit(h) + ':' + digit(m) + ':' + digit(s);
function dateString(date) {
const epoch = Number.isInteger(date);
const h = epoch ? Math.floor(date / HOUR) : date.getHours();
const m = epoch ? Math.floor((date % HOUR) / MINUTE) : date.getMinutes();
const s = epoch ? Math.floor((date % MINUTE) / SECOND) : date.getSeconds();
return format(h, m, s);
}
const c = document.getElementById('clock');
let timer = false;
setInterval(() => {
d = new Date();
c.innerHTML = dateString(timer ? d - timer : d);
}, SECOND / 10);
return _ => timer = timer ? false : new Date();
}