UNPKG

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