Skip to content

Commit 3a30d10

Browse files
committed
Add object reflection: omap
1 parent 48b4396 commit 3a30d10

File tree

1 file changed

+34
-3
lines changed

1 file changed

+34
-3
lines changed

JavaScript/5-instance.js

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,12 @@
44

55
// Imperative
66

7-
const marcus = {
7+
const marcus1 = {
88
name: 'Marcus Aurelius',
99
born: 121,
10+
upperName() {
11+
this.name = this.name.toUpperCase();
12+
},
1013
get era() {
1114
return this.born < 0 ? 'BC' : 'AD';
1215
},
@@ -15,13 +18,41 @@ const marcus = {
1518
},
1619
};
1720

18-
console.log(`${marcus}`);
21+
marcus1.name += ' Antoninus';
22+
marcus1.city = 'Roma';
23+
marcus1.position = 'emperor';
24+
marcus1.upperName();
25+
console.log(`Era of ${marcus1.name} birth is ${marcus1.era}`);
26+
console.log(`${marcus1}`);
27+
const keys = Object.keys(marcus1);
28+
console.log('Fields:', keys.join(', '));
1929

2030
// Functional
2131

2232
const era = year => (year < 0 ? 'BC' : 'AD');
2333
const person = (name, born) => () => `${name} was born in ${born} ${era(born)}`;
2434

2535
const marcus2 = person('Marcus Aurelius', 121, 'Roma');
26-
2736
console.log(marcus2());
37+
38+
// Object reflection
39+
40+
const omap = (obj, fn) => Object.keys(obj)
41+
.reduce((res, key) => {
42+
const [prop, val] = fn(key, obj[key]);
43+
res[prop] = val;
44+
return res;
45+
}, {});
46+
47+
const marcus3 = {
48+
firstName: 'Marcus',
49+
middleName: 'Aurelius',
50+
lastName: 'Antoninus',
51+
};
52+
53+
const marcus4 = omap(marcus3, (key, val) => {
54+
const prop = key.toLowerCase().replace('name', '');
55+
const value = val.toUpperCase();
56+
return [prop, value];
57+
});
58+
console.log(marcus4);

0 commit comments

Comments
 (0)