-
Notifications
You must be signed in to change notification settings - Fork 14
/
typed.js
306 lines (259 loc) · 8.46 KB
/
typed.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import * as Immutable from 'immutable'
if (typeof(Symbol) === 'undefined') {
var Symbol = hint => `@@${hint}`
Symbol.for = Symbol
}
function Construct() {}
export const construct = value => {
Construct.prototype = value.constructor.prototype
return new Construct()
}
const $type = Symbol.for("typed/type")
const $store = Symbol.for("typed/store")
const $empty = Symbol.for("typed/empty")
const $maybe = Symbol.for("typed/type/maybe")
const $default = Symbol.for("typed/type/default")
const $label = Symbol.for("typed/type/label")
const $init = Symbol.for("transducer/init")
const $result = Symbol.for("transducer/result")
const $step = Symbol.for("transducer/step")
const $read = Symbol.for("typed/type/read")
const $parse = Symbol.for("typed/type/parse")
const $typeName = Symbol("typed/type/name")
const $typeSignature = Symbol("typed/type/signature")
export const Typed = function(label, parse, defaultValue) {
class ValueType extends Type {
constructor(defaultValue) {
super()
this[$default] = defaultValue
}
}
const prototype = ValueType.prototype
prototype[$default] = defaultValue
prototype[$parse] = parse
prototype[$label] = label
const TypedValue = function(defaultValue) {
return defaultValue === void(0) ? prototype :
new ValueType(defaultValue)
}
TypedValue.prototype = prototype
return TypedValue
}
Typed.label = $label
Typed.defaultValue = $default
Typed.read = $read
Typed.typeName = $typeName
Typed.typeSignature = $typeSignature
Typed.type = $type
Typed.store = $store
Typed.init = $init
Typed.result = $result
Typed.step = $step
Typed.DELETE = "delete"
Typed.empty = $empty
const typeName = type => type[$typeName]()
const typeSignature = type => type[$typeSignature]()
export class Type {
constructor() {}
[Typed.read](value=this[$default]) {
return this[$parse](value)
}
[Typed.parse](value) {
throw TypeError(`Type implementation must implement "[read.symbol]" method`)
}
[Typed.typeName]() {
const label = this[$label]
const defaultValue = this[$default]
return defaultValue === void(0) ? label : `${label}(${JSON.stringify(defaultValue)})`
}
}
const ObjectPrototype = Object.prototype
// Returns `true` if given `x` is a JS array.
const isArray = Array.isArray ||
(x => ObjectPrototype.toString.call(x) === '[object Array]')
// Returns `true` if given `x` is a regular expression.
const isRegExp = x =>
ObjectPrototype.toString.call(x) === '[object RegExp]'
export const typeOf = (x, type=typeof(x)) =>
x === void(0) ? x :
x === null ? x :
x[$read] ? x :
(x.prototype && x.prototype[$read]) ? x.prototype :
type === "number" ? new Typed.Number(x) :
type === "string" ? new Typed.String(x) :
type === "boolean" ? new Typed.Boolean(x) :
type === "symbol" ? new Typed.Symbol(x) :
isArray(x) ? Typed.Array(x) :
isRegExp(x) ? new Typed.RegExp(x) :
x === String ? Typed.String.prototype :
x === Number ? Typed.Number.prototype :
x === Boolean ? Typed.Boolean.prototype :
x === RegExp ? Typed.RegExp.prototype :
x === Array ? Typed.Array.prototype :
x === Symbol ? Typed.Symbol.prototype :
x === Date ? Typed.Date.prototype :
Any;
export const Any = Typed("Any", value => value)()
Typed.Any = Any
Typed.Number = Typed("Number", value =>
typeof(value) === "number" ? value :
TypeError(`"${value}" is not a number`))
Typed.String = Typed("String", value =>
typeof(value) === "string" ? value :
TypeError(`"${value}" is not a string`))
Typed.Symbol = Typed("Symbol", value =>
typeof(value) === "symbol" ? value :
TypeError(`"${value}" is not a symbol`))
Typed.Array = Typed("Array", value =>
isArray(value) ? value :
TypeError(`"${value}" is not an array`))
Typed.RegExp = Typed("RegExp", value =>
value instanceof RegExp ? value :
TypeError(`"${value}" is not a regexp`))
Typed.Boolean = Typed("Boolean", value =>
value === true ? true :
value === false ? false :
TypeError(`"${value}" is not a boolean`))
Typed.Date = Typed("Date", value => {
var d = new Date(value)
if (isNaN(d.valueOf())) {
return new TypeError(`"${value}" is not a valid date.`)
}
return d
})
class MaybeType extends Type {
constructor(type) {
super()
this[$type] = type
}
[Typed.typeName]() {
return `Maybe(${this[$type][$typeName]()})`
}
[Typed.read](value) {
const result = value == null ? null : this[$type][$read](value)
return !(result instanceof TypeError) ? result :
TypeError(`"${value}" is not nully nor it is of ${this[$type][$typeName]()} type`)
}
}
export const Maybe = Type => {
const type = typeOf(Type)
if (type === Any) {
throw TypeError(`${Type} is not a valid type`)
}
return type[$maybe] || (type[$maybe] = new MaybeType(type))
}
Maybe.Type = MaybeType
class UnionType extends Type {
constructor(variants) {
super()
this[$type] = variants
}
[Typed.typeName]() {
return `Union(${this[$type].map(typeName).join(', ')})`
}
[Typed.read](value) {
const variants = this[$type]
const count = variants.length
let index = 0
while (index < count) {
const variant = variants[index]
if (value instanceof variant.constructor) {
return value
}
index = index + 1
}
index = 0
while (index < count) {
const result = variants[index][$read](value)
if (!(result instanceof TypeError)) {
return result
}
index = index + 1
}
return TypeError(`"${value}" does not satisfy ${this[$typeName]()} type`)
}
}
// Returns `xs` excluding any values that are included in `ys`.
const subtract = (xs, ys) =>
xs.filter(x => ys.indexOf(x) < 0)
// Returns array including all values from `xs` and all values from
// `ys` that aren't already included in `xs`. It will also attempt
// to return either `xs` or `ys` if one of them is a superset of other.
// return `xs` or `ys` if
const union = (xs, ys) => {
// xs can be superset only if it contains more items then
// ys. If that's a case find items in ys that arent included
// in xs. If such items do not exist return back `xs` otherwise
// return concatination of xs with those items.
// those items
if (xs.length > ys.length) {
const diff = subtract(ys, xs)
return diff.length === 0 ? xs : xs.concat(diff)
}
// if number of items in xs is not greater than number of items in ys
// then either xs is either subset or equal of `ys`. There for we find
// ys that are not included in `xs` if such items aren't found ys is
// either superset or equal so just return ys otherwise return concatination
// of those items with `ys`.
else {
const diff = subtract(xs, ys)
return diff.length === 0 ? ys : diff.concat(ys)
}
}
export const Union = (...Types) => {
const count = Types.length
if (count === 0) {
throw TypeError(`Union must be of at at least one type`)
}
let variants = null
let type = null
let index = 0;
while (index < count) {
const variant = typeOf(Types[index])
// If there is `Any` present than union is also `Any`.
if (variant === Any) {
return Any
}
// If this is the first type we met than we assume it's the
// one that satisfies all types.
if (!variants) {
type = variant
variants = type instanceof UnionType ? type[$type] : [variant]
} else if (variants.indexOf(variant) < 0) {
// If current reader is of union type
if (variant instanceof UnionType) {
const variantUnion = union(variants, variant[$type])
// If `reader.readers` matches union of readers, then
// current reader is a superset so we use it as a type
// that satisfies all types.
if (variantUnion === variant[$type]) {
type = variant
variants = variantUnion
}
// If current readers is not the union than it does not
// satisfy currenty reader. There for we update readers
// and unset a type.
else if (variantUnion !== variants) {
type = null
variants = variantUnion
}
} else {
type = null
variants.push(variant)
}
}
index = index + 1
}
return type ? type : new UnionType(variants)
}
Union.Type = UnionType
Typed.Number.Range = (from, to=+Infinity, defaultValue) =>
Typed(`Typed.Number.Range(${from}..${to})`, value => {
if (typeof(value) !== 'number') {
return TypeError(`"${value}" is not a number`)
}
if (!(value >= from && value <= to)) {
return TypeError(`"${value}" isn't in the range of ${from}..${to}`)
}
return value
}, defaultValue)