-
-
Notifications
You must be signed in to change notification settings - Fork 59
/
arg.node.ts
99 lines (77 loc) · 2.3 KB
/
arg.node.ts
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
namespace $ {
/** State of arguments like `foo=bar xxx` */
export class $mol_state_arg extends $mol_object {
static prolog = ''
static separator = ' '
@ $mol_mem
static href( next? : string ) {
return next || process.argv.slice( 2 ).join( ' ' )
}
@ $mol_mem
static href_normal() {
return this.link({})
}
@ $mol_mem
static dict( next? : { [ key : string ] : string | null } ) {
if( next !== void 0 ) this.href( this.make_link( next ) )
var href = this.href()
var chunks = href.split( ' ' )
var params : { [ key : string ] : string } = {}
chunks.forEach(
chunk => {
if( !chunk ) return
var vals = chunk.split( '=' ).map( decodeURIComponent )
params[ vals.shift()! ] = vals.join('=')
}
)
return params as Readonly< typeof params >
}
@ $mol_mem_key
static value( key : string , next? : string | null ) {
if( next === void 0 ) return this.dict()[ key ] ?? null
this.href( this.link( { [ key ] : next } ) )
return next
}
static link( next : Record<string, string | null> ) {
const params : Record<string, string | null> = {}
var prev = this.dict()
for( var key in prev ) {
params[ key ] = prev[ key ]
}
for( var key in next ) {
params[ key ] = next[ key ]
}
return this.make_link( params )
}
static make_link( next : Record<string, string | null>) {
const chunks : string[] = []
for( const key in next ) {
if( next[ key ] !== null ) {
chunks.push([key, next[key]!].map(encodeURIComponent).join('='))
}
}
return chunks.join( ' ' )
}
@ $mol_action
static go( next : { [ key : string ] : string | null } ) {
this.href( this.link( next ) )
}
constructor( public prefix = '' ) {
super()
}
value( key : string , next? : string ) {
return ( this.constructor as typeof $mol_state_arg ).value( this.prefix + key , next )
}
sub( postfix : string ) {
return new ( this.constructor as typeof $mol_state_arg )( this.prefix + postfix + '.' )
}
link( next : Record<string, string | null> ) {
const prefix = this.prefix
const dict : Record<string, string | null> = {}
for( var key in next ) {
dict[ prefix + key ] = next[ key ]
}
return ( this.constructor as typeof $mol_state_arg ).link( dict )
}
}
}