algorithm11 function

bool algorithm11(
  1. String initialDigits,
  2. String verificationDigitString,
  3. TypeIdentification typeIdentification
)

Validates a number using the "modulo 11" algorithm, used for Ecuadorian RUC numbers.

initialDigits The initial digits of the RUC number. verificationDigitString The verification digit to validate. typeIdentification The type of identification being validated.

Returns true if the verification digit is valid.

Throws an IdentificationException if the verification digit is invalid, the identification type is not supported, or if any part of the identification is not a number.

Implementation

bool algorithm11(
  String initialDigits,
  String verificationDigitString,
  TypeIdentification typeIdentification,
) {
  final coefficients = listCoefficients[typeIdentification];

  if (coefficients == null) {
    throw IdentificationException(
      ErrorCode.invalidType,
      EcMessageKey.identificationInvalidType,
    );
  }

  final verificationDigit = int.tryParse(verificationDigitString);

  if (verificationDigit == null) {
    throw IdentificationException(
      ErrorCode.invalidVerificationDigit,
      EcMessageKey.verificationDigitNotNumber,
    );
  }

  final listDigits = initialDigits.split('').map((e) => int.parse(e)).toList();

  if (listDigits.length != coefficients.length) {
    throw IdentificationException(
      ErrorCode.invalidType,
      EcMessageKey.identificationInvalidType,
    );
  }

  int total = 0;

  for (int i = 0; i < listDigits.length; i++) {
    total += listDigits[i] * coefficients[i];
  }

  final remainder = total % 11;

  final result = remainder == 0 ? 0 : 11 - remainder;

  if (result != verificationDigit) {
    throw IdentificationException(
      ErrorCode.invalidVerificationDigit,
      EcMessageKey.verificationDigitInvalid
    );
  }

  return true;
}