Skip to content

Instantly share code, notes, and snippets.

@ilikerobots
Last active June 20, 2016 13:01
Show Gist options
  • Save ilikerobots/adb3ebb1f08c692eea5f30018b5cd046 to your computer and use it in GitHub Desktop.
Save ilikerobots/adb3ebb1f08c692eea5f30018b5cd046 to your computer and use it in GitHub Desktop.
Basic Examples: Mixins and typedefs in Dart
d(id) => new Document(id.toString()); //convenience function
List<Document> docs = [d('Foo'), d('bar'), d('BIZ'), d('Baz'), d('fab')];
///A simple document class with id
class Document {
String id;
Document(this.id);
toString() => id;
}
///Any function that meets this signature is a Matcher
typedef bool Matcher(String s, Document d);
abstract class AbstractDocumentRepo {
///The store of documents
List<Document> _repo;
AbstractDocumentRepo(this._repo);
///Search the documents, returning a list of matched docs
List<Document> search(String term) => _repo.where( (doc) => matcher(term, doc));
///A matching strategy for documents
Matcher get matcher;
}
class CaseSensitiveMatchingBehavior {
Matcher get matcher => (String s, Document d) => d.id.contains(s);
}
class CaseInsensitiveMatchingBehavior {
Matcher get matcher => (String s, Document d) => d.id.toLowerCase().contains(s.toLowerCase());
}
class SensitiveDocRepo extends AbstractDocumentRepo with CaseSensitiveMatchingBehavior {
SensitiveDocRepo(r): super(r);
}
class InsensitiveDocRepo extends AbstractDocumentRepo with CaseInsensitiveMatchingBehavior {
InsensitiveDocRepo(r): super(r);
}
class CustomDocRepo extends AbstractDocumentRepo {
CustomDocRepo(r): super(r);
Matcher get matcher => (String s, Document d) => d.id == s;
}
main() async {
print(" * Starting *");
AbstractDocumentRepo r1 = new SensitiveDocRepo(docs);
AbstractDocumentRepo r2 = new InsensitiveDocRepo(docs);
AbstractDocumentRepo r3 = new CustomDocRepo(docs);
print(r1.search("B"));
print(r2.search("B"));
print(r3.search("Baz"));
print("Is r1 case sensitive? ${r1 is CaseSensitiveMatchingBehavior}");
print("Is r1 case insensitive? ${r1 is CaseInsensitiveMatchingBehavior}");
print("Is r1.matcher a matcher? ${r1.matcher is Matcher}");
Function f = (String s, Document d) => false;
print("Is f a matcher? ${f is Matcher}");
Function g = (String s) => false;
print("Is g a matcher? ${g is Matcher}");
Function h = (String s, Document d) => s;
print("Is h a matcher? ${h is Matcher}");
print(" * Ending * ");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment