-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.js
332 lines (270 loc) · 10.3 KB
/
parse.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
Array.prototype.dump = function(opt={}) {
const ansi = require('ansi');
const cursor = ansi(process.stdout);
var rowColor = 1;
function log(display, isHeader = false) {
for (var counter = 0; counter < display.length; counter++) {
switch (display[counter]) {
case '+': cursor.brightMagenta(); cursor.write("+"); break;
case '-': cursor.magenta(); cursor.write("-"); break;
case '|': cursor.brightMagenta(); cursor.write("!"); break;
default: {
if (isHeader)
cursor.brightYellow();
else
if (rowColor % 2 == 0) cursor.brightWhite(); else cursor.brightBlue();
cursor.write(display[counter]);
}
}
}
console.log("");
rowColor++;
cursor.fg.reset();
}
function objectArray() {
for(var item of db) {
if(typeof(item) != "object") return false;
}
return true;
}
var sizes = {};
var tableData = this;
if (Array.isArray(tableData) && tableData.length != 0 && objectArray()) {
// Get col sizes
for(var item of tableData) {
for(var key of Object.keys(item)) {
if (!(key in sizes)) sizes[key] = key.toString().length + 1;
var itemSize = item[key].toString().length + 1;
if (sizes[key] < itemSize) sizes[key] = itemSize;
}
}
// Excludes
if ("exclude" in opt || Array.isArray(opt.exclude)) {
for(var ex of opt.exclude) {
delete sizes[ex];
};
}
// Build the separator
var sep = '+';
for (key of Object.keys(sizes)) {
sep += "-".repeat(sizes[key]+2);
sep += "+";
}
// Build Header
var header = "";
for (key of Object.keys(sizes)) {
var item = key.toString().padEnd(sizes[key]);
header += `| ${item} `;
}
header += `|`;
log(sep);
log(header, true);
log(sep);
// Build Items
for(var item of tableData) {
var row = "";
for (key of Object.keys(sizes)) {
var rowItem = (key in item) ?
item[key].toString().padEnd(sizes[key]) :
"".padEnd(sizes[key]);
row += `| ${rowItem} `;
}
log(row + '|');
}
log(sep);
} else throw new Error("Not an array -or- not an array of objects");
}
String.prototype.mathEx = function(compare, op) {
var value = this;
var match = false;
function isNumber(n) {
return (!isNaN(parseFloat(n)) && isFinite(n))
}
if (isNumber(value)) value = parseFloat(value); else value = null;
for(var tmpCompare of compare.split(/\|/g)) {
if (isNumber(tmpCompare)) Compare = parseFloat(tmpCompare); else Compare = null;
//console.log(value, op, Compare);
if (!eval(`${value} ${op} ${Compare}`)) match = true;
}
//if (op == "!=") match = (match==true) ? false : true;
match = !match;
return match;
}
Array.prototype.sortCol = function(pK, options={}) {
var db = this;
function isKeyNumber(pK) {
function isNumber(n) {
return (!isNaN(parseFloat(n)) && isFinite(n))
}
for(var item of db) {
if (pK in item && !isNumber(item[pK])) return false;
}
return true;
}
const isNumber = isKeyNumber(pK);
const isReverse = ("reverse" in options) ? options.reverse : false;
const isIgnoreCase = ("ignoreCase" in options) ? options.ignoreCase : false;
db.sort((a,b) => {
var result;
if (typeof a[pK] == 'undefined') {
result = -1;
} else {
if (isNumber)
result = (parseFloat(a[pK]) < parseFloat(b[pK])) ? -1 : 1;
else
result = (isIgnoreCase) ?
(a[pK].toLowerCase() < b[pK].toLowerCase()) ? -1 : 1 :
(a[pK] < b[pK]) ? -1 : 1;
}
return (isReverse) ? result *= -1 : result;
});
return db;
}
Object.prototype.query = function(Query, showQuery=false) {
var db = this;
var dataSet = db;
var results = [];
var query = buildQuery(Query);
if (Array.isArray(db) && objectArray()) {
if (showQuery) query.dump();
for (var thisTest of query) {
if ("chain" in thisTest) {
if (thisTest.chain == "&&") {
// And
dataSet = results;
results = [];
} else {
// Or
dataSet = db;
}
}
for (var row of dataSet) {
var value = String(row[thisTest.key]);
//console.log();
var rx = thisTest.value.join(',')
.replace(/,or,/g, "|")
.replace(/,and,/g, "&");
// What operation ?
var testResult = false;
if(thisTest.op == 'like') {
var test = new RegExp(rx, 'i');
testResult = value.match(test);
} else
if (thisTest.op == '==') {
var test = new RegExp(rx);
testResult = value.match(test);
} else
testResult = value.mathEx(rx, thisTest.op);
if (testResult && !results.includes(row)) {
results.push(row);
}
}
}
if (results.length == 0) {
return [{message:"Your query returned no results"}];
} else return results;
} else throw new Error("Not an array -or- not an array of objects");
/// -----------------------------------------------------------------
function objectArray() {
for(var item of db) {
if(typeof(item) != "object") return false;
}
return true;
}
function buildQuery(query) {
var queries = [];
var queriesBuilt = [];
var queryBuild = {};
// Is Sub Query
function isSub(query) {
queryTypes = [" == ", " != ", " like ", " > ", " >= ", " < ", " <= "];
return query.includes(queryTypes);
}
// Is argument a col in the db
function isCol(query) {
var cols = [];
for (var item of db) {
for (var col of Object.keys(item)) {
if (!cols.includes(col)) cols.push(col);
}
}
return cols.includes(query);
}
// Parses and or expressions
function parseAndOr(query) {
var Sub = [];
if (query.includes('"')) {
for(var tmp of query.split(/(\s?"(?:[^"\\]|\\.)*")\s?/)) {
tmp = tmp.trim();
tmp = tmp.replace(/^"/, "");
tmp = tmp.replace(/"$/, "");
if (tmp != "")
Sub.push(tmp);
}
} else Sub.push(query);
return Sub;
}
// Parses a query "chunk"
function parseQuery(query) {
var Query = query.split(' ');
var query = { key: "[PK]", op: "==", value: "" };
if (isCol(Query[0])) {
query.key = Query.shift();
query.op = Query.shift();
query.value = parseAndOr(Query.join(' '));
} else {
query.value = parseAndOr(Query.join(' '));
}
return query;
}
// Separate sub queries
for(var tmp of query.split(/(?:\s?(\&\&)\s?|\s?(\|\|)\s?)/g)) {
if (typeof tmp != 'undefined') queries.push(tmp);
}
for(var thisQuery of queries) {
if (thisQuery != "||" && thisQuery != "&&") {
var query = parseQuery(thisQuery);
queryBuild.key = query.key;
queryBuild.op = query.op;
queryBuild.value = parseAndOr(query.value);
queriesBuilt.push(queryBuild);
queryBuild = {};
} else {
queryBuild.chain = thisQuery;
}
}
return queriesBuilt;
}
}
var db = [
{name:"Matthew", color:'red', num:"90"},
{name:"Peter", color:'red', num:"8"},
{name:"Alice", color:'blue'},
{name:"alex", color:'blue', num:"0.1"},
{name:"Frank", color:'blue', num:"70"},
{name:"Grace", color:'blue', num:"0.3"},
{name:"steve", color:'yellow', num:"0"},
{name:"Q", color:'yellow'},
{name:"Jeff", color:'yellow', num:"20"},
{name:"Lucy", color:'green', num:"0.2"},
{name:"Molly", color:'green', num:"50"},
{name:"Sandy", color:'green', num:"10"},
{name:"Angie", color:'blue', num:"300"}
];
// db.query("name == ^[a-z].*", true).dump();
// db.query("name == e$ && color like blue", true).dump({exclude:["num"]});
// console.log(db.query('color == "blue" or "yellow"'));
// db.query('color == "blue" or "yellow"', true).sortCol("color",{ignoreCase:true}).dump();
// db.query('name == "Molly" or "Sandy" or "Lucy" or "Alice" && color == green', true).sortCol("num").dump();
// db.query('name == ^.$', true).dump();
// db.query('name == "Jeff the red" or "Sandy" or "Lucy" or "Alice" || color == red || num == 300', true).dump();
// db.sortCol("name",{ignoreCase:true}).dump();
// db.sortCol("num",{reverse:true}).dump();
// db.query('name == ^.$', true).dump();
// var color = "blue";
// var color2 = "yellow";
// db.query(`color == "${color}" or "${color2}"`).sortCol("color").dump({exclude:["num"]});
// db.query(`name like matthew`).dump();
//db.query('color == .* || color == green || color == yellow', true).sortCol("color").dump();
//num <= 10 &&
db.query('num != null', true).dump();