isISO6346.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.isISO6346 = isISO6346;
  6. exports.isFreightContainerID = void 0;
  7. var _assertString = _interopRequireDefault(require("./util/assertString"));
  8. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9. // https://en.wikipedia.org/wiki/ISO_6346
  10. // according to ISO6346 standard, checksum digit is mandatory for freight container but recommended
  11. // for other container types (J and Z)
  12. var isISO6346Str = /^[A-Z]{3}(U[0-9]{7})|([J,Z][0-9]{6,7})$/;
  13. var isDigit = /^[0-9]$/;
  14. function isISO6346(str) {
  15. (0, _assertString.default)(str);
  16. str = str.toUpperCase();
  17. if (!isISO6346Str.test(str)) return false;
  18. if (str.length === 11) {
  19. var sum = 0;
  20. for (var i = 0; i < str.length - 1; i++) {
  21. if (!isDigit.test(str[i])) {
  22. var convertedCode = void 0;
  23. var letterCode = str.charCodeAt(i) - 55;
  24. if (letterCode < 11) convertedCode = letterCode;else if (letterCode >= 11 && letterCode <= 20) convertedCode = 12 + letterCode % 11;else if (letterCode >= 21 && letterCode <= 30) convertedCode = 23 + letterCode % 21;else convertedCode = 34 + letterCode % 31;
  25. sum += convertedCode * Math.pow(2, i);
  26. } else sum += str[i] * Math.pow(2, i);
  27. }
  28. var checkSumDigit = sum % 11;
  29. return Number(str[str.length - 1]) === checkSumDigit;
  30. }
  31. return true;
  32. }
  33. var isFreightContainerID = isISO6346;
  34. exports.isFreightContainerID = isFreightContainerID;