list.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict'
  2. let list = {
  3. comma(string) {
  4. return list.split(string, [','], true)
  5. },
  6. space(string) {
  7. let spaces = [' ', '\n', '\t']
  8. return list.split(string, spaces)
  9. },
  10. split(string, separators, last) {
  11. let array = []
  12. let current = ''
  13. let split = false
  14. let func = 0
  15. let inQuote = false
  16. let prevQuote = ''
  17. let escape = false
  18. for (let letter of string) {
  19. if (escape) {
  20. escape = false
  21. } else if (letter === '\\') {
  22. escape = true
  23. } else if (inQuote) {
  24. if (letter === prevQuote) {
  25. inQuote = false
  26. }
  27. } else if (letter === '"' || letter === "'") {
  28. inQuote = true
  29. prevQuote = letter
  30. } else if (letter === '(') {
  31. func += 1
  32. } else if (letter === ')') {
  33. if (func > 0) func -= 1
  34. } else if (func === 0) {
  35. if (separators.includes(letter)) split = true
  36. }
  37. if (split) {
  38. if (current !== '') array.push(current.trim())
  39. current = ''
  40. split = false
  41. } else {
  42. current += letter
  43. }
  44. }
  45. if (last || current !== '') array.push(current.trim())
  46. return array
  47. }
  48. }
  49. module.exports = list
  50. list.default = list