Adds support for custom split separators.
authorJakub Pawlowicz <contact@jakubpawlowicz.com>
Mon, 24 Aug 2015 04:36:44 +0000 (05:36 +0100)
committerJakub Pawlowicz <contact@jakubpawlowicz.com>
Mon, 24 Aug 2015 05:50:23 +0000 (06:50 +0100)
It defaults to braces as before but it can be customized to anything now.

lib/utils/split.js
test/utils/split-test.js

index c39ed7c..4a978a3 100644 (file)
@@ -1,4 +1,4 @@
-function split(value, separator, includeSeparator) {
+function split(value, separator, includeSeparator, openLevel, closeLevel) {
   var withRegex = typeof separator != 'string';
   var hasSeparator = withRegex ?
     separator.test(value) :
@@ -7,7 +7,10 @@ function split(value, separator, includeSeparator) {
   if (!hasSeparator)
     return [value];
 
-  if (value.indexOf('(') === -1 && !includeSeparator)
+  openLevel = openLevel || '(';
+  closeLevel = closeLevel || ')';
+
+  if (value.indexOf(openLevel) == -1 && !includeSeparator)
     return value.split(separator);
 
   var level = 0;
@@ -17,9 +20,9 @@ function split(value, separator, includeSeparator) {
   var tokens = [];
 
   while (cursor++ < len) {
-    if (value[cursor] == '(') {
+    if (value[cursor] == openLevel) {
       level++;
-    } else if (value[cursor] == ')') {
+    } else if (value[cursor] == closeLevel) {
       level--;
     } else if ((withRegex ? separator.test(value[cursor]) : value[cursor] == separator) && level === 0) {
       tokens.push(value.substring(lastStart, cursor + (includeSeparator ? 1 : 0)));
index 8221aed..f045022 100644 (file)
@@ -85,4 +85,24 @@ vows.describe(split)
       }
     }
   })
+  .addBatch({
+    'with custom wrappers - level 1': {
+      topic: 'a{ color:red; width:100% } p{ color:red }',
+      split: function (input) {
+        assert.deepEqual(split(input, ' ', true, '{', '}'), [ 'a{ color:red; width:100% } ', 'p{ color:red }' ]);
+      }
+    },
+    'with custom wrappers - level 2': {
+      topic: 'a{ color:red; --var { color:red; display: none } } p{ color:red }',
+      split: function (input) {
+        assert.deepEqual(split(input, ' ', true, '{', '}'), [ 'a{ color:red; --var { color:red; display: none } } ', 'p{ color:red }' ]);
+      }
+    },
+    'semicolon separated - variable list': {
+      topic: '--my-toolbar:{color:red;width:100%}',
+      split: function (input) {
+        assert.deepEqual(split(input, ';', false, '{', '}'), ['--my-toolbar:{color:red;width:100%}']);
+      }
+    }
+  })
   .export(module);