[gnome-maps/wip/mlundblad/maps-uri: 4/11] utils: Add function to split string once




commit caf7b845d747d8d289ea766114fbad9c70d39e00
Author: Marcus Lundblad <ml update uu se>
Date:   Mon Oct 25 23:25:49 2021 +0200

    utils: Add function to split string once
    
    Adds a function to split a string at the
    first occurance of a separator, leaving any
    extra occurances in second part.

 src/utils.js       | 15 +++++++++++++++
 tests/utilsTest.js | 13 +++++++++++++
 2 files changed, 28 insertions(+)
---
diff --git a/src/utils.js b/src/utils.js
index fe308472..9c8ec3fd 100644
--- a/src/utils.js
+++ b/src/utils.js
@@ -499,3 +499,18 @@ function isValidEmail(email) {
 function firstToLocaleUpperCase(str) {
     return str[0].toLocaleUpperCase() + str.substring(1);
 }
+
+/* Splits string at first occurance of a character, leaving remaining
+ * occurances of the separator in the second part
+ */
+function splitAtFirst(string, separator) {
+    let [first, ...rest] = string.split(separator);
+
+    if (rest.length > 0) {
+        rest = rest.join(separator);
+
+        return [first, rest];
+    } else {
+        return [first];
+    }
+}
diff --git a/tests/utilsTest.js b/tests/utilsTest.js
index ddd010d3..09fb180f 100644
--- a/tests/utilsTest.js
+++ b/tests/utilsTest.js
@@ -41,6 +41,7 @@ function main() {
     validWebsiteTest();
     validEmailTest();
     firstToLocaleUpperCaseTest();
+    splitAtFirstTest();
 }
 
 function osmTypeToStringTest() {
@@ -137,3 +138,15 @@ function firstToLocaleUpperCaseTest() {
     JsUnit.assertEquals('فارسی', Utils.firstToLocaleUpperCase('فارسی'));
     JsUnit.assertEquals('日本語', Utils.firstToLocaleUpperCase('日本語'));
 }
+
+function _assertPair(first, second, array) {
+    JsUnit.assertEquals(2, array.length);
+    JsUnit.assertEquals(first, array[0]);
+    JsUnit.assertEquals(second, array[1]);
+}
+
+function splitAtFirstTest() {
+    _assertPair('q', 'Query', Utils.splitAtFirst('q=Query', '='));
+    _assertPair('q', 'Query=more', Utils.splitAtFirst('q=Query=more', '='));
+    JsUnit.assertEquals(1, Utils.splitAtFirst('noseparator', '=').length);
+}


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]