To calculate the check digit of an ISBN13 barcode
by Nayana Das
JavaScript
var isbnnum = window.prompt("Enter a 12 digit number to check ISBN13",""); //978014300723
//to check if the user input number contains 12 digits
if(isbnnum.length!=12){
isbnnum = window.prompt("Error!! Please enter the 12 digit number to check ISBN13","");
}
var output = [],
strnum = isbnnum.toString(); //coverted to string
//spliting number into individual number to an array
for (var i = 0, len = strnum.length; i < len; i += 1) {
output.push(+strnum.charAt(i));
}
var onemultiple=0, threemultiple=0;
//multiply each element in array alternatively by 1 and 3
for (i = 0; i < output.length; i++){
if (i % 2 === 0){
onemultiple += output[i];
} else {
threemultiple += output[i] * 3;
}
}
var sumofoutput = onemultiple+threemultiple; //sum of multiply
var modten = sumofoutput % 10; //mod 10 of the summed figure
var endnum = 10 - modten; //Subtracting 10
//Checking if the end number is 10, make it 0
if(endnum ==10){
output.push(0);
}else{
output.push(endnum);
}
var final_isbn = Number(output.join('')); //joining an array of numbers into one number as final ISBN number
alert("Check digit : "+endnum+"\nComplete ISBN : "+final_isbn);