|
<!DOCTYPE html> |
|
<ul> |
|
<script type="text/javascript"> |
|
// 82 bytes |
|
var isValidEan13 = function(a) |
|
{ |
|
for (var b = /\d/g, //initialize regular expression to match single digits |
|
c = 0, //initialize checksum |
|
d, |
|
e = 25; //should be 25 - 13 * 2 = -1 in the end, so `~e` is 0 |
|
d = b.exec(a); //fetch a single digit from the input |
|
e -= 2) |
|
c += e % 4 * d; //multiply current digit with 3, 1, 3, 1 and so on |
|
return !(~e | c % 10) //e must be -1 and sum must be 0 |
|
} |
|
// 126 bytes |
|
var formatEan13 = function(a, b, c) |
|
{ |
|
for (a = ('' + a) //force `a` to be a string |
|
.split(/\D*/) //split into digits, remove all non-digits |
|
.slice(0, b = 12), //use the first 12 digits only |
|
c = 9; //this makes the final calculation easier, -1 also works |
|
b--; |
|
a[12] = 9 - c % 10) //append or replace checksum |
|
c += (b * 2 & 2 | 1) * //multiply current digit with 3, 1, 3, 1 and so on |
|
(a[b] += b % 6 ? '' : ' '); //format with spaces |
|
return a.join('') //array to string |
|
} |
|
var tests = ['5 449000 096241', '5 901234 123457', 9783161484100, |
|
'5 449000 096242', 9783161484105, 413456789018, 41345678901800, 413456789018000]; |
|
for (var i = 0; i < tests.length; i++) |
|
{ |
|
var v = isValidEan13(tests[i]); |
|
var e = formatEan13(tests[i]); |
|
document.write('<li>EAN/ISBN ' + |
|
(v ? '<var>' + tests[i] + '</var>' : '<b>' + tests[i] + '</b>') + |
|
' (a ' + typeof tests[i] + ') is ' + |
|
(v ? '' : 'in') + 'valid. Should be <var>' + e + '</var>.'); |
|
} |
|
</script> |
|
</ul> |
Should the function return false if there are more than 13 digits?