luhnCheckDigit function

String luhnCheckDigit(
  1. String bodyDigits
)

The ISO/IEC 7812-1 Annex B (Luhn) mod-10 check digit for bodyDigits, everything before a card number's final digit, assumed already separator-free.

Doubling alternates from the right, starting on bodyDigits's last digit, so the check digit itself is never doubled. Mod-10 misses a 09/90 transposition and the twin errors 22/55, 33/66 and 44/77.

Implementation

String luhnCheckDigit(String bodyDigits) {
  final weightedSum = bodyDigits.codeUnits.reversed
      .mapIndexed(
        (position, codeUnit) =>
            position.isEven ? _doubled(decimalValue(codeUnit)) : decimalValue(codeUnit),
      )
      .sum;

  return ((_modulus - weightedSum % _modulus) % _modulus).toString();
}