/** @module classes */
const BaseFactory = require('../Base.js');
/** Class representing an ISBN number. */
class ISBN {
constructor(isbn10, isbn13) {
this.isbn10 = isbn10;
this.isbn13 = isbn13;
}
/** Get the ISBN number. */
getISBN() {
return this.isbn13;
}
/** Get the ISBN-10 number. */
getISBN10() {
return this.isbn10;
}
}
/** Class representing an ISBN factory. */
class ISBNFactory extends BaseFactory {
/** Set the ISBN number. */
setISBN(isbn) {
isbn = isbn.replace(/-/g, '');
if (!/^\d+$/.test(isbn)) {
return this;
}
if (isbn.length === 13) {
this.isbn13 = isbn;
this.isbn10 = convISBN13toISBN10(isbn);
} else if (isbn.length === 10) {
this.isbn10 = isbn;
this.isbn13 = convISBN10toISBN13(isbn);
}
return this;
}
/** Create the ISBN. */
async create() {
if (!this.isbn10 && !this.isbn13) {
return null;
}
return new ISBN(this.isbn10, this.isbn13);
}
}
module.exports = { ISBN, ISBNFactory };
// no comment... https://gist.github.com/tsupo/108922
/**
* Converts ISBN-13 to ISBN-10
*
* @param {string} str
* @returns {string}
*/
function convISBN13toISBN10(str) {
var s;
var c;
var checkDigit = 0;
var result = "";
s = str.substring(3,str.length);
for ( i = 10; i > 1; i-- ) {
c = s.charAt(10 - i);
checkDigit += (c - 0) * i;
result += c;
}
checkDigit = (11 - (checkDigit % 11)) % 11;
result += checkDigit == 10 ? 'X' : (checkDigit + "");
return ( result );
}
/**
* Converts ISBN-10 to ISBN-13
*
* @param {string} str
* @returns {string}
*/
function convISBN10toISBN13(str) {
var c;
var checkDigit = 0;
var result = "";
c = '9';
result += c;
checkDigit += (c - 0) * 1;
c = '7';
result += c;
checkDigit += (c - 0) * 3;
c = '8';
result += c;
checkDigit += (c - 0) * 1;
for ( i = 0; i < 9; i++ ) { // >
c = str.charAt(i);
if ( i % 2 == 0 )
checkDigit += (c - 0) * 3;
else
checkDigit += (c - 0) * 1;
result += c;
}
checkDigit = (10 - (checkDigit % 10)) % 10;
result += (checkDigit + "");
return ( result );
}