-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path3-sum.js
86 lines (70 loc) · 1.62 KB
/
3-sum.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
'use strict';
class Sum {
static create(shape) {
const keys = Object.keys(shape);
if (keys.length !== 1) {
throw new Error('Sum.create expects a single root tag');
}
const tag = keys[0];
const variants = shape[tag];
const names = Object.keys(variants);
return class Struct {
static tag = tag;
static variants = names;
constructor(...args) {
return Struct.create(...args);
}
static create(value) {
for (let i = 0; i < names.length; i++) {
const variant = names[i];
const VariantClass = variants[variant];
if (VariantClass.is(value)) {
return new VariantClass(value);
}
}
throw new Error('No matching variant for value');
}
};
}
}
// Usage
class Integer {
constructor(value) {
this.value = value;
}
static is(value) {
return typeof value === 'number' && Number.isInteger(value);
}
}
class Bool {
constructor(value) {
this.value = value;
}
static is(value) {
return typeof value === 'boolean';
}
}
class Some {
constructor(value) {
this.value = value;
}
static is(value) {
return typeof value !== 'undefined';
}
}
class None {
static #instance;
constructor() {
if (None.#instance) return None.#instance;
None.#instance = this;
}
static is(value) {
return typeof value === 'undefined';
}
}
const Option = Sum.create({ Option: { Integer, Bool, Some, None } });
const a = Option.create(42);
const b = Option.create(false);
const c = Option.create('Hello');
const d = Option.create();
console.log({ a, b, c, d });