File: util.go

package info (click to toggle)
golang-github-viant-toolbox 0.33.2-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,280 kB
  • sloc: makefile: 16
file content (479 lines) | stat: -rw-r--r-- 13,052 bytes parent folder | download | duplicates (2)
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
package udf

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/viant/toolbox"
	"github.com/viant/toolbox/data"
	"math/rand"
	"net/url"
	"strings"
	"time"
)

//Length returns length of slice or string
func Length(source interface{}, state data.Map) (interface{}, error) {

	if toolbox.IsSlice(source) {
		return len(toolbox.AsSlice(source)), nil
	}
	if toolbox.IsMap(source) {
		return len(toolbox.AsMap(source)), nil
	}

	if text, ok := source.(string); ok {
		if strings.HasPrefix(text, "$") {
			return nil, fmt.Errorf("unexpanded variable: %v", text)
		}
		return len(text), nil
	}
	return 0, nil
}


//Replace replaces text with old and new fragments
func Replace(source interface{}, state data.Map) (interface{}, error) {
	var args []interface{}
	if ! toolbox.IsSlice(source) {
		return nil, fmt.Errorf("expacted %T, but had %T", args, source)
	}
	args = toolbox.AsSlice(source)
	if len(args) < 3 {
		return nil, fmt.Errorf("expected 3 arguments (text, old, new), but had: %v" , len(args))
	}
	text := toolbox.AsString(args[0])
	old := toolbox.AsString(args[1])
	new := toolbox.AsString(args[2])
	count := strings.Count(text, old)
	return strings.Replace(text, old, new, count), nil
}


// Join joins slice by separator
func Join(args interface{}, state data.Map) (interface{}, error) {
	if !toolbox.IsSlice(args) {
		return nil, fmt.Errorf("expected 2 arguments but had: %T", args)
	}
	arguments := toolbox.AsSlice(args)
	if len(arguments) != 2 {
		return nil, fmt.Errorf("expected 2 arguments but had: %v", len(arguments))
	}

	if !toolbox.IsSlice(arguments[0]) {
		return nil, fmt.Errorf("expected 1st arguments as slice but had: %T", arguments[0])
	}
	var result = make([]string, 0)
	toolbox.CopySliceElements(arguments[0], &result)
	return strings.Join(result, toolbox.AsString(arguments[1])), nil
}

// Split split text to build a slice
func Split(args interface{}, state data.Map) (interface{}, error) {
	if !toolbox.IsSlice(args) {
		return nil, fmt.Errorf("expected 2 arguments but had: %T", args)
	}
	arguments := toolbox.AsSlice(args)
	if len(arguments) != 2 {
		return nil, fmt.Errorf("expected 2 arguments but had: %v", len(arguments))
	}
	if !toolbox.IsString(arguments[0]) {
		return nil, fmt.Errorf("expected 1st arguments as string but had: %T", arguments[0])
	}
	result := strings.Split(toolbox.AsString(arguments[0]), toolbox.AsString(arguments[1]))
	for i := range result {
		result[i] = strings.TrimSpace(result[i])
	}
	return result, nil
}

//Keys returns keys of the supplied map
func Keys(source interface{}, state data.Map) (interface{}, error) {
	aMap, err := AsMap(source, state)
	if err != nil {
		return nil, err
	}
	var result = make([]interface{}, 0)
	err = toolbox.ProcessMap(aMap, func(key, value interface{}) bool {
		result = append(result, key)
		return true
	})
	if err != nil {
		return nil, err
	}
	return result, nil
}

//Values returns values of the supplied map
func Values(source interface{}, state data.Map) (interface{}, error) {
	aMap, err := AsMap(source, state)
	if err != nil {
		return nil, err
	}
	var result = make([]interface{}, 0)
	err = toolbox.ProcessMap(aMap, func(key, value interface{}) bool {
		result = append(result, value)
		return true
	})
	if err != nil {
		return nil, err
	}
	return result, nil
}

//IndexOf returns index of the matched slice elements or -1
func IndexOf(source interface{}, state data.Map) (interface{}, error) {
	if !toolbox.IsSlice(source) {
		return nil, fmt.Errorf("expected arguments but had: %T", source)
	}
	args := toolbox.AsSlice(source)
	if len(args) != 2 {
		return nil, fmt.Errorf("expected 2 arguments but had: %v", len(args))
	}

	if toolbox.IsString(args[0]) {
		return strings.Index(toolbox.AsString(args[0]), toolbox.AsString(args[1])), nil
	}
	collection, err := AsCollection(args[0], state)
	if err != nil {
		return nil, err
	}
	for i, candidate := range toolbox.AsSlice(collection) {
		if candidate == args[1] || toolbox.AsString(candidate) == toolbox.AsString(args[1]) {
			return i, nil
		}
	}
	return -1, nil
}

