Last active
February 6, 2026 23:35
-
-
Save ajmas/fc5d00558dbc8a6c63f74438e60eebbc to your computer and use it in GitHub Desktop.
EAN to ISBN
This file contains hidden or 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
| // ref: https://tritonstore.com.au/ean-vs-isbn/ | |
| function checkDigitISSN (value: string): number | 'X' { | |
| let sum = 0; | |
| const len = value.length; | |
| for (let i = 0; i < value.length; i++) { | |
| sum += (parseInt(value.charAt(i)) * ((len - i) + 1)); | |
| } | |
| let checkdigit: number | 'X' = 11 - (sum % 11); | |
| if (checkdigit === 10) { | |
| checkdigit = 'X'; | |
| } | |
| return checkdigit; | |
| } | |
| function ean2isbn10 (ean: string, separator = '='): string | undefined { | |
| if (!(ean.startsWith('978') || ean.startsWith('979')) || ean.length !== 13) { | |
| throw new Error(`EAN ${ean} does not represent an ISBN`); | |
| } | |
| const value = ean.substring(3, ean.length - 1); | |
| const checkDigit = checkDigitISSN(value); | |
| return `${value.charAt(0)}${separator}${value.substring(1, 4)}${separator}${value.substring(4, 10)}${separator}${checkDigit}`; | |
| } | |
| function ean2isbn13 (ean: string): string | undefined { | |
| if (!(ean.startsWith('978') || ean.startsWith('979')) || ean.length !== 13) { | |
| throw new Error(`EAN ${ean} does not represent an ISBN`); | |
| } | |
| return `${ean.substring(0, 3)}-${ean.substring(4)}`; | |
| } | |
| export { ean2isbn10, ean2isbn13 }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment