forked from gcanti/tcomb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
720 lines (596 loc) · 18.7 KB
/
index.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
(function (root, factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.t = factory();
}
}(this, function () {
'use strict';
function fail(message) {
// start debugger only once
if (!fail.failed) {
/*jshint debug: true*/
debugger;
}
fail.failed = true;
throw new TypeError(message);
}
function assert(guard, message) {
if (guard !== true) {
message = message ? format.apply(null, slice.call(arguments, 1)) : 'assert failed';
exports.fail(message);
}
}
//
// utils
//
var slice = Array.prototype.slice;
function mixin(target, source, overwrite) {
if (Nil.is(source)) { return target; }
for (var k in source) {
if (source.hasOwnProperty(k)) {
if (overwrite !== true) {
assert(!target.hasOwnProperty(k), 'Cannot overwrite property %s', k);
}
target[k] = source[k];
}
}
return target;
}
function format() {
var args = slice.call(arguments);
var len = args.length;
var i = 1;
var message = args[0];
function formatArgument(match, type) {
if (match === '%%') { return '%'; } // handle escaping %
if (i >= len) { return match; } // handle less arguments than placeholders
var formatter = format.formatters[type];
if (!formatter) { return match; } // handle undefined formatters
return formatter(args[i++]);
}
var str = message.replace(/%([a-z%])/g, formatArgument);
if (i < len) {
str += ' ' + args.slice(i).join(' '); // handle more arguments than placeholders
}
return str;
}
function getFunctionName(f) {
assert(typeof f === 'function', 'Invalid argument `f` = `%s` supplied to `getFunctionName()`', f);
return f.displayName || f.name || format('<function%s>', f.length);
}
function replacer(key, value) {
return Func.is(value) ? getFunctionName(value) : value;
}
format.formatters = {
s: function (x) { return String(x); },
j: function (x) {
try { // handle circular references
return JSON.stringify(x, replacer);
} catch (e) {
return String(x);
}
}
};
function getTypeName(type) {
assert(Type.is(type), 'Invalid argument `type` = `%s` supplied to `getTypeName()`', type);
return type.meta.name;
}
function blockNew(x, type) {
assert(!(x instanceof type), 'Operator `new` is forbidden for type `%s`', getTypeName(type));
}
function shallowCopy(x) {
return Arr.is(x) ? x.concat() : Obj.is(x) ? mixin({}, x) : x;
}
function update(instance, spec) {
assert(Obj.is(spec));
var value = shallowCopy(instance);
for (var k in spec) {
if (spec.hasOwnProperty(k)) {
if (update.commands.hasOwnProperty(k)) {
assert(Object.keys(spec).length === 1);
return update.commands[k](spec[k], value);
} else {
value[k] = update(value[k], spec[k]);
}
}
}
return value;
}
update.commands = {
'$apply': function (f, value) {
assert(Func.is(f));
return f(value);
},
'$push': function (elements, arr) {
assert(Arr.is(elements));
assert(Arr.is(arr));
return arr.concat(elements);
},
'$remove': function (keys, obj) {
assert(Arr.is(keys));
assert(Obj.is(obj));
for (var i = 0, len = keys.length ; i < len ; i++ ) {
delete obj[keys[i]];
}
return obj;
},
'$set': function (value) {
return value;
},
'$splice': function (splices, arr) {
assert(list(Arr).is(splices));
assert(Arr.is(arr));
return splices.reduce(function (acc, splice) {
acc.splice.apply(acc, splice);
return acc;
}, arr);
},
'$swap': function (config, arr) {
assert(Obj.is(config));
assert(Num.is(config.from));
assert(Num.is(config.to));
assert(Arr.is(arr));
var element = arr[config.to];
arr[config.to] = arr[config.from];
arr[config.from] = element;
return arr;
},
'$unshift': function (elements, arr) {
assert(Arr.is(elements));
assert(Arr.is(arr));
return elements.concat(arr);
},
'$merge': function (obj, value) {
return mixin(mixin({}, value), obj, true);
}
};
//
// irreducibles
//
function irreducible(name, is) {
assert(typeof name === 'string', 'Invalid argument `name` supplied to `irreducible()`');
assert(typeof is === 'function', 'Invalid argument `is` supplied to `irreducible()`');
function Irreducible(value, mut, key) {
blockNew(this, Irreducible);
assert(is(value), 'Invalid value supplied to `%s` for property `%s`', name, key);
return value;
}
Irreducible.meta = {
kind: 'irreducible',
name: name
};
Irreducible.displayName = name;
Irreducible.is = is;
return Irreducible;
}
var Any = irreducible('Any', function isAny() {
return true;
});
var Nil = irreducible('Nil', function isNil(x) {
return x === null || x === void 0;
});
var Str = irreducible('Str', function isStr(x) {
return typeof x === 'string';
});
var Num = irreducible('Num', function isNum(x) {
return typeof x === 'number' && isFinite(x) && !isNaN(x);
});
var Bool = irreducible('Bool', function isBool(x) {
return x === true || x === false;
});
var Arr = irreducible('Arr', function isArr(x) {
return x instanceof Array;
});
var Obj = irreducible('Obj', function isObj(x) {
return !Nil.is(x) && typeof x === 'object' && !Arr.is(x);
});
var Func = irreducible('Func', function isFunc(x) {
return typeof x === 'function';
});
var Err = irreducible('Err', function isErr(x) {
return x instanceof Error;
});
var Re = irreducible('Re', function isRe(x) {
return x instanceof RegExp;
});
var Dat = irreducible('Dat', function isDat(x) {
return x instanceof Date;
});
var Type = irreducible('Type', function isType(x) {
return Func.is(x) && Obj.is(x.meta);
});
function struct(props, name) {
assert(dict(Str, Type).is(props), 'Invalid argument `props` = `%s` supplied to `struct` combinator', props);
assert(maybe(Str).is(name), 'Invalid argument `name` = `%s` supplied to `struct` combinator', name);
name = name || format('{%s}', Object.keys(props).map(function (prop) {
return format('%s: %s', prop, getTypeName(props[prop]));
}).join(', '));
function Struct(value, mut) {
// makes Struct idempotent
if (Struct.is(value)) {
return value;
}
assert(Obj.is(value), 'Invalid argument `value` = `%s` supplied to struct type `%s`', value, name);
// makes `new` optional
if (!(this instanceof Struct)) {
return new Struct(value, mut);
}
for (var k in props) {
if (props.hasOwnProperty(k)) {
var expected = props[k];
var actual = value[k];
this[k] = expected(actual, mut, k);
}
}
if (mut !== true) {
Object.freeze(this);
}
}
Struct.meta = {
kind: 'struct',
props: props,
name: name
};
Struct.displayName = name;
Struct.is = function (x) {
return x instanceof Struct;
};
Struct.update = function (instance, spec) {
return new Struct(exports.update(instance, spec));
};
Struct.extend = function (arr, name) {
arr = [].concat(arr).map(function (x) {
return Obj.is(x) ? x : x.meta.props;
});
arr.unshift(props);
var ret = struct(arr.reduce(mixin, {}), name);
mixin(ret.prototype, Struct.prototype); // prototypal inheritance
return ret;
};
return Struct;
}
function union(types, name) {
assert(list(Type).is(types), 'Invalid argument `types` = `%s` supplied to `union` combinator', types);
var len = types.length;
var defaultName = types.map(getTypeName).join(' | ');
assert(len >= 2, 'Invalid argument `types` = `%s` supplied to `union` combinator, provide at least two types', defaultName);
assert(maybe(Str).is(name), 'Invalid argument `name` = `%s` supplied to `union` combinator', name);
name = name || defaultName;
function Union(value, mut) {
blockNew(this, Union);
assert(Func.is(Union.dispatch), 'Unimplemented `dispatch()` function for union type `%s`', name);
var type = Union.dispatch(value);
assert(Type.is(type), 'The `dispatch()` function of union type `%s` returns no type constructor', name);
return type(value, mut, name);
}
Union.meta = {
kind: 'union',
types: types,
name: name
};
Union.displayName = name;
Union.is = function (x) {
return types.some(function (type) {
return type.is(x);
});
};
// default dispatch implementation
Union.dispatch = function (x) {
for (var i = 0 ; i < len ; i++ ) {
if (types[i].is(x)) {
return types[i];
}
}
};
return Union;
}
function maybe(type, name) {
assert(Type.is(type), 'Invalid argument `type` = `%s` supplied to `maybe` combinator', type);
// makes the combinator idempotent and handle Any, Nil
if (type.meta.kind === 'maybe' || type === Any || type === Nil) {
return type;
}
assert(Nil.is(name) || Str.is(name), 'Invalid argument `name` = `%s` supplied to `maybe` combinator', name);
name = name || ('?' + getTypeName(type));
function Maybe(value, mut, key) {
blockNew(this, Maybe);
return Nil.is(value) ? null : type(value, mut, key);
}
Maybe.meta = {
kind: 'maybe',
type: type,
name: name
};
Maybe.displayName = name;
Maybe.is = function (x) {
return Nil.is(x) || type.is(x);
};
return Maybe;
}
function enums(map, name) {
assert(Obj.is(map), 'Invalid argument `map` = `%s` supplied to `enums` combinator', map);
assert(maybe(Str).is(name), 'Invalid argument `name` = `%s` supplied to `enums` combinator', name);
var keys = Object.keys(map); // cache enums
name = name || keys.map(function (k) { return JSON.stringify(k); }).join(' | ');
function Enums(value, mut, key) {
blockNew(this, Enums);
assert(Enums.is(value), 'Invalid value supplied to property `%s` for enum type `%s`, expected one of %j', key, name, keys);
return value;
}
Enums.meta = {
kind: 'enums',
map: map,
name: name
};
Enums.displayName = name;
Enums.is = function (x) {
return Str.is(x) && map.hasOwnProperty(x);
};
return Enums;
}
enums.of = function (keys, name) {
keys = Str.is(keys) ? keys.split(' ') : keys;
var value = {};
keys.forEach(function (k) {
value[k] = k;
});
return enums(value, name);
};
function tuple(types, name) {
assert(list(Type).is(types), 'Invalid argument `types` = `%s` supplied to `tuple` combinator', types);
var len = types.length; // cache types length
assert(maybe(Str).is(name), 'Invalid argument `name` = `%s` supplied to `tuple` combinator', name);
name = name || format('[%s]', types.map(getTypeName).join(', '));
function isTuple(x) {
return types.every(function (type, i) {
return type.is(x[i]);
});
}
function Tuple(value, mut) {
assert(Arr.is(value) && value.length === len, 'Invalid argument `value` = `%s` supplied to tuple type `%s`, expected an `Arr` of length `%s`', value, name, len);
var frozen = (mut !== true);
// makes Tuple idempotent
if (isTuple(value) && Object.isFrozen(value) === frozen) {
return value;
}
var arr = [];
for (var i = 0 ; i < len ; i++) {
var expected = types[i];
var actual = value[i];
arr.push(expected(actual, mut));
}
if (frozen) {
Object.freeze(arr);
}
return arr;
}
Tuple.meta = {
kind: 'tuple',
types: types,
length: len,
name: name
};
Tuple.displayName = name;
Tuple.is = function (x) {
return Arr.is(x) && x.length === len && isTuple(x);
};
Tuple.update = function (instance, spec) {
return Tuple(exports.update(instance, spec));
};
return Tuple;
}
function subtype(type, predicate, name) {
assert(Type.is(type), 'Invalid argument `type` = `%s` supplied to `subtype` combinator', type);
assert(Func.is(predicate), 'Invalid argument `predicate` = `%s` supplied to `subtype` combinator', predicate);
assert(maybe(Str).is(name), 'Invalid argument `name` = `%s` supplied to `subtype` combinator', name);
name = name || format('{%s | %s}', getTypeName(type), getFunctionName(predicate));
function Subtype(value, mut, key) {
blockNew(this, Subtype);
var x = type(value, mut, key);
assert(predicate(x), 'Invalid value supplied to `%s`, for property `%s`', name, key);
return x;
}
Subtype.meta = {
kind: 'subtype',
type: type,
predicate: predicate,
name: name
};
Subtype.displayName = name;
Subtype.is = function (x) {
return type.is(x) && predicate(x);
};
Subtype.update = function (instance, spec) {
return Subtype(exports.update(instance, spec));
};
return Subtype;
}
function list(type, name) {
assert(Type.is(type), 'Invalid argument `type` = `%s` supplied to `list` combinator', type);
assert(maybe(Str).is(name), 'Invalid argument `name` = `%s` supplied to `list` combinator', name);
name = name || format('Array<%s>', getTypeName(type));
function isList(x) {
return x.every(type.is);
}
function List(value, mut) {
assert(Arr.is(value), 'Invalid argument `value` = `%s` supplied to list type `%s`', value, name);
var frozen = (mut !== true);
// makes List idempotent
if (isList(value) && Object.isFrozen(value) === frozen) {
return value;
}
var arr = [];
for (var i = 0, len = value.length ; i < len ; i++ ) {
var actual = value[i];
arr.push(type(actual, mut));
}
if (frozen) {
Object.freeze(arr);
}
return arr;
}
List.meta = {
kind: 'list',
type: type,
name: name
};
List.displayName = name;
List.is = function (x) {
return Arr.is(x) && isList(x);
};
List.update = function (instance, spec) {
return List(exports.update(instance, spec));
};
return List;
}
function dict(domain, codomain, name) {
assert(Type.is(domain), 'Invalid argument `domain` = `%s` supplied to `dict` combinator', domain);
assert(Type.is(codomain), 'Invalid argument `codomain` = `%s` supplied to `dict` combinator', codomain);
assert(maybe(Str).is(name), 'Invalid argument `name` = `%s` supplied to `dict` combinator', name);
name = name || format('{[key:%s]: %s}', getTypeName(domain), getTypeName(codomain));
function isDict(x) {
for (var k in x) {
if (x.hasOwnProperty(k)) {
if (!domain.is(k) || !codomain.is(x[k])) { return false; }
}
}
return true;
}
function Dict(value, mut) {
assert(Obj.is(value), 'Invalid argument `value` = `%s` supplied to dict type `%s`', value, name);
var frozen = (mut !== true);
// makes Dict idempotent
if (isDict(value) && Object.isFrozen(value) === frozen) {
return value;
}
var obj = {};
for (var k in value) {
if (value.hasOwnProperty(k)) {
k = domain(k);
var actual = value[k];
obj[k] = codomain(actual, mut);
}
}
if (frozen) {
Object.freeze(obj);
}
return obj;
}
Dict.meta = {
kind: 'dict',
domain: domain,
codomain: codomain,
name: name
};
Dict.displayName = name;
Dict.is = function (x) {
return Obj.is(x) && isDict(x);
};
Dict.update = function (instance, spec) {
return Dict(exports.update(instance, spec));
};
return Dict;
}
function isInstrumented(f) {
return Func.is(f) && Obj.is(f.type);
}
function func(domain, codomain, name) {
// handle handy syntax for unary functions
domain = Arr.is(domain) ? domain : [domain];
assert(list(Type).is(domain), 'Invalid argument `domain` = `%s` supplied to `func` combinator', domain);
assert(Type.is(codomain), 'Invalid argument `codomain` = `%s` supplied to `func` combinator', codomain);
assert(maybe(Str).is(name), 'Invalid argument `name` = `%s` supplied to `func` combinator', name);
name = name || format('(%s) => %s', domain.map(getTypeName).join(', '), getTypeName(codomain));
var domainLen = domain.length; // cache the domain length
function Func(value) {
// automatically instrument the function
if (!isInstrumented(value)) {
return Func.of(value);
}
assert(Func.is(value), 'Invalid argument `value` = `%s` supplied to func type `%s`', value, name);
return value;
}
Func.meta = {
kind: 'func',
domain: domain,
codomain: codomain,
name: name
};
Func.displayName = name;
Func.is = function (x) {
return isInstrumented(x) &&
x.type.domain.length === domainLen &&
x.type.domain.every(function (type, i) {
return type === domain[i];
}) &&
x.type.codomain === codomain;
};
Func.of = function (f) {
assert(typeof f === 'function');
// makes Func.of idempotent
if (Func.is(f)) {
return f;
}
function fn() {
var args = slice.call(arguments);
var len = args.length;
var argsType = tuple(domain.slice(0, len));
args = argsType(args);
if (len === domainLen) {
/* jshint validthis: true */
return codomain(f.apply(this, args));
} else {
var curried = Function.prototype.bind.apply(f, [this].concat(args));
var newdomain = func(domain.slice(len), codomain);
return newdomain.of(curried);
}
}
fn.type = {
domain: domain,
codomain: codomain,
f: f
};
fn.displayName = getFunctionName(f);
return fn;
};
return Func;
}
var exports = {
format: format,
getFunctionName: getFunctionName,
getTypeName: getTypeName,
mixin: mixin,
slice: slice,
shallowCopy: shallowCopy,
update: update,
assert: assert,
fail: fail,
Any: Any,
Nil: Nil,
Str: Str,
Num: Num,
Bool: Bool,
Arr: Arr,
Obj: Obj,
Func: Func,
Err: Err,
Re: Re,
Dat: Dat,
Type: Type,
irreducible: irreducible,
struct: struct,
enums: enums,
union: union,
maybe: maybe,
tuple: tuple,
subtype: subtype,
list: list,
dict: dict,
func: func
};
return exports;
}));