UNPKG

2.1 kBJavaScriptView Raw
1import Property from './property';
2import { identity } from './utilities';
3import { assert, isUndefined, isObject, isFunction } from './assertions';
4
5const internal = {};
6
7internal.empty = val => val == null;
8internal.nullOrType = type => val => !val ? null : type(val);
9internal.zeroOrNumber = val => !val ? 0 : Number(val);
10
11
12internal.Attribute = module.exports = (attribute) => {
13
14 assert(isObject(attribute), `'attribute' must be an object`);
15
16 let {
17 stringify = JSON.stringify,
18 parse = JSON.parse,
19 coerce,
20 isDataAttribute = true,
21 defaultValue,
22 } = attribute;
23
24 assert(isFunction(stringify), `'stringify' must be a function`);
25 assert(isFunction(parse), `'parse' must be a function`);
26
27 return Object.assign(attribute, {
28 isAttribute: true,
29 isDataAttribute,
30 stringify,
31 parse,
32 coerce,
33 defaultValue
34 });
35};
36
37internal.Attribute.array = (options = {}) => internal.Attribute(Property.array(options));
38internal.Attribute.plain = (options = {}) => internal.Attribute(Property.plain(options));
39internal.Attribute.boolean = (options = {}) => internal.Attribute(
40 Object.assign(Property.boolean(options), {
41 parse: val => {
42 console.log('parse', val)
43 return val === '';
44 },
45 stringify: val => val ? '' : null
46 })
47);
48
49internal.Attribute.number = (options = {}) => internal.Attribute(
50 Object.assign({
51 defaultValue: 0,
52 coerce: internal.zeroOrNumber,
53 parse: internal.zeroOrNumber,
54 stringify: internal.nullOrType(Number)
55 }, options)
56);
57
58internal.Attribute.integer = (options = {}) => internal.Attribute.number(
59 Object.assign(options, {
60 coerce: parseInt,
61 parse: parseInt
62 })
63);
64
65internal.Attribute.float = (options = {}) => internal.Attribute.number(
66 Object.assign(options, {
67 coerce: parseFloat,
68 parse: parseFloat
69 })
70);
71
72internal.Attribute.object = (options = {}) => internal.Attribute(Property.object(options));
73
74internal.Attribute.string = (options = {}) => internal.Attribute(
75 Object.assign({
76 defaultValue: '',
77 coerce: String,
78 stringify: internal.nullOrType(String)
79 }, options)
80);