In the last few “code” posts of Prose Poetry Code, there’s been one thing missing. One very important thing, and you might have noticed it. That’s right: there’s no code! I’ve been writing about generalities and theory and the like for a while now, but I’ve been neglecting the ugly innards. Part of that is because I haven’t been in much of a coding mood these past few months. Writing fiction was more interesting at the time. But I’ve had a few spare hours, and I really do want to get back into coding, so here goes.
A while back, I mentioned Typescript, a neat wrapper that sits on top of JavaScript and generally makes it palatable. And at the end of that post, I said I’d be playing around with the language. So here’s what I’ve got, a practical example of using Typescript. Well, dice rollers aren’t exactly practical—they’re a dime a dozen, and nobody really needs them—but you get the idea.
The code
I’ve posted a full ZIP of the code, including a config file, an HTML skeleton, and the JavaScript output. But here’s the Typescript code (dice.ts
) for your perusal.
// Simple function simulating a single die roll
function roll(sides: number): number {
return 1 + Math.floor(Math.random() * sides);
}
// Our "back-end" will roll a number of simulated dice,
// possibly adding a bonus or subtracting a penalty.
// It will return an object containing the rolls and their total.
// (This is really for no reason other than to show off interfaces.)
interface RollResult {
rolls: number[],
total: number
}
// Roll a number of dice, and return the results,
// using the object we defined above.
function rollMany(count: number, sides: number): RollResult {
let rolls : number[] = [];
for (let i = 0; i < count; i++) {
rolls.push(roll(sides));
}
let result = {
rolls: rolls,
total: rolls.reduce((a: number, b: number) => a+b, 0)
};
return result;
}
// This is where the interactive portion of the script begins.
// It's really just basic DOM stuff. In a moment, we'll actually
// hook it all up to the page.
function diceRoller() {
console.log("Rolling...");
let countBox = document.getElementById("count") as HTMLInputElement;
let sidesBox = document.getElementById("sides") as HTMLInputElement;
let addsBox = document.getElementById("adds") as HTMLInputElement;
let resultRollsText = document.getElementById("result");
let resultTotalText = document.getElementById("total");
let count = +countBox.value;
let sides = +sidesBox.value;
let adds = +addsBox.value;
let result = rollMany(count, sides);
let totalRoll = result.total + adds;
resultRollsText.innerHTML = result.rolls.join(" ");
resultTotalText.innerHTML = ""+ totalRoll;
}
// This clears out our results and options.
function clearAll() {
console.log("Clearing...");
// Note that this gives us an HTMLCollection...
let boxes = document.getElementsByClassName("entry");
// ...which can't be used like an array in for/of...
for (let b in boxes) {
// ...and contains only generic HTMLElements.
(boxes[b] as HTMLInputElement).value = "";
}
let resultText = document.getElementById("result");
let totalText = document.getElementById("total");
resultText.innerHTML = "";
totalText.innerHTML = "";
}
// Here's where we connect our functions to the page.
document.addEventListener("DOMContentLoaded", function () {
let clearButton = document.getElementById("clear");
let rollButton = document.getElementById("roll");
clearButton.onclick = clearAll;
rollButton.onclick = diceRoller;
});
Honestly, if you’ve seen JavaScript, you should have a pretty good idea of what’s going on here. We start with a helper function, roll
, which does the dirty work of generating a number from 1 to N, exactly as if you rolled a die with N sides. (It’s not perfect, as JavaScript uses pseudorandom numbers, but it’s the best we can do.) If you take out the two type declarations, you wouldn’t be able to tell this was Typescript.
Next comes something that inarguably identifies our source as not normal JS: an interface. We don’t really need it for something this simple, but it doesn’t cost anything, and it’s a good check on our typing. Our RollResult
interface simply defines an object “layout” that we’ll pass from our back-end rolling function to the front-end output. If we screw up, the compiler lets us know—that’s the whole point of strong typing.
After this is the rollMany
function. It builds on the simple roll
, calling it multiple times and storing each result in an array. This array, along with the sum of its contents, will become the returned object, matching our interface.
We’ll skip over the diceRoller
function briefly, as it’s the grand finale of our little app, and I wanted to save it for last. Instead, we move to clearAll
. It would be an unremarkable DOM manipulation function, if not for two quirks in Typescript. First, our simple HTML page defines a few entry boxes: one for the number of dice to roll, one for how many sides each die has, and one for a flat bonus or penalty to add to the total. These are <input>
text elements, and they all have a CSS class of entry
. Iterating over them (and only them) should be a piece of cake, right?
Not quite. See, the obvious way to do this, document.getElementsByClassName
, returns an HTMLCollection
, which isn’t quite the same thing as a JavaScript array. And Typescript, unless you tell it to spit out the latest and greatest ECMAScript standard (and I haven’t), won’t let you use the easier for..of
loop. Instead, you have to use for..in
, which iterates over the keys of a collection—for arrays, these are the indexes.
And that brings us to our second problem. See, our DOM collection is full of HTMLElements
. These could be anything at all, and are thus usable as essentially nothing. In particular, we can’t change the value
property that all input textboxes have, because not every HTML element has them. As any Java or C# programmer knows, we need an explicit cast into the more specific type of HTMLInputElement
. That seems like needless drudgery, but it pays off in more complex applications, and we could always use jQuery or something instead. In a “real” setting, we probably would be.
The areas where we output our rolls and their total are simple div
s. We don’t have to do any casting with them; we can just clear their innerHTML
properties. And the last bit is not much more than your usual “let’s set up some event handlers” block.
That leaves diceRoller
. First up are a few variables to hold the DOM elements: 3 text boxes and 2 output areas. Again, we have to do a cast on anything that’s an input element, but that should be old hat by now.
Following that, we make a few variables that hold our input values in number form. I used the idiomatic “unary plus” conversion from string to number here.
Next comes result
, which holds (naturally) our resulting roll. I threw in a totalRoll
variable to hold the total (including the “adds” roll bonus/penalty), but you don’t really need it; you can calculate that as you’re putting it into the output field. Speaking of which, that’s where we end: joining the result array into a space-separated string (you could use commas or whatever), then putting that and the total into their proper places.
Conclusion
So Typescript isn’t that hard. Counting comments and blank lines, this little thing weighs in at about 80 lines. The resulting JavaScript is less than 50. The difference comes from the strong typing, an interface definition that is purely for the benefit of the Typescript compiler and the programmer, and a few other odds and ends that contribute nothing physical to the finished product.
It may seem silly. We’re writing more code, locking ourselves into the type system, and we’re not really getting much out of it. Sure, we’ve got protection from typos. If I’d misspelled the name of one of the RollResult
fields, I’d get an error telling me where I went wrong, but that’s about it.
For something this simple, even that’s enough. I get that error when compiling. I don’t end up with a blank screen or unresponsive page and no indication as to why. JavaScript’s dynamic nature is great, but it’s also terrible. In coding, unlike in real life, there’s such a thing as too much freedom.
Now, if you like, feel free to take this tiny app and improve on it. The HTML, for instance, expects a stylesheet; you could make one. Add in some bells and whistles. Throw up a few preset buttons. Store the last 100 rolls in DOM local storage. Most of all, have fun with it.