Created
October 11, 2021 21:04
-
-
Save andrewbruner/86a65d59d7425883d85621f1a0b40f66 to your computer and use it in GitHub Desktop.
Returns if ISBN-10 is valid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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