split.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. var Marker = require('../tokenizer/marker');
  2. function split(value, separator) {
  3. var openLevel = Marker.OPEN_ROUND_BRACKET;
  4. var closeLevel = Marker.CLOSE_ROUND_BRACKET;
  5. var level = 0;
  6. var cursor = 0;
  7. var lastStart = 0;
  8. var lastValue;
  9. var lastCharacter;
  10. var len = value.length;
  11. var parts = [];
  12. if (value.indexOf(separator) == -1) {
  13. return [value];
  14. }
  15. if (value.indexOf(openLevel) == -1) {
  16. return value.split(separator);
  17. }
  18. while (cursor < len) {
  19. if (value[cursor] == openLevel) {
  20. level++;
  21. } else if (value[cursor] == closeLevel) {
  22. level--;
  23. }
  24. if (level === 0 && cursor > 0 && cursor + 1 < len && value[cursor] == separator) {
  25. parts.push(value.substring(lastStart, cursor));
  26. lastStart = cursor + 1;
  27. }
  28. cursor++;
  29. }
  30. if (lastStart < cursor + 1) {
  31. lastValue = value.substring(lastStart);
  32. lastCharacter = lastValue[lastValue.length - 1];
  33. if (lastCharacter == separator) {
  34. lastValue = lastValue.substring(0, lastValue.length - 1);
  35. }
  36. parts.push(lastValue);
  37. }
  38. return parts;
  39. }
  40. module.exports = split;