-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path8-syntax.js
More file actions
80 lines (71 loc) · 2.18 KB
/
8-syntax.js
File metadata and controls
80 lines (71 loc) · 2.18 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
'use strict';
// Projection
const projection = (metadata) => {
const meta = {};
let key;
for (const item of metadata) {
const type = typeof item;
let cast = projection[type];
if (type === 'string') key = item;
if (type === 'object') cast = cast(key);
meta[key] = cast(item);
}
const keys = Object.keys(meta);
const mapper = (obj) => {
const hash = {};
for (const key of keys) {
const cast = meta[key];
const value = cast(obj);
if (value) hash[key] = value;
}
return hash;
};
return mapper;
};
projection.string = (name) => (d) => d[name];
projection.function = (fn) => (d) => fn(d);
projection.object = (name) => (proj) => (d) => {
const data = d[name];
if (!data) return data;
return data.map(projection(proj));
};
// Dataset
const persons = [
{ name: 'Marcus Aurelius', city: 'Rome', born: 121, places: [
{ name: 'Shanghai', population: 24256800, country: 'China' },
{ name: 'Beijing', population: 21516000, country: 'China' },
{ name: 'Delhi', population: 16787941, country: 'India' }
] },
{ name: 'Victor Glushkov', city: 'Rostov on Don', born: 1923, places: [
{ name: 'Lagos', population: 16060303, country: 'Nigeria' },
{ name: 'Delhi', population: 16787941, country: 'India' },
{ name: 'Tianjin', population: 15200000, country: 'China' }
] },
{ name: 'Ibn Arabi', city: 'Murcia', born: 1165, places: [
{ name: 'Beijing', population: 21516000, country: 'China' },
] },
{ name: 'Mao Zedong', city: 'Shaoshan', born: 1893 },
{ name: 'Rene Descartes', city: 'La Haye en Touraine', born: 1596, places: [
{ name: 'Karachi', population: 14910352, country: 'Pakistan' },
{ name: 'Istanbul', population: 14160467, country: 'Turkey' },
{ name: 'Tianjin', population: 15200000, country: 'China' }
] },
];
// Metadata
const md = [
'name',
'place', (d) => `<${d.city.toUpperCase()}>`,
'born',
'age', (d) => (
new Date().getFullYear() -
new Date(d.born.toString()).getFullYear()
),
'places', [
'address', (d) => (d.country.toUpperCase() + ', ' + d.name),
'population'
]
];
// Usage
const p = projection(md);
const data = persons.map(p);
console.dir(data, { depth: 10 });