#MonthOfCode - Day 3: binary

My entry for the 3rd day of the month of code. The theme for today is: binary.

Here’s a binary clock!

Code after the break.

Here are the interesting bits, IMHO:

  • quick zero left-padding: ('000' + n.toString(2)).slice(-4)
  • UTF-8 characters for the circles ○ ●
  • the transpose function which is a lot simpler than what I could have come up with myself
binary.jsview raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
(function() {

var el = document.getElementById('moc-3');

function updateClock(d) {
var time = '';
time += ('0' + d.getHours()).slice(-2); // hhmmss, padded
time += ('0' + d.getMinutes()).slice(-2);
time += ('0' + d.getSeconds()).slice(-2);

var binary = time
.split('') // convert each digit
.map(Number) // to a number
.map(function (n) {
return ('000' + n.toString(2)) // convert it to binary,
.slice(-4) // padded,
.split(''); // in an array
});

binary = transpose(binary);

var text = binary.map(function (line) {
return line
.join(' ')
.replace(/0/g, '○') // utf8 white circle
.replace(/1/g, '●'); // utf8 black circle
}).join('<br />');

el.innerHTML = text;
}

function transpose(matrix) {
// thanks stack overflow
// http://stackoverflow.com/questions/17428587/transposing-a-2d-array-in-javascript
return matrix[0].map(function(col, i) {
return matrix.map(function(row) {
return row[i];
})
});
}

function run() {
updateClock(new Date());
setTimeout(run, 900); // less than 1 sec to be sure not to miss a second
}
run();

})();