Skip to content

Instantly share code, notes, and snippets.

@andrewbruner
Created October 11, 2021 21:04
Show Gist options
  • Save andrewbruner/86a65d59d7425883d85621f1a0b40f66 to your computer and use it in GitHub Desktop.
Save andrewbruner/86a65d59d7425883d85621f1a0b40f66 to your computer and use it in GitHub Desktop.
Returns if ISBN-10 is valid
/**
* Returns if ISBN-10 is valid
*
* @param {string} isbn
* @returns {boolean}
*/
function isbn10IsValid(isbn) {
// split isbn into an array
let isbnArr = isbn.split('');
// remove and remember the check digit
let checkDigit = isbnArr.pop();
// multiply each digit by 10, 9, 8. . .
for (let i = 0; i < isbnArr.length; i++) {
isbnArr[i] = isbnArr[i] * (10 - i);
}
// find sum of all digits
let sum = isbnArr.reduce((acc, curr) => {
return acc + curr;
});
// find the remainder of sum mod 11
let mod = sum % 11;
// calculate the final check digit
let checkDigitCalc = 11 - mod;
// convert check digit to X if needed
if (checkDigitCalc == 10) {
checkDigitCalc = 'X';
}
// compare final check digits and return boolean
if (checkDigitCalc == checkDigit) {
return true
}
else {
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment