Last active
April 13, 2026 08:13
-
-
Save Juul/9b83007e5566ccbf84c29a015efbaf79 to your computer and use it in GitHub Desktop.
Command-line node.js script to calculate an ISBN from an SBN
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
| #!/usr/bin/env node | |
| // Command-line node.js script to calculate an ISBN from an SBN | |
| // Note that this re-calculates the check digit (the last digit) | |
| // which may not be the correct thing to do. | |
| // Wikipedia claims that it should _not_ be recalculated but cites no sources | |
| function isbnCheck(isbn) { | |
| const str = isbn.toString(); | |
| var sum = 0; | |
| var i, number; | |
| for(i=0; i < str.length; i++) { | |
| number = str[i].toLowerCase(); | |
| if(number == 'x') number = 10; | |
| sum += (i+1) * parseInt(str[i]); | |
| } | |
| return sum % 11; | |
| } | |
| function sbnToIsbn(sbn) { | |
| if(isbnCheck(sbn.toString())) { | |
| console.error("Invalid SBN!"); | |
| process.exit(1); | |
| } | |
| // Prepend 0 and remove old check digit | |
| const str = '0'+sbn.toString().slice(0,-1); | |
| const checkDigit = isbnCheck(str); | |
| var isbn10 = str; | |
| if(checkDigit == 10) { | |
| isbn10 += 'X'; | |
| } else { | |
| isbn10 += checkDigit; | |
| } | |
| if(isbnCheck(isbn10)) { | |
| console.error("Conversion failed"); | |
| process.exit(1); | |
| } | |
| console.log("ISBN-10:", isbn10); | |
| } | |
| if(process.argv.length != 3) { | |
| console.log("Usage: ./sbn_to_isbn <sbn>"); | |
| process.exit(1) | |
| } | |
| sbnToIsbn(process.argv[2]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment