isLuhnValid function

bool isLuhnValid(
  1. String str
)

Returns true if str passes the Luhn checksum algorithm.

Implementation

bool isLuhnValid(String str) {
  final sanitized = str.replaceAll(RegExp(r'\D'), '');
  if (sanitized.isEmpty) return false;

  var sum = 0;
  var shouldDouble = false;

  for (var i = sanitized.length - 1; i >= 0; i--) {
    var digit = int.parse(sanitized[i]);
    if (shouldDouble) {
      digit *= 2;
      if (digit >= 10) digit -= 9;
    }
    sum += digit;
    shouldDouble = !shouldDouble;
  }
  return sum % 10 == 0;
}