detectCCType function
This function determines the potential CC types based on the cardPatterns.
Returns a list of CreditCardType
s with the most likely type as the first.
Implementation
List<CreditCardType> detectCCType(String ccNumStr) {
List<CreditCardType> cardTypes = [];
ccNumStr = ccNumStr.replaceAll(_whiteSpace, '');
if (ccNumStr.isEmpty) {
return _customCards.cards.values.toList();
}
// Check that only numerics are in the string
if (_nonNumeric.hasMatch(ccNumStr)) {
return cardTypes;
}
_customCards.cards.forEach(
(String cardName, CreditCardType type) {
for (Pattern pattern in type.patterns) {
// Remove any spaces
String ccPatternStr = ccNumStr;
int patternLen = pattern.prefixes[0].length;
// Trim the CC number str to match the pattern prefix length
if (patternLen < ccNumStr.length) {
ccPatternStr = ccPatternStr.substring(0, patternLen);
}
if (pattern.prefixes.length > 1) {
// Convert the prefix range into numbers then make sure the
// CC num is in the pattern range.
// Because Strings don't have '>=' type operators
int ccPrefixAsInt = int.parse(ccPatternStr);
int startPatternPrefixAsInt = int.parse(pattern.prefixes[0]);
int endPatternPrefixAsInt = int.parse(pattern.prefixes[1]);
if (ccPrefixAsInt >= startPatternPrefixAsInt &&
ccPrefixAsInt <= endPatternPrefixAsInt) {
// Found a match
type.matchStrength = _determineMatchStrength(
ccNumStr,
pattern.prefixes[0],
);
cardTypes.add(type);
break;
}
} else {
// Just compare the single pattern prefix with the CC prefix
if (ccPatternStr == pattern.prefixes[0]) {
// Found a match
type.matchStrength = _determineMatchStrength(
ccNumStr,
pattern.prefixes[0],
);
cardTypes.add(type);
break;
}
}
}
},
);
cardTypes.sort((a, b) => b.matchStrength.compareTo(a.matchStrength));
return cardTypes;
}