|
2 | 2 |
|
3 | 3 | // Projection |
4 | 4 |
|
5 | | -const transforms = { |
6 | | - string: name => d => d[name], |
7 | | - function: fn => d => fn(d), |
8 | | - object: name => proj => d => { |
9 | | - const data = d[name]; |
10 | | - if (!data) return data; |
11 | | - return data.map(projection(proj)); |
12 | | - } |
13 | | -}; |
14 | | - |
15 | 5 | const projection = (metadata) => { |
16 | 6 | const meta = {}; |
17 | | - let item, key, type, transform; |
| 7 | + let item, key, type, cast; |
18 | 8 | for (item of metadata) { |
19 | 9 | type = typeof(item); |
20 | | - transform = transforms[type]; |
| 10 | + cast = projection[type]; |
21 | 11 | if (type === 'string') key = item; |
22 | | - if (type === 'object') transform = transform(key); |
23 | | - meta[key] = transform(item); |
| 12 | + if (type === 'object') cast = cast(key); |
| 13 | + meta[key] = cast(item); |
24 | 14 | } |
25 | 15 | const keys = Object.keys(meta); |
26 | 16 | const mapper = obj => { |
27 | 17 | const hash = {}; |
28 | | - let key, value, transform; |
| 18 | + let key, value, cast; |
29 | 19 | for (key of keys) { |
30 | | - transform = meta[key]; |
31 | | - value = transform(obj); |
| 20 | + cast = meta[key]; |
| 21 | + value = cast(obj); |
32 | 22 | if (value) hash[key] = value; |
33 | 23 | } |
34 | 24 | return hash; |
35 | 25 | }; |
36 | 26 | return mapper; |
37 | 27 | }; |
38 | 28 |
|
| 29 | +projection.string = name => d => d[name]; |
| 30 | +projection.function = fn => d => fn(d); |
| 31 | +projection.object = name => proj => d => { |
| 32 | + const data = d[name]; |
| 33 | + if (!data) return data; |
| 34 | + return data.map(projection(proj)); |
| 35 | +}; |
| 36 | + |
39 | 37 | // Dataset |
40 | 38 |
|
41 | 39 | const persons = [ |
@@ -64,16 +62,16 @@ const persons = [ |
64 | 62 |
|
65 | 63 | const md = [ |
66 | 64 | 'name', |
67 | | - 'places', [ |
68 | | - 'address', d => (d.country.toUpperCase() + ', '+ d.name), |
69 | | - 'population' |
70 | | - ], |
71 | 65 | 'place', d => '<' + d.city.toUpperCase() + '>', |
72 | 66 | 'born', |
73 | 67 | 'age', d => ( |
74 | 68 | new Date().getFullYear() - |
75 | 69 | new Date(d.born + '').getFullYear() |
76 | | - ) |
| 70 | + ), |
| 71 | + 'places', [ |
| 72 | + 'address', d => (d.country.toUpperCase() + ', ' + d.name), |
| 73 | + 'population' |
| 74 | + ] |
77 | 75 | ]; |
78 | 76 |
|
79 | 77 | // Usage |
|
0 commit comments