forked from gcanti/tcomb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.js
81 lines (64 loc) · 2.46 KB
/
list.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
var assert = require('./assert');
var isTypeName = require('./isTypeName');
var isFunction = require('./isFunction');
var getTypeName = require('./getTypeName');
var isIdentity = require('./isIdentity');
var create = require('./create');
var is = require('./is');
var isArray = require('./isArray');
function getDefaultName(type) {
return 'Array<' + getTypeName(type) + '>';
}
function list(type, name) {
if (process.env.NODE_ENV !== 'production') {
assert(isFunction(type), function () { return 'Invalid argument type ' + assert.stringify(type) + ' supplied to list(type, [name]) combinator (expected a type)'; });
assert(isTypeName(name), function () { return 'Invalid argument name ' + assert.stringify(name) + ' supplied to list(type, [name]) combinator (expected a string)'; });
}
var displayName = name || getDefaultName(type);
var typeNameCache = getTypeName(type);
var identity = isIdentity(type); // the list is identity iif type is identity
function List(value, path) {
if (process.env.NODE_ENV === 'production') {
if (identity) {
return value; // just trust the input if elements must not be hydrated
}
}
if (process.env.NODE_ENV !== 'production') {
path = path || [displayName];
assert(isArray(value), function () { return 'Invalid value ' + assert.stringify(value) + ' supplied to ' + path.join('/') + ' (expected an array of ' + typeNameCache + ')'; });
}
var idempotent = true; // will remain true if I can reutilise the input
var ret = []; // make a temporary copy, will be discarded if idempotent remains true
for (var i = 0, len = value.length; i < len; i++ ) {
var actual = value[i];
var instance = create(type, actual, ( process.env.NODE_ENV !== 'production' ? path.concat(i + ': ' + typeNameCache) : null ));
idempotent = idempotent && ( actual === instance );
ret.push(instance);
}
if (idempotent) { // implements idempotency
ret = value;
}
if (process.env.NODE_ENV !== 'production') {
Object.freeze(ret);
}
return ret;
}
List.meta = {
kind: 'list',
type: type,
name: name,
identity: identity
};
List.displayName = displayName;
List.is = function (x) {
return isArray(x) && x.every(function (e) {
return is(e, type);
});
};
List.update = function (instance, patch) {
return List(assert.update(instance, patch));
};
return List;
}
list.getDefaultName = getDefaultName;
module.exports = list;