-
Notifications
You must be signed in to change notification settings - Fork 0
/
LicensePlateFormatter.cpp
59 lines (49 loc) · 1.54 KB
/
LicensePlateFormatter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include "LicensePlateFormatter.h"
#include "LongestWordAccumulator.h"
#include <cctype>
namespace license_plate {
namespace {
CharacterType GetCharacterTypeOf(char character)
{
if (isalpha(character) != 0) {
return CharacterType::kLetter;
}
if (isdigit(character) != 0) {
return CharacterType::kDigit;
}
return CharacterType::kInvalid;
}
}
LicensePlateFormatter::LicensePlateFormatter()
: mLastChatacter(CharacterType::kInvalid)
, mConsecutiveCharacterCount(0U)
{
mResult.reserve(10U);
}
LicensePlateFormatter operator+(LicensePlateFormatter&& formatter, char character)
{
const CharacterType characterType = GetCharacterTypeOf(character);
// Early return for invalid characters.
if (characterType == CharacterType::kInvalid) {
return formatter;
}
const bool hasCharacterSwitched = characterType != formatter.mLastChatacter;
const bool hasReachedSegmentMaxSize = formatter.mConsecutiveCharacterCount >= 3;
const bool newSegment = hasCharacterSwitched || hasReachedSegmentMaxSize;
if (newSegment) {
const bool hasOngoingResult = !formatter.mResult.empty();
if (hasOngoingResult) {
formatter.mResult += '-';
}
formatter.mLastChatacter = characterType;
formatter.mConsecutiveCharacterCount = 0;
}
++formatter.mConsecutiveCharacterCount;
formatter.mResult += toupper(character);
return formatter;
}
std::string LicensePlateFormatter::Result() const
{
return mResult;
}
}