-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path7-class.js
More file actions
43 lines (36 loc) · 903 Bytes
/
7-class.js
File metadata and controls
43 lines (36 loc) · 903 Bytes
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
'use strict';
const Lens = class {
constructor(source, destination = source) {
this.source = source;
this.destination = destination;
}
static from(source, destination) {
return new Lens(source, destination);
}
get(obj) {
return obj[this.source];
}
set(val, obj) {
return { ...obj, [this.destination]: val };
}
static view(lens, obj) {
return lens.get(obj);
}
static set(lens, val, obj) {
return lens.set(val, obj);
}
static over(lens, map, obj) {
return lens.set(map(lens.get(obj)), obj);
}
};
// Usage
const person = {
name: 'Marcus Aurelius',
city: 'Rome',
born: 121,
};
const nameLens = Lens.from('name');
console.log('view name:', Lens.view(nameLens, person));
console.log('set name:', Lens.set(nameLens, 'Marcus', person));
const upper = (s) => s.toUpperCase();
console.log('over name:', Lens.over(nameLens, upper, person));