isISBN.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = isISBN;
  6. var _assertString = _interopRequireDefault(require("./util/assertString"));
  7. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  8. var isbn10Maybe = /^(?:[0-9]{9}X|[0-9]{10})$/;
  9. var isbn13Maybe = /^(?:[0-9]{13})$/;
  10. var factor = [1, 3];
  11. function isISBN(str) {
  12. var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  13. (0, _assertString.default)(str);
  14. version = String(version);
  15. if (!version) {
  16. return isISBN(str, 10) || isISBN(str, 13);
  17. }
  18. var sanitized = str.replace(/[\s-]+/g, '');
  19. var checksum = 0;
  20. var i;
  21. if (version === '10') {
  22. if (!isbn10Maybe.test(sanitized)) {
  23. return false;
  24. }
  25. for (i = 0; i < 9; i++) {
  26. checksum += (i + 1) * sanitized.charAt(i);
  27. }
  28. if (sanitized.charAt(9) === 'X') {
  29. checksum += 10 * 10;
  30. } else {
  31. checksum += 10 * sanitized.charAt(9);
  32. }
  33. if (checksum % 11 === 0) {
  34. return !!sanitized;
  35. }
  36. } else if (version === '13') {
  37. if (!isbn13Maybe.test(sanitized)) {
  38. return false;
  39. }
  40. for (i = 0; i < 12; i++) {
  41. checksum += factor[i % 2] * sanitized.charAt(i);
  42. }
  43. if (sanitized.charAt(12) - (10 - checksum % 10) % 10 === 0) {
  44. return !!sanitized;
  45. }
  46. }
  47. return false;
  48. }
  49. module.exports = exports.default;
  50. module.exports.default = exports.default;