Created
May 15, 2020 05:06
-
-
Save McLarenCollege/377d53ad8b56f0de99c006f51234f915 to your computer and use it in GitHub Desktop.
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
function isbn13(input){ | |
let isbn = Array.from(input); | |
// console.log(isbn) | |
isbn[9] = isNaN(isbn[9])? 10 : isbn[9]; | |
isbn = convertForChecking(isbn); | |
if(isbn.reduce((a, b) => Number(a) + Number(b), 0) % (isbn.length === 10 ? 11 : 10) === 0){ | |
return isbn.length === 13 | |
? 'Valid' | |
: convertToIsbn13(input) | |
} | |
return 'Invalid'; | |
} | |
function convertToIsbn13(input){ | |
input = '978' + input.substring(0, input.length - 1); | |
let check = input.split(''); | |
check = convertForChecking(check); | |
check = check.reduce((a,b) => Number(a)+Number(b), 0); | |
input += 10 - (check % 10); | |
return input; | |
} | |
function convertForChecking(isbn){ | |
let length = isbn.length; | |
// console.log(isbn, length); | |
return length === 10 | |
? isbn.map((digit, index) => !isNaN(digit) ? digit * (length - index) : 10 * (length - index)) | |
: isbn.map((digit, index) => digit * (index % 2 !== 0 ? 3 : 1)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment