Skip to content

Commit 4b70fb9

Browse files
authored
Merge pull request #229 from scratchcpp/fix_list_tostring_digits
Fix #188: Join digits without spaces in List::toString()
2 parents a26cf40 + 38f7b17 commit 4b70fb9

File tree

3 files changed

+46
-6
lines changed

3 files changed

+46
-6
lines changed

src/scratch/list.cpp

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,14 +43,36 @@ bool List::contains(const Value &value) const
4343
return (indexOf(value) != -1);
4444
}
4545

46-
/*! Joins the list items with spaces. */
46+
/*! Joins the list items with spaces or without any separator if there are only digits. */
4747
std::string List::toString() const
4848
{
4949
std::string ret;
50-
for (int i = 0; i < size(); i++) {
51-
ret.append(at(i).toString());
52-
if (i + 1 < size())
53-
ret.push_back(' ');
50+
bool digits = true;
51+
52+
for (const auto &item : *this) {
53+
if (item.type() == Value::Type::Integer) {
54+
long num = item.toLong();
55+
56+
if (num < 0 || num >= 10) {
57+
digits = false;
58+
break;
59+
}
60+
} else {
61+
digits = false;
62+
break;
63+
}
5464
}
65+
66+
if (digits) {
67+
for (const auto &item : *this)
68+
ret.append(item.toString());
69+
} else {
70+
for (int i = 0; i < size(); i++) {
71+
ret.append(at(i).toString());
72+
if (i + 1 < size())
73+
ret.push_back(' ');
74+
}
75+
}
76+
5577
return ret;
5678
}

test/engine/engine_test.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -422,7 +422,7 @@ TEST(EngineTest, Clones)
422422
if (i < 10)
423423
ASSERT_EQ((*list)[i].toInt(), 1);
424424
else
425-
ASSERT_EQ((*list)[i].toString(), "1 2"); // TODO: Change this to "12" after #188 is fixed
425+
ASSERT_EQ((*list)[i].toString(), "12");
426426
}
427427
}
428428

test/scratch_classes/list_test.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,4 +151,22 @@ TEST(ListTest, ToString)
151151
list.push_back("áä");
152152
list.push_back("ľ š");
153153
ASSERT_EQ(list.toString(), "áä ľ š");
154+
155+
list.clear();
156+
list.push_back(-2);
157+
list.push_back(5);
158+
list.push_back(8);
159+
ASSERT_EQ(list.toString(), "-2 5 8");
160+
161+
list.clear();
162+
list.push_back(2);
163+
list.push_back(10);
164+
list.push_back(8);
165+
ASSERT_EQ(list.toString(), "2 10 8");
166+
167+
list.clear();
168+
list.push_back(0);
169+
list.push_back(9);
170+
list.push_back(8);
171+
ASSERT_EQ(list.toString(), "098");
154172
}

0 commit comments

Comments
 (0)