CODE93.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Encoding documentation:
  2. // https://en.wikipedia.org/wiki/Code_93#Detailed_outline
  3. import { SYMBOLS, BINARIES, MULTI_SYMBOLS } from './constants';
  4. import Barcode from "../Barcode.js";
  5. class CODE93 extends Barcode {
  6. constructor(data, options){
  7. super(data, options);
  8. }
  9. valid(){
  10. return /^[0-9A-Z\-. $/+%]+$/.test(this.data);
  11. }
  12. encode(){
  13. const symbols = this.data
  14. .split('')
  15. .flatMap(c => MULTI_SYMBOLS[c] || c);
  16. const encoded = symbols
  17. .map(s => CODE93.getEncoding(s))
  18. .join('');
  19. // Compute checksum symbols
  20. const csumC = CODE93.checksum(symbols, 20);
  21. const csumK = CODE93.checksum(symbols.concat(csumC), 15);
  22. return {
  23. text: this.text,
  24. data:
  25. // Add the start bits
  26. CODE93.getEncoding('\xff') +
  27. // Add the encoded bits
  28. encoded +
  29. // Add the checksum
  30. CODE93.getEncoding(csumC) + CODE93.getEncoding(csumK) +
  31. // Add the stop bits
  32. CODE93.getEncoding('\xff') +
  33. // Add the termination bit
  34. '1'
  35. };
  36. }
  37. // Get the binary encoding of a symbol
  38. static getEncoding(symbol) {
  39. return BINARIES[CODE93.symbolValue(symbol)];
  40. }
  41. // Get the symbol for a symbol value
  42. static getSymbol(symbolValue) {
  43. return SYMBOLS[symbolValue];
  44. }
  45. // Get the symbol value of a symbol
  46. static symbolValue(symbol) {
  47. return SYMBOLS.indexOf(symbol);
  48. }
  49. // Calculate a checksum symbol
  50. static checksum(symbols, maxWeight) {
  51. const csum = symbols
  52. .slice()
  53. .reverse()
  54. .reduce((sum, symbol, idx) => {
  55. const weight = (idx % maxWeight) + 1;
  56. return sum + (CODE93.symbolValue(symbol) * weight);
  57. }, 0);
  58. return CODE93.getSymbol(csum % 47);
  59. }
  60. }
  61. export default CODE93;