Skip to content

Instantly share code, notes, and snippets.

@misha-krainik
Created March 4, 2023 04:07
Show Gist options
  • Save misha-krainik/b7f802478f2e37504ccff7497a83be39 to your computer and use it in GitHub Desktop.
Save misha-krainik/b7f802478f2e37504ccff7497a83be39 to your computer and use it in GitHub Desktop.
enum Error {
recordNotFound,
notValidId,
}
class Result<T, E> {
T? value;
E? error;
Result.Ok(T value) {
this.value = value;
}
Result.Err(E error) {
this.error = error;
}
dynamic then({required Function ok, required Function err}) {
if (this.value != null) {
return ok(value);
}
if (this.error != null) {
return err(error);
}
}
}
class Record {
int _id;
get getId => _id;
Record({required id}) : _id = id;
String toString() => 'Record(id: $_id)';
}
class RecordStore {
final _records;
RecordStore({required records}) : _records = records;
Result<Record, Error> getRecordById(int searchId) {
if (searchId <= 0) return Result.Err(Error.notValidId);
for (final record in _records) {
if (record.getId == searchId) return Result.Ok(record);
}
return Result.Err(Error.recordNotFound);
}
}
void main() {
final store = RecordStore(
records: List<Record>.generate(10, (genNum) => Record(id: genNum)));
final result = store.getRecordById(-4);
result.then(ok: (record) {
print(record.toString());
}, err: (error) {
switch (error) {
case Error.recordNotFound:
print("Nothing to display at this time.");
break;
case Error.notValidId:
print(
"Invalid ID provided. Please enter a positive integer value for the record ID.");
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment