Skip to content

Commit 26b07b8

Browse files
committed
Add lense example
1 parent 955e665 commit 26b07b8

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

JavaScript/5-lense.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
'use strict';
2+
3+
// Lens
4+
5+
const view = (lens, obj) => lens.get(obj);
6+
7+
const lens = (source, destination = source) => ({
8+
get: obj => obj[source],
9+
set: (val, obj) => ({ ...obj, [destination]: val })
10+
});
11+
12+
const id = x => x;
13+
14+
const field = (name, map = id) => obj => map(view(lens(name), obj));
15+
16+
// Projection
17+
18+
const projection = meta => {
19+
const keys = Object.keys(meta);
20+
return obj => {
21+
const hash = {};
22+
keys.forEach(key => {
23+
const field = meta[key];
24+
hash[key] = field(obj);
25+
});
26+
return hash;
27+
};
28+
};
29+
30+
// Dataset
31+
32+
const persons = [
33+
{ name: 'Marcus Aurelius', city: 'Rome', born: 121 },
34+
{ name: 'Victor Glushkov', city: 'Rostov on Don', born: 1923 },
35+
{ name: 'Ibn Arabi', city: 'Murcia', born: 1165 },
36+
{ name: 'Mao Zedong', city: 'Shaoshan', born: 1893 },
37+
{ name: 'Rene Descartes', city: 'La Haye en Touraine', born: 1596 },
38+
];
39+
40+
// Metadata
41+
42+
const age = year =>
43+
new Date().getFullYear() -
44+
new Date(year + '').getFullYear();
45+
46+
const upper = s => s.toUpperCase();
47+
48+
const md = {
49+
name: field('name'),
50+
place: field('city', upper),
51+
age: field('born', age)
52+
};
53+
54+
// Usage
55+
56+
const p1 = projection(md);
57+
const data = persons.map(p1);
58+
console.dir(data);

0 commit comments

Comments
 (0)