From 798b4e8940ca4a1c29bf76952dd861e1e8da6d93 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Stephan=20B=C3=B6sch-Plepelits?= <skunk@xover.mud.at>
Date: Sat, 16 Mar 2019 08:11:10 +0100
Subject: [PATCH] twigFunction enumerate(): adapt to new lang_enumarte method

---
 doc/TwigJS.md        |  1 +
 src/twigFunctions.js | 26 +++++++++++++++++++++-----
 2 files changed, 22 insertions(+), 5 deletions(-)

diff --git a/doc/TwigJS.md b/doc/TwigJS.md
index ab8526c9..97d59e22 100644
--- a/doc/TwigJS.md
+++ b/doc/TwigJS.md
@@ -62,6 +62,7 @@ There are several extra functions defined for the TwigJS language:
 * function `tagsPrefix(tags, prefix)`: return all tags with the specified prefix. The result will be an array with `{ "en": "name:en", "de": "name:de" }` (for the input `{ "name": "foo", "name:en": "english foo", "name:de": "german foo" }` and the prefix "name:").
 * function openingHoursState(opening_hours_definition): returns state of object as string: 'closed', 'open' or 'unknown'.
 * function colorInterpolate(map, value): interpolates between two or more colors. E.g. `colorInterpolate([ 'red', 'yellow', 'green' ], 0.75)`.
+* function enumerate(list): enumerate the given list, e.g. "foo, bar, and bla". Input either an array (`[ "foo", "bar", "bla" ]`) or a string with `;` as separator (`"foo;bar;bla"`).
 
 Extra filters:
 * filter websiteUrl: return a valid http link. Example: `{{ "www.google.com"|websiteUrl }}` -> "http://www.google.com"; `{{ "https://google.com"|websiteUrl }}` -> "https://google.com"
diff --git a/src/twigFunctions.js b/src/twigFunctions.js
index 1bde15a3..24333649 100644
--- a/src/twigFunctions.js
+++ b/src/twigFunctions.js
@@ -93,10 +93,26 @@ OverpassLayer.twig.extendFunction('evaluate', function (tags) {
   var d = global.currentCategory.layer.mainlayer.evaluate(ob)
   return d
 })
-OverpassLayer.twig.extendFunction('enumerate', function (value) {
-  let list = value.split(/,/)
-  if (list.length > 1) {
-    return list.slice(0, -1).join(lang_str.enumerate_join) +  lang_str.enumerate_last + list.slice(-1)[0]
+OverpassLayer.twig.extendFunction('enumerate', function (list) {
+  if (typeof list === 'string') {
+    list = list.split(/;/g)
   }
-  return value
+
+  if (list.length > 2) {
+    let result = lang_str.enumerate_start.replace('{0}', list[0]).replace('{1}', list[1])
+
+    for (let i = 2; i < list.length - 1; i++) {
+      result = lang_str.enumerate_middle.replace('{0}', result).replace('{1}', list[i])
+    }
+
+    return lang_str.enumerate_end.replace('{0}', result).replace('{1}', list[list.length - 1])
+  }
+  else if (list.length == 2) {
+    return lang_str.enumerate_2.replace('{0}', list[0]).replace('{1}', list[1])
+  }
+  else if (list.length > 0) {
+    return list[0]
+  }
+
+  return ''
 })