lib/core/text: add a last_separator to `Collection::join`
authorJean Privat <jean@pryen.org>
Mon, 7 Mar 2016 16:02:58 +0000 (11:02 -0500)
committerJean Privat <jean@pryen.org>
Thu, 10 Mar 2016 04:54:52 +0000 (23:54 -0500)
Signed-off-by: Jean Privat <jean@pryen.org>

lib/core/text/abstract_text.nit
lib/pthreads/concurrent_collections.nit

index 0d2848c..405eb76 100644 (file)
@@ -1887,7 +1887,11 @@ redef class Collection[E]
        #     assert [1, 2, 3].join(":")    == "1:2:3"
        #     assert [1..3].join(":")       == "1:2:3"
        #     assert [1..3].join            == "123"
-       fun join(separator: nullable Text): String
+       #
+       # if `last_separator` is given, then it is used to separate the last element.
+       #
+       #     assert [1, 2, 3, 4].join(", ", " and ")    == "1, 2, 3 and 4"
+       fun join(separator: nullable Text, last_separator: nullable Text): String
        do
                if is_empty then return ""
 
@@ -1898,13 +1902,19 @@ redef class Collection[E]
                var e = i.item
                if e != null then s.append(e.to_s)
 
+               if last_separator == null then last_separator = separator
+
                # Concat other items
                i.next
                while i.is_ok do
-                       if separator != null then s.append(separator)
                        e = i.item
-                       if e != null then s.append(e.to_s)
                        i.next
+                       if i.is_ok then
+                               if separator != null then s.append(separator)
+                       else
+                               if last_separator != null then s.append(last_separator)
+                       end
+                       if e != null then s.append(e.to_s)
                end
                return s.to_s
        end
index d55bad0..e0c53af 100644 (file)
@@ -161,10 +161,10 @@ abstract class ConcurrentCollection[E]
                return r
        end
 
-       redef fun join(sep)
+       redef fun join(sep, last_sep)
        do
                mutex.lock
-               var r = real_collection.join(sep)
+               var r = real_collection.join(sep, last_sep)
                mutex.unlock
                return r
        end