upceToUpca method

String upceToUpca(
  1. String data
)

Convert a short version UPC-E barcode to a full length UPC-A

Implementation

String upceToUpca(String data) {
  final exp = RegExp(r'^\d{6,8}$');
  final match = exp.firstMatch(data);

  if (match == null) {
    throw BarcodeException('Unable to convert "$data" to UPC A Barcode');
  }

  var first = '0';
  String? checksum;

  switch (data.length) {
    case 8:
      checksum = data[7];
      first = data[0];
      data = data.substring(1, 7);
      break;
    case 7:
      first = data[0];
      data = data.substring(1, 7);
      break;
  }

  if (first != '0' && first != '1') {
    throw BarcodeException('Unable to convert "$data" to UPC A Barcode');
  }

  final d1 = data[0];
  final d2 = data[1];
  final d3 = data[2];
  final d4 = data[3];
  final d5 = data[4];
  final d6 = data[5];

  String manufacturer;
  String product;

  switch (d6) {
    case '0':
    case '1':
    case '2':
      manufacturer = '$d1$d2${d6}00';
      product = '00$d3$d4$d5';
      break;
    case '3':
      manufacturer = '$d1$d2${d3}00';
      product = '000$d4$d5';
      break;
    case '4':
      manufacturer = '$d1$d2$d3${d4}0';
      product = '0000$d5';
      break;
    default:
      manufacturer = '$d1$d2$d3$d4$d5';
      product = '0000$d6';
      break;
  }

  data = first + manufacturer + product;
  return data + (checksum ?? checkSumModulo10(data));
}