-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.js
66 lines (58 loc) · 1.66 KB
/
convert.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
const getComparator = (key) => {
if (key === '>') {
return (a,b) => a > b ? 1 : (a === b ? 0 : -1)
}
if (key === '<') {
return (a,b) => a < b ? 1 : (a === b ? 0 : -1)
}
}
const convert = (data, rule, {parent} = {}) => {
console.log('before convert')
console.dir(data, {depth: 4})
const result = {}
if (rule.from) {
result.src = data[rule.from]
} else {
result.src = data
}
if (rule.to === 'array') {
rule.to = Object.values
}
if (typeof rule.to === 'function') {
result.dst = rule.to(result.src)
}
if (typeof rule.mapTo === 'function') {
const mapFn = rule.mapTo
result.dst = result.dst.map((el, idx) => mapFn(parent, el,idx, convert))
} else if (Array.isArray(rule.mapTo)) {
const mapFn = (el, idx) => rule.mapTo.reduce((acc, mapRule) => {
Object.assign(acc, convert(el, mapRule, {parent: Array.isArray(parent) ? [el, ...parent] : [el]}))
return acc
}, {})
result.dst = result.dst.map(mapFn)
}
if (typeof rule.sort === 'object' && rule.sort.key && ['function', 'string'].includes(typeof(rule.sort.compare))) {
let {compare, key} = rule.sort
if (typeof compare === 'string') {
compare = getComparator(compare)
}
rule.sort = (a, b) => {
if (a === undefined || b === undefined) {
console.error({a,b})
throw new Error('a or b undefined. error sort function')
}
return compare(a[key], b[key])
}
}
if (typeof rule.sort === 'function' && Array.isArray(result.dst)) {
result.dst = result.dst.sort(rule.sort)
}
if (rule.from) {
data[rule.from] = result.dst
}
return result.dst
}
module.exports = {
getComparator,
convert,
}