objectToSaneObject.js
1.57 KB
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
// Generated by CoffeeScript 1.12.7
var object, self,
hasProp = {}.hasOwnProperty;
object = require('utila').object;
module.exports = self = {
sanitize: function(val) {
return self._toChildren(val);
},
_toChildren: function(val) {
var ref;
if (object.isBareObject(val)) {
return self._objectToChildren(val);
} else if (Array.isArray(val)) {
return self._arrayToChildren(val);
} else if (val === null || typeof val === 'undefined') {
return [];
} else if ((ref = typeof val) === 'string' || ref === 'number') {
return [String(val)];
} else {
throw Error("not a valid child node: `" + val);
}
},
_objectToChildren: function(o) {
var a, cur, key, val;
a = [];
for (key in o) {
if (!hasProp.call(o, key)) continue;
val = o[key];
cur = {};
cur[key] = self.sanitize(val);
a.push(cur);
}
return a;
},
_arrayToChildren: function(a) {
var i, len, ret, v;
ret = [];
for (i = 0, len = a.length; i < len; i++) {
v = a[i];
ret.push(self._toNode(v));
}
return ret;
},
_toNode: function(o) {
var key, keys, obj, ref;
if ((ref = typeof o) === 'string' || ref === 'number') {
return String(o);
} else if (object.isBareObject(o)) {
keys = Object.keys(o);
if (keys.length !== 1) {
throw Error("a node must only have one key as tag name");
}
key = keys[0];
obj = {};
obj[key] = self._toChildren(o[key]);
return obj;
} else {
throw Error("not a valid node: `" + o + "`");
}
}
};