Direction.fromCardinal constructor

Direction.fromCardinal(
  1. String code
)

Factory constructor to create a Direction object from a cardinal direction code. Throws: AssertionError: Raised if code is not in compassDirs keys.

Implementation

factory Direction.fromCardinal(String code) {
  if (code == 'N') {
    return Direction('360');
  }

  final keys = compassDirs.keys;
  for (var key in keys) {
    if (key == code) {
      final dirs = compassDirs[key];
      final meanDir = dirs!.reduce((a, b) => a + b) / 2;
      final strDir = '${meanDir.toInt()}'.padLeft(3, '0');
      return Direction(strDir);
    }
  }

  throw AssertionError(
      'invalid cardinal direction code, use one of the following: ${compassDirs.keys}');
}