Skip to content

Instantly share code, notes, and snippets.

@aab29
Last active July 6, 2018 20:40
Show Gist options
  • Select an option

  • Save aab29/7ef2b1d4a856b6fdfb6d1dec0f93537f to your computer and use it in GitHub Desktop.

Select an option

Save aab29/7ef2b1d4a856b6fdfb6d1dec0f93537f to your computer and use it in GitHub Desktop.
A silly simulation of a boat picking up cargo boxes at a port to demonstrate Dart's fat arrow syntax
import "dart:math";
class Port {
static final randomGenerator = new Random();
static const cargoNames = const [
"guano",
"fuzzy dice",
"weasles",
"bubble wrap",
"shoelaces",
"peanut butter"
];
int boxesCount = randomGenerator.nextInt(4) + 2;
static String nextCargoName() =>
cargoNames[randomGenerator.nextInt(cargoNames.length)];
static double nextCargoWeight() => 0.1 + randomGenerator.nextDouble() * 4.0;
bool hasBoxesRemaining() => boxesCount > 0;
CargoBox nextBox() {
boxesCount--;
return new CargoBox(nextCargoName(), nextCargoWeight());
}
}
abstract class Weighable {
double get weight;
String get formattedWeight => "${weight.toStringAsFixed(2)} tons";
}
class Boat extends Weighable {
static const baseWeight = 34.96;
List<CargoBox> cargoBoxes = [];
void addBox(CargoBox box) => cargoBoxes.add(box);
double get weight {
var totalWeight = baseWeight;
cargoBoxes.forEach((box) => totalWeight += box.weight);
return totalWeight;
}
bool isBoxesPlural() => cargoBoxes.length != 1;
String get boxesForm => isBoxesPlural() ? "boxes" : "box";
String get formattedBoxesCount => "${cargoBoxes.length} $boxesForm";
String get manifest {
var s =
"The boat weighs $formattedWeight and contains $formattedBoxesCount:\n";
for (var box in cargoBoxes) {
s += " $box\n";
}
return s;
}
}
class CargoBox extends Weighable {
final String contents;
final double weight;
CargoBox(this.contents, this.weight);
@override
String toString() =>
"a box that weighs $formattedWeight and contains $contents";
}
void main() {
var port = new Port();
var boat = new Boat();
print("A boat is stopping at a port with ${port
.boxesCount} boxes to load up.\n");
print(boat.manifest);
while (port.hasBoxesRemaining()) {
var box = port.nextBox();
print("Loading up $box.");
boat.addBox(box);
print("Now the manifest looks like this:\n${boat.manifest}");
}
print("That's all the boxes. The boat's final weight is ${boat
.formattedWeight}.");
print("Bon voyage!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment