isISBN.js 1.4 KB

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