Skip to content

Commit dc0b44a

Browse files
committed
Refactor imperative to pure functional
1 parent a8587e2 commit dc0b44a

File tree

2 files changed

+11
-11
lines changed

2 files changed

+11
-11
lines changed

JavaScript/6-mapping.js

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -21,22 +21,20 @@ console.log(marcus2);
2121

2222
// Functional
2323

24+
const inst = (prev, prop, val) => ({ ...prev, [prop]: val });
25+
2426
const omap = (obj, fn) => Object.keys(obj)
25-
.reduce((res, key) => {
26-
const [prop, val] = fn(key, obj[key]);
27-
res[prop] = val;
28-
return res;
29-
}, {});
27+
.reduce((prev, key) => inst(prev, ...fn(key, obj[key])), {});
3028

3129
const marcus3 = {
3230
firstName: 'Marcus',
3331
middleName: 'Aurelius',
3432
lastName: 'Antoninus',
3533
};
3634

37-
const marcus4 = omap(marcus3, (key, val) => {
38-
const prop = key.toLowerCase().replace('name', '');
39-
const value = val.toUpperCase();
40-
return [prop, value];
41-
});
35+
const marcus4 = omap(marcus3, (key, val) => [
36+
key.toLowerCase().replace('name', ''),
37+
val.toUpperCase()
38+
]);
39+
4240
console.log(marcus4);

JavaScript/7-chaining.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,13 @@ console.log('Sum:', +sum1);
2222

2323
const adder = initial => Object.assign(
2424
value => adder(initial + value),
25-
{ valueOf: () => initial }
25+
{ valueOf: () => initial,
26+
map: log => log(initial) }
2627
);
2728

2829
const sum2 = adder(1)(9)(1)(7);
2930
console.log('Sum:', +sum2);
31+
sum2.map(console.log);
3032

3133
// Functional methods
3234

0 commit comments

Comments
 (0)