//Base64Decode encodes source using base64.StdEncoding
func Base64Encode(source interface{}, state data.Map) (interface{}, error) {
	if source == nil {
		return "", nil
	}
	switch value := source.(type) {
	case string:
		return base64.StdEncoding.EncodeToString([]byte(value)), nil
	case []byte:
		return base64.StdEncoding.EncodeToString(value), nil
	default:
		if toolbox.IsMap(source) || toolbox.IsSlice(source) {
			encoded, err := json.Marshal(source)
			fmt.Printf("%s %v\n", encoded, err)
			if err == nil {
				return base64.StdEncoding.EncodeToString(encoded), nil
			}
		}
		return nil, fmt.Errorf("unsupported type: %T", source)
	}
}

//Base64Decode decodes source using base64.StdEncoding
func Base64Decode(source interface{}, state data.Map) (interface{}, error) {
	if source == nil {
		return "", nil
	}
	switch value := source.(type) {
	case string:
		return base64.StdEncoding.DecodeString(value)
	case []byte:
		return base64.StdEncoding.DecodeString(string(value))
	default:
		return nil, fmt.Errorf("unsupported type: %T", source)
	}
}

//Base64DecodeText decodes source using base64.StdEncoding to string
func Base64DecodeText(source interface{}, state data.Map) (interface{}, error) {
	decoded, err := Base64Decode(source, state)
	if err != nil {
		return nil, err
	}
	return toolbox.AsString(decoded), nil
}

//QueryEscape returns url escaped text
func QueryEscape(source interface{}, state data.Map) (interface{}, error) {
	text := toolbox.AsString(source)
	return url.QueryEscape(text), nil
}

//QueryUnescape returns url escaped text
func QueryUnescape(source interface{}, state data.Map) (interface{}, error) {
	text := toolbox.AsString(source)
	return url.QueryUnescape(text)
}

//TrimSpace returns trims spaces from supplied text
func TrimSpace(source interface{}, state data.Map) (interface{}, error) {
	text := toolbox.AsString(source)
	return strings.TrimSpace(text), nil
}

//Count returns count of matched nodes leaf value
func Count(xPath interface{}, state data.Map) (interface{}, error) {
	result, err := aggregate(xPath, state, func(previous, newValue float64) float64 {
		return previous + 1
	})
	if err != nil {
		return nil, err
	}
	return AsNumber(result, nil)
}

//Sum returns sums of matched nodes leaf value
func Sum(xPath interface{}, state data.Map) (interface{}, error) {
	result, err := aggregate(xPath, state, func(previous, newValue float64) float64 {
		return previous + newValue
	})
	if err != nil {
		return nil, err
	}
	return AsNumber(result, nil)
}

//Select returns all matched attributes from matched nodes, attributes can be alised with sourcePath:alias
func Select(params interface{}, state data.Map) (interface{}, error) {
	var arguments = make([]interface{}, 0)
	if toolbox.IsSlice(params) {
		arguments = toolbox.AsSlice(params)
	} else {
		arguments = append(arguments, params)
	}
	xPath := toolbox.AsString(arguments[0])
	var result = make([]interface{}, 0)
	attributes := make([]string, 0)
	for i := 1; i < len(arguments); i++ {
		attributes = append(attributes, toolbox.AsString(arguments[i]))
	}
	err := matchPath(xPath, state, func(matched interface{}) error {
		if len(attributes) == 0 {
			result = append(result, matched)
			return nil
		}
		if !toolbox.IsMap(matched) {
			return fmt.Errorf("expected map for %v, but had %T", xPath, matched)
		}
		matchedMap := data.Map(toolbox.AsMap(matched))
		var attributeValues = make(map[string]interface{})
		for _, attr := range attributes {
			if strings.Contains(attr, ":") {
				kvPair := strings.SplitN(attr, ":", 2)
				value, has := matchedMap.GetValue(kvPair[0])
				if !has {
					continue
				}
				attributeValues[kvPair[1]] = value
			} else {
				value, has := matchedMap.GetValue(attr)
				if !has {
					continue
				}
				attributeValues[attr] = value
			}
		}
		result = append(result, attributeValues)
		return nil
	})
	return result, err
}

//AsNumber return int or float
func AsNumber(value interface{}, state data.Map) (interface{}, error) {
	floatValue := toolbox.AsFloat(value)
	if float64(int(floatValue)) == floatValue {
		return int(floatValue), nil
	}
	return floatValue, nil
}

//Aggregate applies an aggregation function to matched path
func aggregate(xPath interface{}, state data.Map, agg func(previous, newValue float64) float64) (float64, error) {
	var result = 0.0
	if state == nil {
		return 0.0, fmt.Errorf("state was empty")
	}
	err := matchPath(toolbox.AsString(xPath), state, func(value interface{}) error {
		if value == nil {
			return nil
		}
		floatValue, err := toolbox.ToFloat(value)
		if err != nil {
			return err
		}
		result = agg(result, floatValue)
		return nil
	})
	return result, err
}

func matchPath(xPath string, state data.Map, handler func(value interface{}) error) error {
	fragments := strings.Split(toolbox.AsString(xPath), "/")
	var node = state
	var nodeValue interface{}
	for i, part := range fragments {

		isLast := i == len(fragments)-1
		if isLast {
			if part == "*" {
				if toolbox.IsSlice(nodeValue) {
					for _, item := range toolbox.AsSlice(nodeValue) {
						if err := handler(item); err != nil {
							return err
						}
					}
					return nil
				} else if toolbox.IsMap(nodeValue) {
					for _, item := range toolbox.AsMap(nodeValue) {
						if err := handler(item); err != nil {
							return err
						}
					}
				}
				return handler(nodeValue)
			}

			if !node.Has(part) {
				break
			}
			if err := handler(node.Get(part)); err != nil {
				return err
			}
			continue
		}
		if part != "*" {
			nodeValue = node.Get(part)
			if nodeValue == nil {
				break
			}
			if toolbox.IsMap(nodeValue) {
				node = toolbox.AsMap(nodeValue)
				continue
			}
			if toolbox.IsSlice(nodeValue) {
				continue
			}
			break
		}

		if nodeValue == nil {
			break
		}
		subXPath := strings.Join(fragments[i+1:], "/")
		if toolbox.IsSlice(nodeValue) {
			aSlice := toolbox.AsSlice(nodeValue)
			for _, item := range aSlice {
				if toolbox.IsMap(item) {
					if err := matchPath(subXPath, toolbox.AsMap(item), handler); err != nil {
						return err
					}
					continue
				}
				return fmt.Errorf("unsupported path type:%T", item)
			}
		}
		if toolbox.IsMap(nodeValue) {
			aMap := toolbox.AsMap(nodeValue)
			for _, item := range aMap {
				if toolbox.IsMap(item) {
					if err := matchPath(subXPath, toolbox.AsMap(item), handler); err != nil {
						return err
					}
					continue
				}
				return fmt.Errorf("unsupported path type:%T", item)
			}
		}
		break
	}
	return nil
}

//Rand returns random
func Rand(params interface{}, state data.Map) (interface{}, error) {
	source := rand.NewSource(time.Now().UnixNano())
	generator := rand.New(source)
	floatValue := generator.Float64()
	if params == nil || !toolbox.IsSlice(params) {
		return floatValue, nil
	}
	parameters := toolbox.AsSlice(params)
	if len(parameters) != 2 {
		return floatValue, nil
	}
	min := toolbox.AsInt(parameters[0])
	max := toolbox.AsInt(parameters[1])
	return min + int(float64(max-min)*floatValue), nil
}

//Concat concatenate supplied parameters, parameters
func Concat(params interface{}, state data.Map) (interface{}, error) {
	if params == nil || !toolbox.IsSlice(params) {
		return nil, fmt.Errorf("invalid signature, expected: $Concat(arrayOrItem1, arrayOrItem2)")
	}
	var result = make([]interface{}, 0)
	parameters := toolbox.AsSlice(params)
	if len(parameters) == 0 {
		return result, nil
	}

	if toolbox.IsString(parameters[0]) {
		result := ""
		for _, item := range parameters {
			result += toolbox.AsString(item)
		}
		return result, nil
	}

	for _, item := range parameters {
		if toolbox.IsSlice(item) {
			itemSlice := toolbox.AsSlice(item)
			result = append(result, itemSlice...)
			continue
		}
		result = append(result, item)
	}
	return result, nil
}

//Merge creates a new merged map for supplied maps,  (mapOrPath1, mapOrPath2, mapOrPathN)
func Merge(params interface{}, state data.Map) (interface{}, error) {
	if params == nil || !toolbox.IsSlice(params) {
		return nil, fmt.Errorf("invalid signature, expected: $Merge(map1, map2, override)")
	}
	var result = make(map[string]interface{})
	parameters := toolbox.AsSlice(params)
	if len(parameters) == 0 {
		return result, nil
	}
	var ok bool
	for _, item := range parameters {
		if toolbox.IsString(item) && state != nil {
			if item, ok = state.GetValue(toolbox.AsString(item)); !ok {
				continue
			}
		}
		if !toolbox.IsMap(item) {
			continue
		}
		itemMap := toolbox.AsMap(item)
		for k, v := range itemMap {
			result[k] = v
		}
	}
	return result, nil
}

//AsNewLineDelimitedJSON convers a slice into new line delimited JSON
func AsNewLineDelimitedJSON(source interface{}, state data.Map) (interface{}, error) {
	if source == nil || !toolbox.IsSlice(source) {
		return nil, fmt.Errorf("invalid signature, expected: $AsNewLineDelimitedJSON([])")
	}
	aSlice := toolbox.AsSlice(source)
	var result = make([]string, 0)
	for _, item := range aSlice {
		data, _ := json.Marshal(item)
		result = append(result, string(data))
	}
	return strings.Join(result, "\n"), nil
}