-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchute.js
292 lines (291 loc) · 10.5 KB
/
chute.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
const chute = (()=>{
// https://gregabbott.github.io/chute By + Copyright Greg Abbott
// [V1=2024-11-27][V=2024-12-08.2]
const stringy=x=>JSON.stringify(x),
error=(...x)=>{throw new Error(x)},
is_fn=x=>x instanceof Function,
is_number=v=>typeof v ==='number'&&!isNaN(v),
is_array=x=>Array.isArray(x),
is_object=v=>v&& typeof v=='object'&&!Array.isArray(v),
is_js_method=(o,k)=>is_fn(Object.getPrototypeOf(o)[k]),
is_global_fn=name=>is_fn(globalThis[name]),
loop_o=f=>o=>{for(let k in o)if(f(k,o[k],o)===!1)break},
lift_libraries=o=>{// hoist
if(!is_object(o))error(`give .lift 1 object`)
loop_o((k,v)=>{
if(!is_object(v))return
CHUTE.library[k]=v
CHUTE.lifted_libraries.push(v)
})(o)
return CHUTE
},
load_feed_items=o=>{
if(!is_object(o))error(`give .feed 1 object`)
loop_o((k,v)=>{if(is_fn(v)||is_object(v))CHUTE.library[k]=v})
(o)
return CHUTE
},
chute_lib={},//Holds: log, tap, do, if
PLACEHOLDER = {},//Stands in for data in .fn call arguments
CHUTE=(seed=PLACEHOLDER,...args)=>{
//To require seed use: if(seed===PLACEHOLDER)return CHUTE
//Allow blank start so user may call a dot FN to get seed
return new_chute({seed,args})//Default chute
}//^Becomes "const chute". `chute([seed,args])` makes new chute
CHUTE.make=(...o)=>{
let settings=o.length===1&&is_object(o[0])?o[0]:0
if(!settings)error('Make takes 1 object for settings')
return new_chute({settings})//Custom chute
}
const setup_chute=({settings,a_chute})=>{
let o = settings
if(o.sync)load_sync_fn(o.sync,a_chute)
if('skip' in o)a_chute.skip_void=!!o.skip
if(o.path)a_chute.treat_dots_as_paths=!!o.path
}
CHUTE.x=PLACEHOLDER//Gives user access
CHUTE.library={}//Holds Fns that FEED/LIFT give to all chutes
CHUTE.lifted_libraries=[]//Holds libs LIFT gives to all chutes
//lifted_libraries can call ".fn_name" & ".lib_name.fn_name"
CHUTE.lift=lift_libraries
CHUTE.feed=load_feed_items
chute_lib.log=({args,data})=>{
if(args.length>0){console.log(...args,data)}
else console.log(data)
return data
}
chute_lib.do=({args,data,a_chute})=>{//[a,b,c]->c(b(a(x)))
if(args.length==0)error('give .do >0 arguments')
return args.reduce((data,arg)=>{
if(arg==='log'){console.log(data);return data}
else if(is_fn(arg)){a_chute.keep(arg);return arg(data)}
return arg//Likely an expression result: `.do(variable*5)`
},data)
}
const make_memoizer=a_chute=>f=>{
let n = f.name
let keep=n&&!is_global_fn(n)&&!a_chute.fns_seen[n]
if(keep)a_chute.fns_seen[n]=f
return f
}
const call_a_function=({fn,data,args})=>{
if(args.length===0)return fn(data)
let processed_args=swap_placeholders(args,data)
let had_placeholder=processed_args!==args
if(had_placeholder)return fn(...processed_args)
// Because arguments lack placeholder for data:
else return fn(...args)(data)//Expect a Fn to provide data to.
}
const swap_placeholders=(args,data)=>{
let must_swap=args.length>0&&args.includes(PLACEHOLDER)
if(must_swap)return args.map(a=>a===PLACEHOLDER?data:a)
return args
}
const chain_stopping_methods=new Set([
'forEach',//returns undefined
'push',//returns new length
'unshift',//returns new length
])
const is_condition_block=o=>{
//Has {if:[q,a]} and any else_ifs have valid [q,a] pairs
if(!is_object(o))return false
if(!'if' in o)return false
const is_q_a=x=>is_array(x)&&x.length===2&&0 in x && 1 in x
let results = Object.entries(o).reduce((a,[k,v])=>{
if(k=='if'&&is_array(v)&&is_q_a(v)){ a.valid[k]=v }
else if(k=='else_if'){
let Y=is_array(v)&&v.map(is_q_a).filter(x=>!x).length<1
a[Y?'valid':'invalid'][k]=v
}
else if(k=='else'){ a.valid[k]=v }
else { a.invalid[k]=v }
return a
},{valid:{},invalid:{}})
//console.log(results)
return Object.keys(results.invalid).length===0
}
const process_condition_block=(c,data,a_chute)=>{
//Memoize non-global Q/A Fns to dot-style call in same Chute
(c.else_if?[c.if, ...c.else_if]:[c.if]).forEach(([q,a])=>{
if(is_fn(q))a_chute.keep(q)
if(is_fn(a))a_chute.keep(a)
})
// Get first truthy's returnable (which may === undefined)
function Q({q,data}){ if(is_fn(q)){return q(data)}return q }
if(Q({q:c.if[0],data}))return c.if[1]//answer
if('else_if' in c){
for(let[q,a] of c.else_if)if(Q({q,data}))return a
}
if('else' in c){
if(is_fn(c.else))a_chute.keep(c.else)
return c.else
}
return data//No matches
}
chute_lib.pick=({args,data,a_chute})=>{
if(args.length==0)error('.if needs 1-2 arguments')
let conditions_block=
args.length===2?{if:args}//reshape into an if-else object
:args.length===1?args[0]
:false
if(is_condition_block(conditions_block)){
let rv = process_condition_block(
conditions_block,
data,
a_chute
)
if(data===rv)return data//unchanged
if(is_fn(rv))return call_a_function({fn:rv,data,args:[]})
//^If above true, memoized the FN in process_condition_block
return rv
}
else {
error(`.if block incorrect`,args)
return data
}
}
chute_lib.tap=({args,data})=>{
let fn = args[0]
if(is_fn(fn)) fn(data)//ignore return
else error('give .tap a fn to send data to')
return data
}
function load_sync_fn(o,a_chute){
if(!is_fn(o))error(`give SYNC FN: "v=>user_variable=v"`)
a_chute.sync_data=o
a_chute.sync_data(a_chute.get_data())//Make user_variable!null
}
function handle_nested_access(a_chute,args){
let dot_list = a_chute.dot_list
let data = a_chute.get_data()
let skip_void = a_chute.skip_void
// This finds break points in a dot sequence.
//if given: ".reverse.log[4].JSON.stringify(Args)"
//it deduces: .reverse|.log|index 4|.JSON.stringify(Args)
function setup_root(key,a){
//let o = { }
let desc = `a built in chute method; `+
`a method of the_current_data; `+
`a function passed in to this chute via a previous call, `+
`or Chute's .feed or .lift properties;`+
`or a global function.`
//console.log(`find root of "${key}"`,a.data)
//ORDERED BY RANK (local to far)
let chute_fn=chute_lib.hasOwnProperty(key)//<-non native
if(chute_fn)return ['chute_lib',chute_lib]
let seeded_chute=a.data!==null&&a.data[key]!==undefined
if(seeded_chute)return['the_current_data',a.data]
let memoised=a_chute.fns_seen[key]
if(memoised)return['memoized_function',a_chute.fns_seen]
//X
if(CHUTE.library[key])return ['Feed_lib',CHUTE.library]
let lifted_lib=CHUTE.lifted_libraries.find(lib=>lib[key])
if(lifted_lib)return['Lift_lib',lifted_lib]
let global_el=globalThis[key]!==undefined
if(global_el)return ['global_this',globalThis]
error(`"${key}" is not: ${desc}`)
}/* globalThis.JSON.stringify(Args)
\________/ \__/ \_______/
| | |
root context Fn*/
let path_mode=a_chute.treat_dots_as_paths
//^ if dot_list==[a,b,c] path_mode expects a[b][c](). !a|>b|>c
return dot_list.reduce((a,key,i,l)=>{
if(!a.path){
([a.root_string,a.root]=setup_root(key,a))
a.path = a.root//a new path starts with the root
a.context=a.root//context means the item that holds the FN
//console.log(`root of ${key} is ${a.root_string}`)
}
a.path=a.path[key]//e.g. GlobalThis['JSON']
let is_last_key=i==l.length-1
if(is_last_key)return try_do({fn:a.path,key,a,args})
let next_key=dot_list[i+1]
let found_last_in_current_path=a.path[next_key]===undefined
if(found_last_in_current_path){
if(path_mode)error(`"${key}" lacks "${next_key}"`)
//^ EG key==".a.b()"&&!a[b]&&path_mode?FAIL^:CHAIN b(a(x))
//console.log(`run "${key}"`)
a.data = try_do({fn:a.path,key,a})//not last key so 0 args
//^ Data forms input for next FN && not saved to chute yet
// next key starts a new path:
a.path=null//reset
}
else a.context=a.path//the current item holds the next item
return a
},{path:null,data,context:null,root:null})
function try_do({fn,key,a,args=[]}){
//console.log(`RUN ${a.root_string}'s '"${key}"`)
// Dot-style-calls use functions Chute can access already:
// no need to memoize fn but do inspect their args for fns
if(!is_fn(a.path))error(`${a.root_string}…"${key}" not ƒ`)
let rv
if(a.root==chute_lib)rv=fn({args,data:a.data,a_chute})
else if(
a.root===globalThis
||a.root==a_chute.fns_seen
||a.root==CHUTE.library
||a.root_string=='Lift_lib'
){ rv = call_a_function({fn,data:a.data,args}) }
else {//current_data.a.b.c.fn(),
//Call any function the current_data contains.
//To restrict to native methods (e.g. .map .reduce),
//add condition is_js_method(data,key)
rv = fn.call(a.context,...swap_placeholders(args,a.data))
rv = chain_stopping_methods.has(key)?a.data:rv
}
return rv===undefined&&skip_void?/*old*/a.data:/*new*/rv
}
}
const blank_chute=()=>({
data:null,
fns_seen: {},//non-global named fns encountered memoized
treat_dots_as_paths:false,//.log.reverse vs .log().reverse()
sync_data:null,//Accepts `x=>user_variable=x` to send data
skip_void:true,//Default
dot_list:[],//^.a.b.c collected until '()' given
})
function _get(a_chute,key){a_chute.dot_list.push(key)}
function _apply(a_chute, args){
let named_end_chute=['_end','_$']
.includes(a_chute.dot_list.at(-1))
if(named_end_chute)a_chute.dot_list.pop()
let is_nameless_call = a_chute.dot_list.length==0,
is_nameless_do_call = is_nameless_call && args.length>0,
is_nameless_end_chute = is_nameless_call && args.length===0,
is_named_call = !is_nameless_call,
should_end_chute = is_nameless_end_chute || named_end_chute
let update_value = is_nameless_do_call||is_named_call
let rv
if(is_nameless_do_call){
rv=chute_lib.do({args, data:a_chute.get_data(), a_chute})
}
else if(is_named_call)rv=handle_nested_access(a_chute, args)
if(update_value)a_chute.set_data(rv)
a_chute.dot_list.length=0//Reset : processed all call keys
return should_end_chute?a_chute.get_data():a_chute.proxy
}
function new_chute({seed,args,settings}){
let a_chute=blank_chute()
a_chute.keep=make_memoizer(a_chute)
a_chute.set_data=x=>{
if(x===undefined&&a_chute.skip_void)return/*move on*/
if(a_chute.sync_data/*provided*/){a_chute.sync_data(x)}
a_chute.data=x
}
a_chute.get_data=()=>a_chute.data
if(settings){//called chute.make({settings_object})
setup_chute({settings,a_chute})
}
if(seed)a_chute.set_data(seed)
if(args?.length>0){
a_chute.set_data(chute_lib.do({args,data:seed,a_chute}))
}
a_chute.proxy = new Proxy(()=>{},{
get:(_,k)=>{_get(a_chute,k);return a_chute.proxy},
apply:(_,__,args)=>_apply(a_chute,args)
})
return a_chute.proxy
}
return CHUTE
})()