Last active
July 6, 2018 20:36
-
-
Save aab29/08bf6e427d07a2c3b1acfb0647cf17ef to your computer and use it in GitHub Desktop.
Demonstrating the power of Dart's cascade syntax with an arbitrarily intricate Sentence class.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| enum SentencePurpose { declarative, imperative, interrogative, exclamatory } | |
| const endPunctuationByPurpose = const { | |
| SentencePurpose.declarative: ".", | |
| SentencePurpose.imperative: ".", | |
| SentencePurpose.interrogative: "?", | |
| SentencePurpose.exclamatory: "!" | |
| }; | |
| const underWaterSoundsByCharacter = const { | |
| "a": "blahb", | |
| "e": "leeh", | |
| "i": "bli", | |
| "o": "bloo", | |
| "u": "blub" | |
| }; | |
| class Sentence { | |
| List<String> _words = []; | |
| SentencePurpose purpose = SentencePurpose.declarative; | |
| void addWord(String word) => _words.add(word); | |
| void capitalizeFirstWord() { | |
| var firstWord = _words.first; | |
| var firstCharacter = firstWord[0]; | |
| var remainingWord = firstWord.substring(1); | |
| _words.first = firstCharacter.toUpperCase() + remainingWord; | |
| } | |
| String get joinedWords => _words.join(" "); | |
| String get endPunctuation => endPunctuationByPurpose[purpose]; | |
| String get completeText => joinedWords + endPunctuation; | |
| void reverse() => _words = _words.reversed.toList(); | |
| void speak() => print(completeText); | |
| void shout() => print(completeText.toUpperCase()); | |
| void whisper() => print(completeText.toLowerCase()); | |
| void speakUnderWater() { | |
| var underWaterText = completeText.toLowerCase(); | |
| for (var character in underWaterSoundsByCharacter.keys) { | |
| var sound = underWaterSoundsByCharacter[character]; | |
| underWaterText = underWaterText.replaceAll(character, sound); | |
| } | |
| print(underWaterText); | |
| } | |
| } | |
| void main() { | |
| var intro = new Sentence() | |
| ..addWord("my") | |
| ..addWord("name") | |
| ..addWord("is") | |
| ..addWord("Aaron") | |
| ..addWord("Barrett") | |
| ..purpose = SentencePurpose.declarative | |
| ..capitalizeFirstWord() | |
| ..speak(); | |
| new Sentence() | |
| ..purpose = SentencePurpose.exclamatory | |
| ..addWord("I") | |
| ..addWord("am") | |
| ..addWord("the") | |
| ..addWord("dartographer") | |
| ..shout(); | |
| intro | |
| ..reverse() | |
| ..whisper(); | |
| new Sentence() | |
| ..addWord("I") | |
| ..addWord("know") | |
| ..addWord("how") | |
| ..addWord("to") | |
| ..addWord("swim") | |
| ..purpose = SentencePurpose.declarative | |
| ..speak() | |
| ..purpose = SentencePurpose.interrogative | |
| ..speakUnderWater(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment