SassNumber.withUnits constructor

SassNumber.withUnits(
  1. num value, {
  2. List<String>? numeratorUnits,
  3. List<String>? denominatorUnits,
})

Creates a number with full numeratorUnits and denominatorUnits.

Implementation

factory SassNumber.withUnits(num value,
    {List<String>? numeratorUnits, List<String>? denominatorUnits}) {
  var valueDouble = value.toDouble();
  switch ((numeratorUnits, denominatorUnits)) {
    case (null || [], null || []):
      return UnitlessSassNumber(valueDouble);
    case ([var unit], null || []):
      return SingleUnitSassNumber(valueDouble, unit);
    // TODO(dart-lang/language#3160): Remove extra null checks
    case (var numerators?, null || []):
      return ComplexSassNumber(
          valueDouble, List.unmodifiable(numerators), const []);
    case (null || [], var denominators?):
      return ComplexSassNumber(
          valueDouble, const [], List.unmodifiable(denominators));
  }

  // dart-lang/language#3160 as well
  var numerators = numeratorUnits!.toList();
  var unsimplifiedDenominators = denominatorUnits!.toList();

  var denominators = <String>[];
  for (var denominator in unsimplifiedDenominators) {
    var simplifiedAway = false;
    for (var i = 0; i < numerators.length; i++) {
      var factor = conversionFactor(denominator, numerators[i]);
      if (factor == null) continue;
      valueDouble *= factor;
      numerators.removeAt(i);
      simplifiedAway = true;
      break;
    }
    if (!simplifiedAway) denominators.add(denominator);
  }

  return switch ((numerators, denominators)) {
    ([], []) => UnitlessSassNumber(valueDouble),
    ([var unit], []) => SingleUnitSassNumber(valueDouble, unit),
    _ => ComplexSassNumber(valueDouble, List.unmodifiable(numerators),
        List.unmodifiable(denominators))
  };
}