-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjects.js
More file actions
58 lines (49 loc) · 1.5 KB
/
objects.js
File metadata and controls
58 lines (49 loc) · 1.5 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";
// numeric for loop without curly braces
const range = (length) => Array(length).fill().map((_, i) => i);
// object literal without curly braces
const obj = (...items) => Object.fromEntries(
range(items.length / 2).map(i => [items[2*i], items[2*i + 1]])
);
// trap object inside closure to create local scope
const withMy = (fn) => (...args) => fn(obj(), ...args);
// for convenience: iterate over object values
const objectMap = (o, fn) => Object.fromEntries(Object.entries(o).map(
([k, v]) => [k, fn(v)]
));
// tada!
const main = withMy((my) => (
my.items = obj(
'one', 1,
'two', 2,
'three', 3,
'four', 4,
'five', 5
),
my.fizzbuzz = (n) => (
n % 15 == 0 ? 'fizzbuzz' :
n % 3 == 0 ? 'fizz' :
n % 5 == 0 ? 'buzz' :
n
),
objectMap(my.items, my.fizzbuzz)
));
console.log(main());
// -> { one: 1, two: 2, three: 'fizz', four: 4, five: 'buzz' }
// bonus round: error catching without curly braces!
(Promise.resolve()
.then(() => console.log(my))
.catch((err) => console.log(err.message))
);
// -> my is not defined
// sanity check: these are really creating new objects every time.
const obj1 = withMy((my) => (my.sharedKey = 'i love javascript', my))();
const obj2 = withMy((my) => (my.sharedKey = 'i have mixed-to-neutral feelings about it, honestly', my))();
console.log(obj(
'obj1', obj1,
'obj2', obj2,
));
// -> {
// obj1: { sharedKey: 'i love javascript' },
// obj2: { sharedKey: 'i have mixed-to-neutral feelings about it, honestly' }
// }