Micro Blog
Truncate a post to its first five characters, where a character may be an emoji or any other Unicode.
Adapted from Exercism’s problem specification (MIT). Listed under Strings & Text.
// FILE: micro_blog.nomi
//# Truncates a post to its first five characters.
/// The first five characters of `post`, or all of it when it is shorter. A
/// character is a grapheme, so an emoji is one, however many bytes it takes.
pub fn truncate(post: String) -> String
String.take(post, 5)
end
// FILE: micro_blog_test.nomi
import micro_blog
test "truncate"
[
("English language short", "Hi", "Hi"),
("English language long", "Hello there", "Hello"),
("German language short (broth)", "brühe", "brühe"),
("German language long (bear carpet → beards)", "Bärteppich", "Bärte"),
("Bulgarian language short (good)", "Добър", "Добър"),
("Greek language short (health)", "υγειά", "υγειά"),
("Maths short", "a=πr²", "a=πr²"),
("Maths long", "∅⊊ℕ⊊ℤ⊊ℚ⊊ℝ⊊ℂ", "∅⊊ℕ⊊ℤ"),
("English and emoji short", "Fly 🛫", "Fly 🛫"),
("Emoji short", "💇", "💇"),
("Emoji long", "❄🌡🤧🤒🏥🕰😀", "❄🌡🤧🤒🏥"),
("Royal Flush?", "🃎🂸🃅🃋🃍🃁🃊", "🃎🂸🃅🃋🃍"),
]
|> subtests (description, post, expected), description
assert micro_blog.truncate(post) == expected
end
end
// Not a canonical case: the canonical data avoids characters made of several
// codepoints. A family emoji is five codepoints joined into one grapheme, and
// an "e" with a combining accent is two, so each counts as one character.
test "graphemes of several codepoints"
assert micro_blog.truncate("👨👩👧 ok and more") == "👨👩👧 ok "
assert micro_blog.truncate("cafés") == "cafés"
endok truncate (12 cases)
ok graphemes of several codepoints
test result: ok. 13 passed, 0 failed
How it’s written
Section titled “How it’s written”truncateisString.take(post, 5). AStringis iterated, counted and taken by grapheme cluster, so an emoji is one character, and so is a letter with a combining accent. The exercise’s trap, counting UTF-16 code units or bytes, has no API to fall into.- The canonical data avoids characters of more than one codepoint. A test marked as not canonical adds two: a family emoji (five codepoints joined by zero-width joiners) and an
efollowed by a combining acute accent. Both count as one character, where a codepoint count would cut them apart. - The twelve canonical cases are one
subteststable.