split.js 1.5 KB

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