-
Notifications
You must be signed in to change notification settings - Fork 2
/
Primitive.js
70 lines (60 loc) · 1.67 KB
/
Primitive.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
// @flow
import assert from 'minimalistic-assert';
const invalidNameMsg = name =>
`Invalid primitive name "${name}".` +
'\nNames must begin lowercase and contain no special characters.';
type Binary =
| ArrayBuffer
| Uint8Array
| Uint8ClampedArray
| Uint16Array
| Uint32Array
| Int8Array
| Int16Array
| Int32Array
| Float32Array
| Float64Array;
type JsonPrimitive = ?(number | string | boolean | Binary);
type TypeDefinition = {
coerce(value: JsonPrimitive): JsonPrimitive,
isValid(data: mixed): boolean,
};
export const nameRegex = /^[a-z][0-9a-z-]*$/;
/** Creates primitive types. */
export default class Primitive {
_isValid: mixed => boolean;
_coerce: Function;
name: string;
/**
* @param {String} name - A unique title for the primitive.
* @param {Object} def - Primitive definition.
* @param {Function} def.isValid - Whether an arbitrary value qualifies.
*/
constructor(name: string, def: TypeDefinition) {
assert(nameRegex.test(name), invalidNameMsg(name));
this.name = name;
Object.defineProperties(this, {
_isValid: { value: def.isValid },
_coerce: { value: def.coerce },
});
}
/**
* Whether the value is valid.
* @param {mixed} value - Anything but `undefined`.
* @return {Boolean} - Whether the value is valid.
*/
isValid(value: mixed): boolean {
if (value === undefined) {
return false;
}
return this._isValid(value);
}
/**
* Coerces a JSON value to the given type.
* @param {mixed} value - Any JSON-expressable value.
* @return {mixed} - The type this primitive represents.
*/
coerce(value: JsonPrimitive) {
return this._coerce(value);
}
}