You could use the encoding of a seven-segment display and the following
- split by linefeed
'\n'
- build an array with single ASCII digits
- join a single ASCII digit to a string
- map the ASCII value
- join the result to a string
The ASCII value is taken with an object for a number, and the single segments are weighted with a value for the segment.
Value of segments is 2n.
_0_
|5 1|
_6_
|4 2|
_3_
Dots as segments
0
561
432
This generates the string
'909561432'
^ ^^^^^^ denoted segments with the number above
^ ^ no segments
For example, take
012
0
1 |
2 |
the ASCII string of 1, and the above segment numbers, then you get for the segment 1
the value 21 and for 2
the value 22. The result is 2 + 4 = 6
.
After a lookup in the bits object,
{
63: 0,
6: 1, // <----
91: 2,
/* ... */
}
you get the digit 1
.
function get7segment(ascii) {
return ascii.
split('\n').
reduce(function (r, a, i) {
a.match(/.../g).forEach(function (b, j) {
r[j] = r[j] || [];
r[j][i] = b;
});
return r;
}, []).
map(function (a) {
return a.join('');
}).
map(function (a) {
var bits = { 63: 0, 6: 1, 91: 2, 79: 3, 102: 4, 109: 5, 125: 6, 7: 7, 127: 8, 111: 9, 0: ' ' },
v = '909561432'.split('').reduce(function (r, v, i) {
return r + ((a[i] !== ' ') << v);
}, 0);
return v in bits ? bits[v] : '*'; // * is an illegal character
}).
join('');
}
function print(ascii) {
var pre = document.createElement('pre');
pre.innerHTML = ascii + '\n\n' + get7segment(ascii);
document.body.appendChild(pre);
}
print(' _ _ _ _ _ _ _ _ \n| | | _| _||_||_ |_ ||_||_| \n|_| ||_ _| | _||_| ||_| _|');
print(' _ _ _ ...\n | _| _| | ...\n | _| _| | ...');
print(' _ _ _ _ _ \n|_||_|| ||_||_ |\n | _||_||_||_| |');