convertMass function Null safety

double convertMass(
  1. Mass from,
  2. Mass to,
  3. double value
)

Convert Mass. It may lose some decimals in the proccess.

from, to and value can NOT be null, otherwise an AssertionError is thrown

Basic usage:

main() {
 final mass = convertMass(
   Mass.kilogram, // from
   Mass.gram, // to
   1, // value
 );
 print(mass); // 1000
}

Read the documentation for more information

Implementation

double convertMass(Mass from, Mass to, double value) {
  verify(from, to, value);
  if (from == to) return value;
  if (from == Mass.gram) {
    switch (to) {
      case Mass.tonne:
        return value / 1e+9;
      case Mass.kilogram:
        return value / 1000;
      case Mass.milligram:
        return value * 1000;
      case Mass.microgram:
        return value * 1e+6;
      case Mass.imperialTon:
        return value / 1.016e+6;
      case Mass.usTon:
        return value / 907185;
      case Mass.stone:
        return value / 6350;
      case Mass.pound:
        return value / 454;
      case Mass.ounce:
        return value / 28.35;
      default:
        return value;
    }
  } else {
    final gram = Mass.gram;
    switch (from) {
      case Mass.tonne:
        return convertMass(gram, to, value * 1e+9);
      case Mass.kilogram:
        return convertMass(gram, to, value * 1000);
      case Mass.milligram:
        return convertMass(gram, to, value / 1000);
      case Mass.microgram:
        return convertMass(gram, to, value / 1e+6);
      case Mass.imperialTon:
        return convertMass(gram, to, value * 1.016e+6);
      case Mass.usTon:
        return convertMass(gram, to, value * 907185);
      case Mass.stone:
        return convertMass(gram, to, value * 6350);
      case Mass.pound:
        return convertMass(gram, to, value * 454);
      case Mass.ounce:
        return convertMass(gram, to, value * 28.35);
      default:
        return value;
    }
  }
}