-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphp-query-builder.js
More file actions
63 lines (59 loc) · 1.58 KB
/
Copy pathphp-query-builder.js
File metadata and controls
63 lines (59 loc) · 1.58 KB
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
function isSeqArray(entries) {
let i = 0;
for(const e of entries) {
if(e[0] !== String(i++)) { return false; }
}
return true;
}
function* keyValStr(key, value) {
if(value === null) { yield key; return; }
switch(typeof value) {
case 'string': {
yield `${key}=${encodeURIComponent(value)}`; return;
}
case 'boolean':
case 'number':
case 'bigint': {
yield `${key}=${encodeURIComponent(String(value))}`; return;
}
case 'object': {
const entries = Object.entries(value);
if(Array.isArray(value) && isSeqArray(entries)) {
const kArr = key + encodeURIComponent('[]');
for(const [k, v] of entries) {
yield* keyValStr(kArr, v);
}
} else {
for(const [k, v] of entries) {
yield* keyValStr(key + encodeURIComponent(`[${k}]`), v);
}
}
return;
}
case 'undefined': { yield key; return; }
// case 'symbol': return; // No output
// case 'function': { return; } // Already handled
}
}
function* genItems(data) {
const entries = Object.entries(data);
if(entries.length === 0) { yield ''; return; }
for(const [key, value] of entries) {
const eKey = encodeURIComponent(key);
if(typeof value === 'function') {
try {
yield* keyValStr(eKey, value.apply(data));
} catch (error) {}
} else {
yield* keyValStr(eKey, value);
}
}
}
function PHPQueryBuilder(data) {
if(typeof data !== 'object') {
throw new TypeError('Expected a object|null as a parameter');
}
if(data === null) { return ''; }
return Array.from(genItems(data)).join('&');
}
export default PHPQueryBuilder;