-
Notifications
You must be signed in to change notification settings - Fork 0
/
utilities.libsonnet
162 lines (102 loc) · 3.37 KB
/
utilities.libsonnet
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
local empty( ) = ({ });
local key( kv ) = ( kv[ 0 ] );
local value( kv ) = ( kv [ 1 ] );
local get( o, k, d = null ) = (
if std.objectHas( o, k )
then o[ k ]
else d
);
local entries( o ) = (
std.map(
function( key )([ key, o[ key ] ]),
std.objectFields( o )
)
);
local keys( o ) = (
std.objectFields( o )
);
local values( o ) = (
std.map(
function( k )( o [ k ] ),
std.objectFields( o )
)
);
local setMap( f, o ) = (
std.map(
function ( kv ) f( key( kv ), value( kv ) ),
entries( o )
)
);
local to_object( pairs ) = ({
[ key( kv ) ] : value( kv ) for kv in std.set( std.reverse( std.filter( std.isArray, pairs ) ), key )
});
local combine( default, combiner ) =
function( left, right ) default( ) + left + right + combiner( left, right );
local mixin( combiner ) =
function( mixins, target ) std.foldr( combiner, mixins, target );
local unzip_objects( left, right ) = (
local pick( key ) = ([
key,
if std.objectHas( left, key ) then [ key, left[ key ] ] else null,
if std.objectHas( right, key ) then [ key, right[ key ] ] else null,
]);
local keys = std.setUnion(
std.objectFields( left ),
std.objectFields( right )
);
std.map( pick, keys )
);
local map_combiner( handlers ) = (
function( left, right )(
local combined = std.foldr(
function( tuple, _ )(
local tkey = key( tuple );
local tleft = if null == tuple[ 1 ] then [ null, null ] else tuple[ 1 ];
local tright = if null == tuple[ 2 ] then [ null, null ] else tuple[ 2 ];
local left_has_entry = null != key( tleft );
local right_has_entry = null != key( tright );
local handler =
if std.objectHasAll( handlers, tkey )
then function( l, r, k )(
handlers[ tkey ]( value( l ), value( r ) )
)
else
if std.objectHasAll( handlers, "*" )
then function( l, r, k )(
handlers[ "*" ]( value( l ), value( r ), k )
)
else function( l, r, k )(
get( to_object([ l, r ]), k )
)
;
_ + {
[ tkey ] :
if left_has_entry && right_has_entry
then handler( tleft, tright, tkey )
else
if right_has_entry
then value( tright )
else value( tleft )
}
),
unzip_objects( left, right ),
empty( )
);
combined
)
);
{
empty :: empty,
key :: key,
value :: value,
get :: get,
entries :: entries,
keys :: keys,
values :: values,
setMap :: setMap,
to_object :: to_object,
combine :: combine,
mixin :: mixin,
unzip_objects :: unzip_objects,
map_combiner :: map_combiner,
}