-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1-record.js
61 lines (53 loc) · 1.66 KB
/
1-record.js
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
59
60
61
'use strict';
class Record {
static immutable(fields) {
return Record.#build(fields, false);
}
static mutable(fields) {
return Record.#build(fields, true);
}
static #build(fields, isMutable) {
class Struct {
static fields = fields.slice();
static mutable = isMutable;
static create(...values) {
if (fields.length !== values.length) {
throw new Error('Record arity mismatch');
}
const obj = Object.create(null);
for (let i = 0; i < fields.length; i++) {
obj[fields[i]] = values[i];
}
return isMutable ? Object.seal(obj) : Object.freeze(obj);
}
}
return Struct;
}
static update(instance, updates) {
if (Object.isFrozen(instance)) {
throw new Error('Cannot mutate immutable Record');
}
for (const key of Object.keys(updates)) {
if (Reflect.has(instance, key)) {
instance[key] = updates[key];
}
}
return instance;
}
static fork(instance, updates) {
const copy = Object.create(null);
for (const key of Object.keys(instance)) {
copy[key] = Reflect.has(updates, key) ? updates[key] : instance[key];
}
return Object.isFrozen(instance) ? Object.freeze(copy) : Object.seal(copy);
}
}
// Usage
const City = Record.immutable(['name']);
const User = Record.mutable(['id', 'name', 'city', 'email']);
const rome = City.create('Rome');
Record.update(marcus, { name: 'Marcus Aurelius' });
const lucius = Record.fork(marcus, { name: 'Lucius Verus' });
console.log({ marcus, lucius });