exercism

Exercism - TwoFer

This post shows you how to get TowFer excercise of Exercism.

Stevinator Stevinator
3 min read
exercism dart flutter two-fer

Preparation

Before we click on our next exercise, let’s see what concepts of DART we need to consider

TwoFer Exercise

Conditionals

It is basically a short version of an if-else statement, also called “Ternary Operator.”

condition ? expression 1 : expression 2

If the condition is true, the expression will return expression 1, else expression 2

void main() {
	var result = 15 > 20 ? "bigger" : "smaller";
	print(result);
}

To check if one of the expressions is null, you can use the conditional operator ??

expression 1 ?? expression 2

If the first expression is null, then the second expression will be printed and vice versa.

main() {
	print(null ?? 1);
	print(1 ?? null);
	print(1 ?? 2);
	print(false ?? 1);
}

Optional Parameters

There are three different versions of optional parameters:

  • Optional Positional
  • Optional Named
  • Optional Default
void main() {
  print("Optional Positional");
  print(optionalPositional("a"));
  print("\n");

  print("Optional Named");
  print(optionalNamed("a", b: "b"));
  print("\n");

  print("Optional Default");
  print(optionalDefault("a"));
}

String optionalPositional(String a, [String b]) {
  return "a = $a" + " und b = $b";
}

String optionalNamed(String a, {String b, String c}) {
  return "a = $a" + " und b = $b" + " und c = $c";
}

String optionalDefault(String a, [String b = "b"]) {
  return "a = $a" + " und b = $b";
}

Expression Bodied Method

When we have a method with one code line, we can use this concept to keep our code tidy.

String name() => return 'Stevinator';

Instructions

Two-fer or 2-fer is short for two for one. One for you and one for me. Given a name, return a string with the message:

One for X, one for me. Where X is the given name.

However, if the name is missing, return the string:

One for you, one for me.

Here are some examples:

Alice → One for Alice, one for me.

Bob → One for Bob, one for me.

→ One for you, one for me.

Zaphod → One for Zaphod, one for me.

So basically, we are getting a parameter (or not) as a String, and we need to add it to another String and return it.

Solution

Using what we learned before, one solution would look like this.

String twoFer([String name = 'you']) => 'One for $name, one for me.';

You can watch this tutorial on YouTube. So don’t forget to like and subscribe. 😉

Watch on YouTube
Stevinator

Stevinator

Stevinator is a software engineer passionate about clean code and best practices. Loves sharing knowledge with the developer community.