Skip to content

Commit

Permalink
Use switch expression instead of if else
Browse files Browse the repository at this point in the history
  • Loading branch information
srujzs committed Sep 3, 2024
1 parent 23415f9 commit 98ababf
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 16 deletions.
2 changes: 1 addition & 1 deletion web/analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,4 @@ linter:
- prefer_const_declarations
- prefer_final_locals
- unnecessary_await_in_return
- use_string_buffers
- use_string_buffers
25 changes: 10 additions & 15 deletions web_generator/lib/src/translator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1093,23 +1093,18 @@ class Translator {
}

(List<code.Field>, List<code.Method>) _constant(_Constant constant) {
code.Code? body;
// If it's a value type that we can emit directly in Dart as a constant,
// emit this as a field so users can `switch` over it. Value types taken
// from: https://github.com/w3c/webidl2.js/blob/main/README.md#default-and-const-values
if (constant.valueType == 'string') {
body = code.literalString((constant.value as JSString).toDart).code;
} else if (constant.valueType == 'boolean') {
body = code
.literalBool(
(constant.value as JSString).toDart.toLowerCase() == 'true')
.code;
} else if (constant.valueType == 'number') {
body =
code.literalNum(num.parse((constant.value as JSString).toDart)).code;
} else if (constant.valueType == 'null') {
body = code.literalNull.code;
}
final body = switch (constant.valueType) {
'string' => code.literalString((constant.value as JSString).toDart),
'boolean' => code.literalBool(
(constant.value as JSString).toDart.toLowerCase() == 'true'),
'number' =>
code.literalNum(num.parse((constant.value as JSString).toDart)),
'null' => code.literalNull,
_ => null,
};
if (body != null) {
return (
[
Expand All @@ -1119,7 +1114,7 @@ class Translator {
..static = true
..modifier = code.FieldModifier.constant
..type = _typeReference(constant.type, returnType: true)
..assignment = body
..assignment = body.code
..name = constant.name.name,
)
],
Expand Down

0 comments on commit 98ababf

Please sign in to comment.