UNPKG

2.15 kBJavaScriptView Raw
1
2var Type = require('./type');
3var Node = require('./node');
4function State(){
5 var t = time();
6 if(last < t){
7 return N = 0, last = t;
8 }
9 return last = t + ((N += 1) / D);
10}
11var time = Type.time.is, last = -Infinity, N = 0, D = 1000; // WARNING! In the future, on machines that are D times faster than 2016AD machines, you will want to increase D by another several orders of magnitude so the processing speed never out paces the decimal resolution (increasing an integer effects the state accuracy).
12State._ = '>';
13State.ify = function(n, f, s, v, soul){ // put a field's state on a node.
14 if(!n || !n[N_]){ // reject if it is not node-like.
15 if(!soul){ // unless they passed a soul
16 return;
17 }
18 n = Node.soul.ify(n, soul); // then make it so!
19 }
20 var tmp = obj_as(n[N_], State._); // grab the states data.
21 if(u !== f && f !== N_){
22 if(num_is(s)){
23 tmp[f] = s; // add the valid state.
24 }
25 if(u !== v){ // Note: Not its job to check for valid values!
26 n[f] = v;
27 }
28 }
29 return n;
30}
31State.is = function(n, f, o){ // convenience function to get the state on a field on a node and return it.
32 var tmp = (f && n && n[N_] && n[N_][State._]) || o;
33 if(!tmp){ return }
34 return num_is(tmp[f])? tmp[f] : -Infinity;
35}
36;(function(){
37 State.map = function(cb, s, as){ var u; // for use with Node.ify
38 var o = obj_is(o = cb || s)? o : null;
39 cb = fn_is(cb = cb || s)? cb : null;
40 if(o && !cb){
41 s = num_is(s)? s : State();
42 o[N_] = o[N_] || {};
43 obj_map(o, map, {o:o,s:s});
44 return o;
45 }
46 as = as || obj_is(s)? s : u;
47 s = num_is(s)? s : State();
48 return function(v, f, o, opt){
49 if(!cb){
50 map.call({o: o, s: s}, v,f);
51 return v;
52 }
53 cb.call(as || this || {}, v, f, o, opt);
54 if(obj_has(o,f) && u === o[f]){ return }
55 map.call({o: o, s: s}, v,f);
56 }
57 }
58 function map(v,f){
59 if(N_ === f){ return }
60 State.ify(this.o, f, this.s) ;
61 }
62}());
63var obj = Type.obj, obj_as = obj.as, obj_has = obj.has, obj_is = obj.is, obj_map = obj.map;
64var num = Type.num, num_is = num.is;
65var fn = Type.fn, fn_is = fn.is;
66var N_ = Node._, u;
67module.exports = State;
68
\No newline at end of file