Exam Answers, with Tests!
by Ray Toal
HTML
<link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-git.css">
<script src="https://code.jquery.com/qunit/qunit-2.0.1.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.0.1.css">
<div id="qunit"></div>
<div id="qunit-fixture"></div>
JavaScript
"use strict";
// These are my final exam solutions for LMU CMSI 185-02
// The exam was held on 2015-12-17.
// 1
function counts(a) {
let result = Object.create(null);
for (let s of a) {
s = s.toLowerCase()
result[s] = (result[s] || 0) + 1;
}
return result;
}
QUnit.test("Word count works", assert => {
assert.deepEqual(counts([]), {}, 'for the empty array');
assert.deepEqual(counts(['ah','ha','ha']), {ah:1, ha:2}, 'for a large array');
assert.deepEqual(counts(['HA','Ha','ha']), {ha:3}, 'ignoring case');
});
// 2
function suffixes(s) {
let result = [];
for (let i = 0; i <= s.length; i++) {
result.push(s.substring(s.length-i, s.length));
}
return result;
}
QUnit.test("Suffixes are computed correctly", assert => {
assert.deepEqual(suffixes(''), [''], 'for the empty string');
assert.deepEqual(suffixes('a'), ['', 'a'], 'for a one character string');
assert.deepEqual(suffixes('abc'), ['', 'c', 'bc', 'abc'], 'for multichar strings');
});
// 3
class Color {
constructor(red, green, blue) {
let validated = value => {
if (value < 0 || value > 255 || value % 1 !== 0) {
throw new Error('Invalid argument');
}
return +value;
}
this.red = validated(red);
this.green = validated(green);
this.blue = validated(blue);
}
toString() {
return 'rgb(' + this.red + ', ' + this.green + ', ' + this.blue + ')';
}
}
QUnit.test("For colors", assert => {
let c = new Color(38, 22, 11);
assert.equal(c.red, 38, 'we can get the red part');
assert.equal(c.green, 22, 'we can get the green part');
assert.equal(c.blue, 11, 'we can get the blue part');
assert.equal(c.toString(), 'rgb(38, 22, 11)', 'toString works as expected');
assert.throws(() => new Color(NaN, 20, 20), 'constructor throws if given a NaN argument');
assert.throws(() => new Color(undefined, 20, 20), 'constructor throws if given undefined');
assert.throws(() => new Color(1, 24.001, 20), 'constructor throws if given a...