source: node_modules/postgres-array/index.js

main
Last change on this file was 62b2964, checked in by Klimentina Efremova <klimentina08642@…>, 13 days ago

Project Handcraft Marketplace

  • Property mode set to 100644
File size: 2.3 KB
Line 
1'use strict'
2
3exports.parse = function (source, transform) {
4 return new ArrayParser(source, transform).parse()
5}
6
7class ArrayParser {
8 constructor (source, transform) {
9 this.source = source
10 this.transform = transform || identity
11 this.position = 0
12 this.entries = []
13 this.recorded = []
14 this.dimension = 0
15 }
16
17 isEof () {
18 return this.position >= this.source.length
19 }
20
21 nextCharacter () {
22 var character = this.source[this.position++]
23 if (character === '\\') {
24 return {
25 value: this.source[this.position++],
26 escaped: true
27 }
28 }
29 return {
30 value: character,
31 escaped: false
32 }
33 }
34
35 record (character) {
36 this.recorded.push(character)
37 }
38
39 newEntry (includeEmpty) {
40 var entry
41 if (this.recorded.length > 0 || includeEmpty) {
42 entry = this.recorded.join('')
43 if (entry === 'NULL' && !includeEmpty) {
44 entry = null
45 }
46 if (entry !== null) entry = this.transform(entry)
47 this.entries.push(entry)
48 this.recorded = []
49 }
50 }
51
52 consumeDimensions () {
53 if (this.source[0] === '[') {
54 while (!this.isEof()) {
55 var char = this.nextCharacter()
56 if (char.value === '=') break
57 }
58 }
59 }
60
61 parse (nested) {
62 var character, parser, quote
63 this.consumeDimensions()
64 while (!this.isEof()) {
65 character = this.nextCharacter()
66 if (character.value === '{' && !quote) {
67 this.dimension++
68 if (this.dimension > 1) {
69 parser = new ArrayParser(this.source.substr(this.position - 1), this.transform)
70 this.entries.push(parser.parse(true))
71 this.position += parser.position - 2
72 }
73 } else if (character.value === '}' && !quote) {
74 this.dimension--
75 if (!this.dimension) {
76 this.newEntry()
77 if (nested) return this.entries
78 }
79 } else if (character.value === '"' && !character.escaped) {
80 if (quote) this.newEntry(true)
81 quote = !quote
82 } else if (character.value === ',' && !quote) {
83 this.newEntry()
84 } else {
85 this.record(character.value)
86 }
87 }
88 if (this.dimension !== 0) {
89 throw new Error('array dimension not balanced')
90 }
91 return this.entries
92 }
93}
94
95function identity (value) {
96 return value
97}
Note: See TracBrowser for help on using the repository browser.