Last active
September 26, 2018 13:24
-
-
Save lrhn/b5e0372a347c522f8f3cabfd02f662c3 to your computer and use it in GitHub Desktop.
Example of Locale validation.
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
abstract class Locale { | |
String get languageCode; | |
String get scriptCode; | |
String get regionCode; | |
const factory Locale(String languageCode, | |
[String regionOrScriptCode, String regionCode]) = _Locale._select; | |
} | |
class _Locale implements Locale { | |
final String _language; | |
final String _region; | |
final String _script; | |
const _Locale._select(String language, [String regionOrScript, String region]) : | |
this.validate(language, | |
region == null ? null : regionOrScript, | |
region == null ? regionOrScript : region); | |
const _Locale.validate(this._language, this._script, this._region) | |
: assert(_language != null), | |
assert(_language.length >= 2), | |
assert(_language.length <= 8), | |
assert(_language.length != 4), | |
assert((_script ?? "xxxx").length == 4), | |
assert((_region ?? "xx").length >= 2), | |
assert((_region ?? "xx").length <= 3); | |
// Or whatever normalization to do in getters. | |
String get languageCode => _language.toLowerCase(); | |
String get scriptCode => _script == null ? null : _capitalize(_script); | |
String get regionCode => _region?.toUpperCase(); | |
String toString() { | |
var builder = new StringBuffer(languageCode); | |
if (_script != null) { | |
builder.write("_"); | |
builder.write(scriptCode); | |
} | |
if (_region != null) { | |
builder.write("_"); | |
builder.write(regionCode); | |
} | |
return builder.toString(); | |
} | |
} | |
// ASCII only. (TODO: Check first if already valid). | |
String _capitalize(String word) => | |
word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase(); | |
main() { | |
print(const Locale("zh")); | |
print(const Locale("zh", "TW")); | |
print(const Locale("zh", "Hant", "TW")); | |
print(const Locale("ZH", "HANT", "tw")); | |
try { | |
Locale("zhzh"); | |
} catch (e) { | |
print(e); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment