tryParse static method
Parses source
as a Quaternion. Returns null
in case of a problem.
Implementation
static Quaternion? tryParse(String source) {
final parts = numberAndUnitExtractor
.allMatches(source.replaceAll(' ', ''))
.where((match) => match.start < match.end)
.toList();
if (parts.isEmpty) {
return null;
}
num w = 0, x = 0, y = 0, z = 0;
final seen = <String>{};
for (final part in parts) {
final numberString = part.group(1) ?? '';
final number = num.tryParse(numberString);
final unitString = part.group(4) ?? '';
final unit = unitString.toLowerCase();
if (seen.contains(unit)) {
return null; // repeated unit
}
if (unit == '' && number != null) {
w = number;
} else if (numberString.isEmpty || number != null) {
switch (unit) {
case 'i':
x = number ?? 1;
case 'j':
y = number ?? 1;
case 'k':
z = number ?? 1;
default:
return null; // invalid unit
}
} else {
return null; // parse error
}
seen.add(unit);
}
return Quaternion(w, x, y, z);
}