auto.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _constants = require('./constants');
  6. // Match Set functions
  7. var matchSetALength = function matchSetALength(string) {
  8. return string.match(new RegExp('^' + _constants.A_CHARS + '*'))[0].length;
  9. };
  10. var matchSetBLength = function matchSetBLength(string) {
  11. return string.match(new RegExp('^' + _constants.B_CHARS + '*'))[0].length;
  12. };
  13. var matchSetC = function matchSetC(string) {
  14. return string.match(new RegExp('^' + _constants.C_CHARS + '*'))[0];
  15. };
  16. // CODE128A or CODE128B
  17. function autoSelectFromAB(string, isA) {
  18. var ranges = isA ? _constants.A_CHARS : _constants.B_CHARS;
  19. var untilC = string.match(new RegExp('^(' + ranges + '+?)(([0-9]{2}){2,})([^0-9]|$)'));
  20. if (untilC) {
  21. return untilC[1] + String.fromCharCode(204) + autoSelectFromC(string.substring(untilC[1].length));
  22. }
  23. var chars = string.match(new RegExp('^' + ranges + '+'))[0];
  24. if (chars.length === string.length) {
  25. return string;
  26. }
  27. return chars + String.fromCharCode(isA ? 205 : 206) + autoSelectFromAB(string.substring(chars.length), !isA);
  28. }
  29. // CODE128C
  30. function autoSelectFromC(string) {
  31. var cMatch = matchSetC(string);
  32. var length = cMatch.length;
  33. if (length === string.length) {
  34. return string;
  35. }
  36. string = string.substring(length);
  37. // Select A/B depending on the longest match
  38. var isA = matchSetALength(string) >= matchSetBLength(string);
  39. return cMatch + String.fromCharCode(isA ? 206 : 205) + autoSelectFromAB(string, isA);
  40. }
  41. // Detect Code Set (A, B or C) and format the string
  42. exports.default = function (string) {
  43. var newString = void 0;
  44. var cLength = matchSetC(string).length;
  45. // Select 128C if the string start with enough digits
  46. if (cLength >= 2) {
  47. newString = _constants.C_START_CHAR + autoSelectFromC(string);
  48. } else {
  49. // Select A/B depending on the longest match
  50. var isA = matchSetALength(string) > matchSetBLength(string);
  51. newString = (isA ? _constants.A_START_CHAR : _constants.B_START_CHAR) + autoSelectFromAB(string, isA);
  52. }
  53. return newString.replace(/[\xCD\xCE]([^])[\xCD\xCE]/, // Any sequence between 205 and 206 characters
  54. function (match, char) {
  55. return String.fromCharCode(203) + char;
  56. });
  57. };