Skip to content

Instantly share code, notes, and snippets.

@timsneath
Last active March 11, 2023 23:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timsneath/f31879fc22ef2bb67ccac65ea106f063 to your computer and use it in GitHub Desktop.
Save timsneath/f31879fc22ef2bb67ccac65ea106f063 to your computer and use it in GitHub Desktop.
num-ranges
class Range<T extends num> {
final T from;
final T to;
num get magnitude => to - from;
Range(this.from, this.to);
factory Range.fromList(List<T> list) {
assert(list.length == 2);
return Range(list.first, list.last);
}
}
// Extension on Iterable<Range<T>> is not allowed. Error given:
// The name 'T' isn't a type, so it can't be used as a type argument.
extension RangeOfRanges on Iterable<Range<num>> {
Range<num> range() {
final min = (map((range) => range.from).toList()..sort()).first;
final max = (map((range) => range.to).toList()..sort()).last;
return Range<num>(min, max);
}
}
void main() {
final intRange = Range(-3, 6);
print(intRange.magnitude);
print(intRange.magnitude.runtimeType); // int, all good so far
final rangeList = <Range<double>>[
Range(3.5, 5.3),
Range(6.3, 9.2),
Range(-3.0, 13.1),
];
final rangeOfRanges = rangeList.range();
// I want to call a function that accepts Range<double>.
print(rangeOfRanges.runtimeType); // Range<num> :(
final nastyWorkaround = Range(
rangeOfRanges.from.toDouble(),
rangeOfRanges.to.toDouble()
);
print(nastyWorkaround.runtimeType); // Finally: Range<double>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment