Permalink
Browse files

feature: Added 'asInt' convertion to DataAttribute

  • Loading branch information...
MikeMitterer committed Sep 1, 2016
1 parent 4def065 commit 67e9ba93ddadcd39b9d617ce377f2abb5c2373fa
Showing with 33 additions and 0 deletions.
  1. +17 −0 lib/mdlutils.dart
  2. +16 −0 test/unit/utils/utils_test.dart
View
@@ -93,6 +93,23 @@ class _DataValue {
}
return _value.toString();
}
/// turns value into a boolean
/// {defaultValue} defines the default value if the attribute is not set
/// or if attribute can not converted to an int
int asInt({ final int defaultValue: 0 }) {
if(_value == null) {
return defaultValue;
}
if(_value is num) {
return (_value as num).toInt();
}
final String string = _value.toString();
if(string.isEmpty) {
return defaultValue;
}
return int.parse(string,onError: (_) => defaultValue);
}
}
class ElementProperties {
@@ -39,6 +39,22 @@ main() {
expect(DataAttribute.forValue("").asBool(handleEmptyStringAs: true), isTrue);
}); // end of 'asBool' test
test('> asInt', () {
expect(DataAttribute.forValue("10").asInt(), 10);
expect(DataAttribute.forValue("1000").asInt(), 1000);
expect(DataAttribute.forValue("99").asInt(defaultValue: 42), 99);
expect(DataAttribute.forValue("99.-").asInt(defaultValue: 42), 42);
expect(DataAttribute.forValue("abc").asInt(), 0);
expect(DataAttribute.forValue("1000,10").asInt(), 0);
expect(DataAttribute.forValue("1.000").asInt(), 0);
expect(DataAttribute.forValue(null).asInt(), 0);
expect(DataAttribute.forValue("true").asInt(), 0);
expect(DataAttribute.forValue("false").asInt(), 0);
expect(DataAttribute.forValue("").asInt(), 0);
}); // end of 'asInt' test
});
// end 'DataAttribute' group

0 comments on commit 67e9ba9

Please sign in to comment.