UNPKG

2.13 kBJavaScriptView Raw
1
2var Type = require('./type');
3var Val = require('./val');
4var Node = {_: '_'};
5Node.soul = function(n, o){ return (n && n._ && n._[o || soul_]) } // convenience function to check to see if there is a soul on a node and return it.
6Node.soul.ify = function(n, o){ // put a soul on an object.
7 o = (typeof o === 'string')? {soul: o} : o || {};
8 n = n || {}; // make sure it exists.
9 n._ = n._ || {}; // make sure meta exists.
10 n._[soul_] = o.soul || n._[soul_] || text_random(); // put the soul on it.
11 return n;
12}
13;(function(){
14 Node.is = function(n, cb, as){ var s; // checks to see if an object is a valid node.
15 if(!obj_is(n)){ return false } // must be an object.
16 if(s = Node.soul(n)){ // must have a soul on it.
17 return !obj_map(n, map, {as:as,cb:cb,s:s,n:n});
18 }
19 return false; // nope! This was not a valid node.
20 }
21 function map(v, f){ // we invert this because the way we check for this is via a negation.
22 if(f === Node._){ return } // skip over the metadata.
23 if(!Val.is(v)){ return true } // it is true that this is an invalid node.
24 if(this.cb){ this.cb.call(this.as, v, f, this.n, this.s) } // optionally callback each field/value.
25 }
26}());
27;(function(){
28 Node.ify = function(obj, o, as){ // returns a node from a shallow object.
29 if(!o){ o = {} }
30 else if(typeof o === 'string'){ o = {soul: o} }
31 else if(o instanceof Function){ o = {map: o} }
32 if(o.map){ o.node = o.map.call(as, obj, u, o.node || {}) }
33 if(o.node = Node.soul.ify(o.node || {}, o)){
34 obj_map(obj, map, {o:o,as:as});
35 }
36 return o.node; // This will only be a valid node if the object wasn't already deep!
37 }
38 function map(v, f){ var o = this.o, tmp, u; // iterate over each field/value.
39 if(o.map){
40 tmp = o.map.call(this.as, v, ''+f, o.node);
41 if(u === tmp){
42 obj_del(o.node, f);
43 } else
44 if(o.node){ o.node[f] = tmp }
45 return;
46 }
47 if(Val.is(v)){
48 o.node[f] = v;
49 }
50 }
51}());
52var obj = Type.obj, obj_is = obj.is, obj_del = obj.del, obj_map = obj.map;
53var text = Type.text, text_random = text.random;
54var soul_ = Val.rel._;
55var u;
56module.exports = Node;
57
\No newline at end of file