-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path5-lense.js
More file actions
58 lines (43 loc) · 1.18 KB
/
5-lense.js
File metadata and controls
58 lines (43 loc) · 1.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
'use strict';
// Lens
const view = (lens, obj) => lens.get(obj);
const lens = (source, destination = source) => ({
get: (obj) => obj[source],
set: (val, obj) => ({ ...obj, [destination]: val })
});
const id = (x) => x;
const field = (name, map = id) => (obj) => map(view(lens(name), obj));
// Projection
const projection = (meta) => {
const keys = Object.keys(meta);
return (obj) => {
const hash = {};
keys.forEach((key) => {
const field = meta[key];
hash[key] = field(obj);
});
return hash;
};
};
// Dataset
const persons = [
{ name: 'Marcus Aurelius', city: 'Rome', born: 121 },
{ name: 'Victor Glushkov', city: 'Rostov on Don', born: 1923 },
{ name: 'Ibn Arabi', city: 'Murcia', born: 1165 },
{ name: 'Mao Zedong', city: 'Shaoshan', born: 1893 },
{ name: 'Rene Descartes', city: 'La Haye en Touraine', born: 1596 },
];
// Metadata
const age = (year) =>
new Date().getFullYear() -
new Date(year.toString()).getFullYear();
const upper = (s) => s.toUpperCase();
const md = {
name: field('name'),
place: field('city', upper),
age: field('born', age)
};
// Usage
const p1 = projection(md);
const data = persons.map(p1);
console.dir(data);