Skip to content

Commit

Permalink
chore: remove unnecessary switch default clauses
Browse files Browse the repository at this point in the history
I also added a few assert messages
And simplified a couple hashCode implementations
and imported a modern copy of lerpDouble from Flutter
(and fixed lerpDouble not to modify arguments)

I think these lints are probably more trouble than they're worth
but fixing some of the easy ones.
  • Loading branch information
eseidel committed Sep 26, 2024
1 parent a7a2ef5 commit faace14
Show file tree
Hide file tree
Showing 30 changed files with 103 additions and 91 deletions.
2 changes: 1 addition & 1 deletion charts_common/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# cspell:words runtimetype tostring
# cspell:words runtimetype tostring bools
include: package:austerity/analysis_options.yaml

analyzer:
Expand Down
6 changes: 1 addition & 5 deletions charts_common/lib/src/chart/cartesian/axis/axis.dart
Original file line number Diff line number Diff line change
Expand Up @@ -668,11 +668,7 @@ class OrdinalViewport {
dataSize == other.dataSize;

@override
int get hashCode {
var hashcode = startingDomain.hashCode;
hashcode = (hashcode * 37) + dataSize;
return hashcode;
}
int get hashCode => startingDomain.hashCode * 37 + dataSize;
}

@visibleForTesting
Expand Down
19 changes: 16 additions & 3 deletions charts_common/lib/src/chart/cartesian/axis/axis_tick.dart
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,24 @@ class AxisTicks<D> extends Tick<D> implements Comparable<AxisTicks<D>> {
/// Linearly interpolate between two numbers.
///
/// From lerpDouble in dart:ui which is Flutter only.
double? _lerpDouble(double? a, double? b, double t) {
if (a == null && b == null) return null;
double? _lerpDouble(num? maybeA, num? maybeB, double t) {
var a = maybeA;
var b = maybeB;
if (a == b || (a?.isNaN ?? false) && (b?.isNaN ?? false)) {
return a?.toDouble();
}
a ??= 0.0;
b ??= 0.0;
return a + (b - a) * t;
assert(
a.isFinite,
'Cannot interpolate between finite and non-finite values',
);
assert(
b.isFinite,
'Cannot interpolate between finite and non-finite values',
);
assert(t.isFinite, 't must be finite when interpolating between values');
return a * (1.0 - t) + b * t;
}

@override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -514,9 +514,7 @@ abstract class BaseTickDrawStrategy<D> implements TickDrawStrategy<D> {
labelOffsetPx)
.toInt();
case TextDirection.center:
default:
x = (locationPx - labelOffsetPx).toInt();
break;
}
} else {
if (orientation == AxisOrientation.left) {
Expand Down Expand Up @@ -555,9 +553,7 @@ abstract class BaseTickDrawStrategy<D> implements TickDrawStrategy<D> {
labelOffsetPx)
.toInt();
case PixelVerticalDirection.center:
default:
y = (locationPx - labelHeight / 2 + labelOffsetPx).toInt();
break;
}
}
canvas.drawText(
Expand Down Expand Up @@ -591,7 +587,6 @@ abstract class BaseTickDrawStrategy<D> implements TickDrawStrategy<D> {
}
return TextDirection.center;
case TickLabelAnchor.centered:
default:
return TextDirection.center;
}
}
Expand All @@ -616,7 +611,6 @@ abstract class BaseTickDrawStrategy<D> implements TickDrawStrategy<D> {
}
return PixelVerticalDirection.center;
case TickLabelAnchor.centered:
default:
return PixelVerticalDirection.center;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ class RangeTickDrawStrategy<D> extends SmallTickDrawStrategy<D> {
// text and the axis baseline (even if it isn't drawn).

final maxHorizontalSliceWidth = ticks.fold(0, (prevMax, tick) {
assert(tick.textElement != null);
assert(tick.textElement != null, 'Tick text element is null.');
final labelElements = splitLabel(tick.textElement!);
if (tick is RangeAxisTicks) {
// Find the maximum within prevMax, label total height and
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ class LinearScale implements NumericScale {
void _configureScale() {
if (_scaleReady) return;

assert(_viewportSettings.range != null);
assert(_viewportSettings.range != null, 'Range must be set on the scale.');

// If the viewport's domainExtent are set, then we can calculate the
// viewport's scaleFactor now that the domainInfo has been loaded.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,10 @@ class NumericTickProvider extends BaseTickProvider<num> {
_desiredMinTickCount = null;
}

assert((_desiredMinTickCount == null) == (_desiredMaxTickCount == null));
assert(
(_desiredMinTickCount == null) == (_desiredMaxTickCount == null),
'Desired minTickCount and maxTickCount must be set together.',
);
}

/// Sets the allowed step sizes this tick provider can choose from.
Expand All @@ -188,14 +191,14 @@ class NumericTickProvider extends BaseTickProvider<num> {
///
/// [steps] allowed step sizes in the [1, 10) range.
set allowedSteps(List<double> steps) {
assert(steps.isNotEmpty);
assert(steps.isNotEmpty, "Allowed steps can't be empty.");
steps.sort();

final stepSet = Set.of(steps);
_allowedSteps = List<double>.filled(stepSet.length * 3, 0);
var stepIndex = 0;
for (final step in stepSet) {
assert(1.0 <= step && step < 10.0);
assert(1.0 <= step && step < 10.0, 'Step must be between 1 an 10.');
_allowedSteps[stepIndex] = _removeRoundingErrors(step / 100);
_allowedSteps[stepSet.length + stepIndex] =
_removeRoundingErrors(step / 10);
Expand Down
11 changes: 7 additions & 4 deletions charts_common/lib/src/chart/cartesian/axis/ordinal_extents.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,13 @@ class OrdinalExtents extends Extents<String> {
/// The elements of [range] must all be unique.
OrdinalExtents(List<String> range) : _range = range {
// This asserts that all elements in [range] are unique.
assert(() {
final uniqueValueCount = HashSet.of(_range).length;
return uniqueValueCount == range.length;
}());
assert(
() {
final uniqueValueCount = HashSet.of(_range).length;
return uniqueValueCount == range.length;
}(),
'Ordinal values must be unique.',
);
}

factory OrdinalExtents.all(List<String> range) => OrdinalExtents(range);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ class OrdinalScaleDomainInfo {
int? indexOf(String domain) => _domainsToOrder[domain];

String getDomainAtIndex(int index) {
assert(index >= 0);
assert(index < _index);
assert(index >= 0, 'Index $index is out of bounds.');
assert(index < _index, 'Index $index is out of bounds.');
return _domainList[index];
}

Expand Down
41 changes: 21 additions & 20 deletions charts_common/lib/src/chart/cartesian/axis/scale.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import 'dart:math' as math show max, min;

import 'package:nimble_charts_common/src/common/math.dart';

import 'package:nimble_charts_common/src/common/style/style_factory.dart'
show StyleFactory;

Expand Down Expand Up @@ -225,6 +224,22 @@ enum RangeBandType {
///
/// <p>RangeBandConfig is immutable, See factory methods for creating one.
class RangeBandConfig {
/// Creates a config that assigns the rangeBand according to the stylepack.
///
/// <p>Note: renderers can detect this setting and update the percent based on
/// the number of series in their preprocess.
RangeBandConfig.styleAssignedPercent()
: type = RangeBandType.styleAssignedPercentOfStep,
size = StyleFactory.style.rangeBandSize;

/// Creates a config that defines the rangeBand as the stepSize - pixels.
///
/// Where fixedPixels() gave you a constant rangBand in pixels, this will give
/// you a constant space between rangeBands in pixels.
const RangeBandConfig.fixedPixelSpaceBetweenStep(double pixels)
: type = RangeBandType.fixedPixelSpaceFromStep,
size = pixels;

/// Creates a rangeBand definition of zero, no rangeBand.
const RangeBandConfig.none()
: type = RangeBandType.none,
Expand Down Expand Up @@ -254,25 +269,11 @@ class RangeBandConfig {
/// [percentOfStepWidth] is the percentage of the step from 0.0 - 1.0.
RangeBandConfig.percentOfStep(double percentOfStepWidth)
: type = RangeBandType.fixedPercentOfStep,
size = percentOfStepWidth {
assert(percentOfStepWidth >= 0 && percentOfStepWidth <= 1.0);
}

/// Creates a config that assigns the rangeBand according to the stylepack.
///
/// <p>Note: renderers can detect this setting and update the percent based on
/// the number of series in their preprocess.
RangeBandConfig.styleAssignedPercent()
: type = RangeBandType.styleAssignedPercentOfStep,
size = StyleFactory.style.rangeBandSize;

/// Creates a config that defines the rangeBand as the stepSize - pixels.
///
/// Where fixedPixels() gave you a constant rangBand in pixels, this will give
/// you a constant space between rangeBands in pixels.
const RangeBandConfig.fixedPixelSpaceBetweenStep(double pixels)
: type = RangeBandType.fixedPixelSpaceFromStep,
size = pixels;
size = percentOfStepWidth,
assert(
percentOfStepWidth >= 0 && percentOfStepWidth <= 1.0,
'Percent must be between 0.0 and 1.0',
);
final RangeBandType type;

/// The width of the band in units specified by the bandType.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,7 @@ class DateTimeAxisSpec extends AxisSpec<DateTime> {
other is DateTimeAxisSpec && viewport == other.viewport && super == other;

@override
int get hashCode {
var hashcode = super.hashCode;
hashcode = (hashcode * 37) + viewport.hashCode;
return hashcode;
}
int get hashCode => (super.hashCode * 37) + viewport.hashCode;
}

abstract class DateTimeTickProviderSpec extends TickProviderSpec<DateTime> {}
Expand Down Expand Up @@ -255,7 +251,7 @@ class BasicDateTimeTickFormatterSpec implements DateTimeTickFormatterSpec {
/// [DateTimeFormatterFunction].
@override
DateTimeTickFormatter createTickFormatter(ChartContext context) {
assert(dateFormat != null || formatter != null);
assert(dateFormat != null || formatter != null, 'No formatter provided.');
return DateTimeTickFormatter.uniform(
SimpleTimeTickFormatter(
formatter: dateFormat != null ? dateFormat!.format : formatter!,
Expand All @@ -271,11 +267,7 @@ class BasicDateTimeTickFormatterSpec implements DateTimeTickFormatterSpec {
dateFormat == other.dateFormat);

@override
int get hashCode {
var hash = formatter.hashCode;
hash = (hash * 37) * dateFormat.hashCode;
return hash;
}
int get hashCode => (formatter.hashCode * 37) * dateFormat.hashCode;
}

/// [TickFormatterSpec] that automatically chooses the appropriate level of
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ class AutoAdjustingDateTimeTickProvider implements TickProvider<DateTime> {
int? minDifference;
late TimeRangeTickProvider closestTickProvider;

assert(_potentialTickProviders.isNotEmpty);
assert(_potentialTickProviders.isNotEmpty, 'No tick providers available');
for (final tickProvider in _potentialTickProviders) {
final difference =
(stepSize - tickProvider.getClosestStepSize(stepSize)).abs();
Expand All @@ -167,7 +167,7 @@ class AutoAdjustingDateTimeTickProvider implements TickProvider<DateTime> {
closestTickProvider = tickProvider;
}
}
assert(minDifference != null);
assert(minDifference != null, 'No closest tick provider found');
return closestTickProvider;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import 'package:nimble_charts_common/src/common/date_time_factory.dart';
abstract class BaseTimeStepper implements TimeStepper {
BaseTimeStepper(this.dateTimeFactory) {
// Must have at least one increment option.
assert(allowedTickIncrements.isNotEmpty);
assert(allowedTickIncrements.isNotEmpty, 'No tick increments allowed.');
}

/// The factory to generate a DateTime object.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ class HourTimeStepper extends BaseTimeStepper {
assert(
allowedTickIncrements
.every((increment) => increment >= 1 && increment <= 24),
'Increments must be between 1 and 24',
);

return HourTimeStepper._internal(dateTimeFactory, allowedTickIncrements);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,10 @@ class TimeRangeTickProviderImpl extends TimeRangeTickProvider {
} else {
allowedTickIncrements = timeStepper.allowedTickIncrements;
}
assert(allowedTickIncrements.isNotEmpty);
assert(
allowedTickIncrements.isNotEmpty,
"Allowed tick increments can't be empty.",
);

for (final tickIncrement in allowedTickIncrements) {
// Create tick values with a specified increment.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ class YearTimeStepper extends BaseTimeStepper {
// Set the default increments if null.
allowedTickIncrements ??= _defaultIncrements;

assert(allowedTickIncrements.every((increment) => increment > 0));
assert(
allowedTickIncrements.every((increment) => increment > 0),
'Increments must be greater than 0',
);

return YearTimeStepper._internal(dateTimeFactory, allowedTickIncrements);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ abstract class BaseCartesianRenderer<D> extends BaseSeriesRenderer<D>
AccessorFn<D> domainFn,
List<Object?> data,
) {
assert(data.isNotEmpty);
assert(data.isNotEmpty, 'Data must not be empty.');

var start = 1;
var end = data.length - 1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,9 +194,6 @@ class PercentInjector<D> implements ChartBehavior<D> {

series.setAttr(percentInjectedKey, true);
}

default:
throw ArgumentError('Unsupported totalType: $totalType');
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@ class LockSelection<D> implements ChartBehavior<D> {
switch (eventTrigger) {
case SelectionTrigger.tap:
_listener = GestureListener(onTapTest: _onTapTest, onTap: _onSelect);
default:
case SelectionTrigger.hover:
case SelectionTrigger.tapAndDrag:
case SelectionTrigger.pressHold:
case SelectionTrigger.longPressHold:
throw ArgumentError('LockSelection does not support the event '
'trigger "$eventTrigger"');
}
Expand Down Expand Up @@ -94,9 +97,7 @@ class LockSelection<D> implements ChartBehavior<D> {
case SelectionTrigger.longPressHold:
chart.registerTappable(this);
case SelectionTrigger.hover:
default:
chart.unregisterTappable(this);
break;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ class SelectNearest<D> implements ChartBehavior<D> {
onDragEnd: _onDeselectAll,
);
case SelectionTrigger.hover:
default:
_listener = GestureListener(
onHover: hoverEventDelay == null
? _onSelect
Expand All @@ -99,7 +98,6 @@ class SelectNearest<D> implements ChartBehavior<D> {
defaultReturn: false,
),
);
break;
}
}
late GestureListener _listener;
Expand Down Expand Up @@ -306,9 +304,7 @@ class SelectNearest<D> implements ChartBehavior<D> {
case SelectionTrigger.longPressHold:
chart.registerTappable(this);
case SelectionTrigger.hover:
default:
chart.unregisterTappable(this);
break;
}
}

Expand Down
Loading

0 comments on commit faace14

Please sign in to comment.