Skip to content

Instantly share code, notes, and snippets.

@hn3000
Last active July 7, 2018 10:20
Show Gist options
  • Save hn3000/bec217afe666b0ee0a0430e976df4d22 to your computer and use it in GitHub Desktop.
Save hn3000/bec217afe666b0ee0a0430e976df4d22 to your computer and use it in GitHub Desktop.
Sort numbers by width in Helvetica, as suggested by XKCD 2016
<!doctype html>
<html>
<head>
<title>Numbers ordered by width in Helvetica</title>
<style>
body { font: 13px Helvetica; }
</style>
</head>
<body>
<h1>Sort numbers by Width</h1>
<div><small>inspired by <a href="http://xkcd.com/2016/">XKCD 2016</a></small></div>
<div>
<ul id="list"></ul>
</div>
<canvas id="cnv"></canvas>
<script>
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var cnv = document.getElementById("cnv");
window.setTimeout(function () {
var ctx = cnv.getContext('2d');
ctx.font = '13px "Helvetica"';
var mm = [];
for (var i = 0, n = 2112; i < n; ++i) {
var t = '' + i;
var m = ctx.measureText(t);
mm.push({ t: t, w: m.width, m: m });
}
mm.sort(function (x, y) { return (x.w - y.w) || (x.t - y.t); });
console.clear();
console.log('text metric:', mm);
var dm = [];
var om = [];
for (var j = 0, nn = mm.length; j < nn; ++j) {
if (j === 0 || (mm[j - 1].w !== mm[j].w)) {
dm.push(__assign({}, mm[j], { c: 1 }));
}
else {
dm[dm.length - 1].c++;
}
}
console.log('text metric:', dm);
var list = document.getElementById('list');
list.innerHTML = '<li>' + dm.map(function (x) { return x.t + ": " + x.w + (" (" + x.c + ")"); }).join('</li><li>') + '</li>';
}, 100);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment