list.js 1.2 KB

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