-
Notifications
You must be signed in to change notification settings - Fork 19
/
functions.go
1603 lines (1421 loc) · 48.7 KB
/
functions.go
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package functions
import (
"bytes"
"fmt"
"math"
"net/url"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/nyaruka/gocommon/urns"
"github.com/nyaruka/goflow/excellent/types"
"github.com/nyaruka/goflow/utils"
humanize "github.com/dustin/go-humanize"
"github.com/shopspring/decimal"
)
var nanosPerSecond = decimal.RequireFromString("1000000000")
var nonPrintableRegex = regexp.MustCompile(`[\p{Cc}\p{C}]`)
// XFunction defines the interface that Excellent functions must implement
type XFunction func(env utils.Environment, args ...types.XValue) types.XValue
// RegisterXFunction registers a new function in Excellent
func RegisterXFunction(name string, function XFunction) {
XFUNCTIONS[name] = function
}
// XFUNCTIONS is our map of functions available in Excellent which aren't tests
var XFUNCTIONS = map[string]XFunction{
// type conversion
"text": OneArgFunction(Text),
"boolean": OneArgFunction(Boolean),
"number": OneArgFunction(Number),
"datetime": OneTextFunction(DateTime),
"array": Array,
// text functions
"char": OneNumberFunction(Char),
"code": OneTextFunction(Code),
"split": TwoTextFunction(Split),
"join": TwoArgFunction(Join),
"title": OneTextFunction(Title),
"word": InitialTextFunction(1, 2, Word),
"remove_first_word": OneTextFunction(RemoveFirstWord),
"word_count": InitialTextFunction(0, 1, WordCount),
"word_slice": InitialTextFunction(1, 3, WordSlice),
"field": InitialTextFunction(2, 2, Field),
"clean": OneTextFunction(Clean),
"left": TextAndIntegerFunction(Left),
"lower": OneTextFunction(Lower),
"right": TextAndIntegerFunction(Right),
"text_compare": TwoTextFunction(TextCompare),
"repeat": TextAndIntegerFunction(Repeat),
"replace": ThreeTextFunction(Replace),
"upper": OneTextFunction(Upper),
"percent": OneNumberFunction(Percent),
"url_encode": OneTextFunction(URLEncode),
// bool functions
"and": ArgCountCheck(1, -1, And),
"if": ThreeArgFunction(If),
"or": ArgCountCheck(1, -1, Or),
// number functions
"round": OneNumberAndOptionalIntegerFunction(Round, 0),
"round_up": OneNumberAndOptionalIntegerFunction(RoundUp, 0),
"round_down": OneNumberAndOptionalIntegerFunction(RoundDown, 0),
"max": ArgCountCheck(1, -1, Max),
"min": ArgCountCheck(1, -1, Min),
"mean": ArgCountCheck(1, -1, Mean),
"mod": TwoNumberFunction(Mod),
"rand": NoArgFunction(Rand),
"rand_between": TwoNumberFunction(RandBetween),
"abs": OneNumberFunction(Abs),
// datetime functions
"parse_datetime": ArgCountCheck(2, 3, ParseDateTime),
"datetime_from_parts": ArgCountCheck(3, 3, DateTimeFromParts),
"datetime_diff": DateTimeDiff,
"datetime_add": DateTimeAdd,
"weekday": OneDateTimeFunction(Weekday),
"tz": OneDateTimeFunction(TZ),
"tz_offset": OneDateTimeFunction(TZOffset),
"today": NoArgFunction(Today),
"now": NoArgFunction(Now),
"from_epoch": OneNumberFunction(FromEpoch),
"epoch": OneDateTimeFunction(Epoch),
// json functions
"json": OneArgFunction(JSON),
"parse_json": OneTextFunction(ParseJSON),
// formatting functions
"format_date": ArgCountCheck(1, 2, FormatDate),
"format_datetime": ArgCountCheck(1, 3, FormatDateTime),
"format_location": OneTextFunction(FormatLocation),
"format_number": FormatNumber,
"format_urn": FormatURN,
// utility functions
"length": OneArgFunction(Length),
"default": TwoArgFunction(Default),
"legacy_add": TwoArgFunction(LegacyAdd),
"read_chars": OneTextFunction(ReadChars),
}
//------------------------------------------------------------------------------------------
// Type Conversion Functions
//------------------------------------------------------------------------------------------
// Text tries to convert `value` to text. An error is returned if the value can't be converted.
//
// @(text(3 = 3)) -> true
// @(json(text(123.45))) -> "123.45"
// @(text(1 / 0)) -> ERROR
//
// @function text(value)
func Text(env utils.Environment, value types.XValue) types.XValue {
str, xerr := types.ToXText(env, value)
if xerr != nil {
return xerr
}
return str
}
// Boolean tries to convert `value` to a boolean. An error is returned if the value can't be converted.
//
// @(boolean(array(1, 2))) -> true
// @(boolean("FALSE")) -> false
// @(boolean(1 / 0)) -> ERROR
//
// @function boolean(value)
func Boolean(env utils.Environment, value types.XValue) types.XValue {
str, xerr := types.ToXBoolean(env, value)
if xerr != nil {
return xerr
}
return str
}
// Number tries to convert `value` to a number. An error is returned if the value can't be converted.
//
// @(number(10)) -> 10
// @(number("123.45000")) -> 123.45
// @(number("what?")) -> ERROR
//
// @function number(value)
func Number(env utils.Environment, value types.XValue) types.XValue {
num, xerr := types.ToXNumber(env, value)
if xerr != nil {
return xerr
}
return num
}
// DateTime turns `text` into a date according to the environment's settings. It will return an error
// if it is unable to convert the text to a date.
//
// @(datetime("1979-07-18")) -> 1979-07-18T00:00:00.000000-05:00
// @(datetime("1979-07-18T10:30:45.123456Z")) -> 1979-07-18T10:30:45.123456Z
// @(datetime("2010 05 10")) -> 2010-05-10T00:00:00.000000-05:00
// @(datetime("NOT DATE")) -> ERROR
//
// @function datetime(text)
func DateTime(env utils.Environment, str types.XText) types.XValue {
date, err := utils.DateFromString(env, str.Native(), false)
if err != nil {
return types.NewXError(err)
}
return types.NewXDateTime(date)
}
// Array takes a list of `values` and returns them as an array
//
// @(array("a", "b", 356)[1]) -> b
// @(join(array("a", "b", "c"), "|")) -> a|b|c
// @(length(array())) -> 0
// @(length(array("a", "b"))) -> 2
//
// @function array(values...)
func Array(env utils.Environment, args ...types.XValue) types.XValue {
// check none of our args are errors
for _, arg := range args {
if types.IsXError(arg) {
return arg
}
}
return types.NewXArray(args...)
}
//------------------------------------------------------------------------------------------
// Bool Functions
//------------------------------------------------------------------------------------------
// And returns whether all the passed in arguments are truthy
//
// @(and(true)) -> true
// @(and(true, false, true)) -> false
//
// @function and(tests...)
func And(env utils.Environment, args ...types.XValue) types.XValue {
for _, arg := range args {
asBool, xerr := types.ToXBoolean(env, arg)
if xerr != nil {
return xerr
}
if !asBool.Native() {
return types.XBooleanFalse
}
}
return types.XBooleanTrue
}
// Or returns whether if any of the passed in arguments are truthy
//
// @(or(true)) -> true
// @(or(true, false, true)) -> true
//
// @function or(tests...)
func Or(env utils.Environment, args ...types.XValue) types.XValue {
for _, arg := range args {
asBool, xerr := types.ToXBoolean(env, arg)
if xerr != nil {
return xerr
}
if asBool.Native() {
return types.XBooleanTrue
}
}
return types.XBooleanFalse
}
// If evaluates the `test` argument, and if truthy returns `true_value`, if not returning `false_value`
//
// If the first argument is an error that error is returned
//
// @(if(1 = 1, "foo", "bar")) -> foo
// @(if("foo" > "bar", "foo", "bar")) -> ERROR
//
// @function if(test, true_value, false_value)
func If(env utils.Environment, test types.XValue, arg1 types.XValue, arg2 types.XValue) types.XValue {
asBool, err := types.ToXBoolean(env, test)
if err != nil {
return err
}
if asBool.Native() {
return arg1
}
return arg2
}
//------------------------------------------------------------------------------------------
// Text Functions
//------------------------------------------------------------------------------------------
// Code returns the numeric code for the first character in `text`, it is the inverse of char
//
// @(code("a")) -> 97
// @(code("abc")) -> 97
// @(code("😀")) -> 128512
// @(code("15")) -> 49
// @(code(15)) -> 49
// @(code("")) -> ERROR
//
// @function code(text)
func Code(env utils.Environment, text types.XText) types.XValue {
if text.Length() == 0 {
return types.NewXErrorf("requires a string of at least one character")
}
r, _ := utf8.DecodeRuneInString(text.Native())
return types.NewXNumberFromInt(int(r))
}
// Split splits `text` based on the characters in `delimiters`
//
// Empty values are removed from the returned list
//
// @(split("a b c", " ")) -> ["a","b","c"]
// @(split("a", " ")) -> ["a"]
// @(split("abc..d", ".")) -> ["abc","d"]
// @(split("a.b.c.", ".")) -> ["a","b","c"]
// @(split("a|b,c d", " .|,")) -> ["a","b","c","d"]
//
// @function split(text, delimiters)
func Split(env utils.Environment, text types.XText, delimiters types.XText) types.XValue {
splits := types.NewXArray()
allSplits := utils.TokenizeStringByChars(text.Native(), delimiters.Native())
for i := range allSplits {
splits.Append(types.NewXText(allSplits[i]))
}
return splits
}
// Join joins the passed in `array` of strings with the passed in `delimiter`
//
// @(join(array("a", "b", "c"), "|")) -> a|b|c
// @(join(split("a.b.c", "."), " ")) -> a b c
//
// @function join(array, delimiter)
func Join(env utils.Environment, array types.XValue, delimiter types.XValue) types.XValue {
indexable, isIndexable := array.(types.XIndexable)
if !isIndexable {
return types.NewXErrorf("requires an indexable as its first argument")
}
sep, xerr := types.ToXText(env, delimiter)
if xerr != nil {
return xerr
}
var output bytes.Buffer
for i := 0; i < indexable.Length(); i++ {
if i > 0 {
output.WriteString(sep.Native())
}
itemAsStr, xerr := types.ToXText(env, indexable.Index(i))
if xerr != nil {
return xerr
}
output.WriteString(itemAsStr.Native())
}
return types.NewXText(output.String())
}
// Char returns the rune for the passed in codepoint, `num`, which may be unicode, this is the reverse of code
//
// @(char(33)) -> !
// @(char(128512)) -> 😀
// @(char("foo")) -> ERROR
//
// @function char(num)
func Char(env utils.Environment, num types.XNumber) types.XValue {
code, xerr := types.ToInteger(env, num)
if xerr != nil {
return xerr
}
return types.NewXText(string(rune(code)))
}
// Title titlecases the passed in `text`, capitalizing each word
//
// @(title("foo")) -> Foo
// @(title("ryan lewis")) -> Ryan Lewis
// @(title(123)) -> 123
//
// @function title(text)
func Title(env utils.Environment, text types.XText) types.XValue {
return types.NewXText(strings.Title(text.Native()))
}
// Word returns the word at the passed in `index` for the passed in `text`. There is an optional final
// parameter `delimiters` which is string of characters used to split the text into words.
//
// @(word("bee cat dog", 0)) -> bee
// @(word("bee.cat,dog", 0)) -> bee
// @(word("bee.cat,dog", 1)) -> cat
// @(word("bee.cat,dog", 2)) -> dog
// @(word("bee.cat,dog", -1)) -> dog
// @(word("bee.cat,dog", -2)) -> cat
// @(word("bee.*cat,dog", 1, ".*=|")) -> cat,dog
// @(word("O'Grady O'Flaggerty", 1, " ")) -> O'Flaggerty
//
// @function word(text, index [,delimiters])
func Word(env utils.Environment, text types.XText, args ...types.XValue) types.XValue {
index, xerr := types.ToInteger(env, args[0])
if xerr != nil {
return xerr
}
var words []string
if len(args) == 2 && args[1] != nil {
delimiters, xerr := types.ToXText(env, args[1])
if xerr != nil {
return xerr
}
words = utils.TokenizeStringByChars(text.Native(), delimiters.Native())
} else {
words = utils.TokenizeString(text.Native())
}
offset := index
if offset < 0 {
offset += len(words)
}
if !(offset >= 0 && offset < len(words)) {
return types.NewXErrorf("index %d is out of range for the number of words %d", index, len(words))
}
return types.NewXText(words[offset])
}
// RemoveFirstWord removes the 1st word of `text`
//
// @(remove_first_word("foo bar")) -> bar
//
// @function remove_first_word(text)
func RemoveFirstWord(env utils.Environment, text types.XText) types.XValue {
words := utils.TokenizeString(text.Native())
if len(words) > 1 {
return types.NewXText(strings.Join(words[1:], " "))
}
return types.XTextEmpty
}
// WordSlice extracts a substring from `text` spanning from `start` up to but not-including `end`. (first word is 0). A negative
// end value means that all words after the start should be returned. There is an optional final parameter `delimiters`
// which is string of characters used to split the text into words.
//
// @(word_slice("bee cat dog", 0, 1)) -> bee
// @(word_slice("bee cat dog", 0, 2)) -> bee cat
// @(word_slice("bee cat dog", 1, -1)) -> cat dog
// @(word_slice("bee cat dog", 1)) -> cat dog
// @(word_slice("bee cat dog", 2, 3)) -> dog
// @(word_slice("bee cat dog", 3, 10)) ->
// @(word_slice("bee.*cat,dog", 1, -1, ".*=|,")) -> cat dog
// @(word_slice("O'Grady O'Flaggerty", 1, 2, " ")) -> O'Flaggerty
//
// @function word_slice(text, start, end [,delimiters])
func WordSlice(env utils.Environment, text types.XText, args ...types.XValue) types.XValue {
start, xerr := types.ToInteger(env, args[0])
if xerr != nil {
return xerr
}
if start < 0 {
return types.NewXErrorf("must start with a positive index")
}
end := -1
if len(args) == 2 {
if end, xerr = types.ToInteger(env, args[1]); xerr != nil {
return xerr
}
}
if end > 0 && end <= start {
return types.NewXErrorf("must have a end which is greater than the start")
}
var words []string
if len(args) == 3 && args[2] != nil {
delimiters, xerr := types.ToXText(env, args[2])
if xerr != nil {
return xerr
}
words = utils.TokenizeStringByChars(text.Native(), delimiters.Native())
} else {
words = utils.TokenizeString(text.Native())
}
if start >= len(words) {
return types.XTextEmpty
}
if end >= len(words) {
end = len(words)
}
if end > 0 {
return types.NewXText(strings.Join(words[start:end], " "))
}
return types.NewXText(strings.Join(words[start:], " "))
}
// WordCount returns the number of words in `text`. There is an optional final parameter `delimiters`
// which is string of characters used to split the text into words.
//
// @(word_count("foo bar")) -> 2
// @(word_count(10)) -> 1
// @(word_count("")) -> 0
// @(word_count("😀😃😄😁")) -> 4
// @(word_count("bee.*cat,dog", ".*=|")) -> 2
// @(word_count("O'Grady O'Flaggerty", " ")) -> 2
//
// @function word_count(text [,delimiters])
func WordCount(env utils.Environment, text types.XText, args ...types.XValue) types.XValue {
var words []string
if len(args) == 1 && args[0] != nil {
delimiters, xerr := types.ToXText(env, args[0])
if xerr != nil {
return xerr
}
words = utils.TokenizeStringByChars(text.Native(), delimiters.Native())
} else {
words = utils.TokenizeString(text.Native())
}
return types.NewXNumberFromInt(len(words))
}
// Field splits `text` based on the passed in `delimiter` and returns the field at `offset`. When splitting
// with a space, the delimiter is considered to be all whitespace. (first field is 0)
//
// @(field("a,b,c", 1, ",")) -> b
// @(field("a,,b,c", 1, ",")) ->
// @(field("a b c", 1, " ")) -> b
// @(field("a b c d", 1, " ")) ->
// @(field("a\t\tb\tc\td", 1, " ")) ->
// @(field("a,b,c", "foo", ",")) -> ERROR
//
// @function field(text, offset, delimiter)
func Field(env utils.Environment, text types.XText, args ...types.XValue) types.XValue {
field, xerr := types.ToInteger(env, args[0])
if xerr != nil {
return xerr
}
if field < 0 {
return types.NewXErrorf("cannot use a negative index to FIELD")
}
sep, xerr := types.ToXText(env, args[1])
if xerr != nil {
return xerr
}
fields := strings.Split(text.Native(), sep.Native())
// when using a space as a delimiter, we consider it splitting on whitespace, so remove empty values
if sep.Native() == " " {
var newFields []string
for _, f := range fields {
if f != "" {
newFields = append(newFields, f)
}
}
fields = newFields
}
if field >= len(fields) {
return types.XTextEmpty
}
return types.NewXText(strings.TrimSpace(fields[field]))
}
// Clean strips any non-printable characters from `text`
//
// @(clean("😃 Hello \nwo\tr\rld")) -> 😃 Hello world
// @(clean(123)) -> 123
//
// @function clean(text)
func Clean(env utils.Environment, text types.XText) types.XValue {
return types.NewXText(nonPrintableRegex.ReplaceAllString(text.Native(), ""))
}
// Left returns the `count` most left characters of the passed in `text`
//
// @(left("hello", 2)) -> he
// @(left("hello", 7)) -> hello
// @(left("😀😃😄😁", 2)) -> 😀😃
// @(left("hello", -1)) -> ERROR
//
// @function left(text, count)
func Left(env utils.Environment, text types.XText, count int) types.XValue {
if count < 0 {
return types.NewXErrorf("can't take a negative count")
}
// this weird construct does the right thing for multi-byte unicode
var output bytes.Buffer
i := 0
for _, r := range text.Native() {
if i >= count {
break
}
output.WriteRune(r)
i++
}
return types.NewXText(output.String())
}
// Lower lowercases the passed in `text`
//
// @(lower("HellO")) -> hello
// @(lower("hello")) -> hello
// @(lower("123")) -> 123
// @(lower("😀")) -> 😀
//
// @function lower(text)
func Lower(env utils.Environment, text types.XText) types.XValue {
return types.NewXText(strings.ToLower(text.Native()))
}
// Right returns the `count` most right characters of the passed in `text`
//
// @(right("hello", 2)) -> lo
// @(right("hello", 7)) -> hello
// @(right("😀😃😄😁", 2)) -> 😄😁
// @(right("hello", -1)) -> ERROR
//
// @function right(text, count)
func Right(env utils.Environment, text types.XText, count int) types.XValue {
if count < 0 {
return types.NewXErrorf("can't take a negative count")
}
start := utf8.RuneCountInString(text.Native()) - count
// this weird construct does the right thing for multi-byte unicode
var output bytes.Buffer
i := 0
for _, r := range text.Native() {
if i >= start {
output.WriteRune(r)
}
i++
}
return types.NewXText(output.String())
}
// TextCompare returns the comparison between the strings `text1` and `text2`.
// The return value will be -1 if str1 is smaller than str2, 0 if they
// are equal and 1 if str1 is greater than str2
//
// @(text_compare("abc", "abc")) -> 0
// @(text_compare("abc", "def")) -> -1
// @(text_compare("zzz", "aaa")) -> 1
//
// @function text_compare(text1, text2)
func TextCompare(env utils.Environment, text1 types.XText, text2 types.XText) types.XValue {
return types.NewXNumberFromInt(text1.Compare(text2))
}
// Repeat return `text` repeated `count` number of times
//
// @(repeat("*", 8)) -> ********
// @(repeat("*", "foo")) -> ERROR
//
// @function repeat(text, count)
func Repeat(env utils.Environment, text types.XText, count int) types.XValue {
if count < 0 {
return types.NewXErrorf("must be called with a positive integer, got %d", count)
}
var output bytes.Buffer
for j := 0; j < count; j++ {
output.WriteString(text.Native())
}
return types.NewXText(output.String())
}
// Replace replaces all occurrences of `needle` with `replacement` in `text`
//
// @(replace("foo bar", "foo", "zap")) -> zap bar
// @(replace("foo bar", "baz", "zap")) -> foo bar
//
// @function replace(text, needle, replacement)
func Replace(env utils.Environment, text types.XText, needle types.XText, replacement types.XText) types.XValue {
return types.NewXText(strings.Replace(text.Native(), needle.Native(), replacement.Native(), -1))
}
// Upper uppercases all characters in the passed `text`
//
// @(upper("Asdf")) -> ASDF
// @(upper(123)) -> 123
//
// @function upper(text)
func Upper(env utils.Environment, text types.XText) types.XValue {
return types.NewXText(strings.ToUpper(text.Native()))
}
// Percent converts `num` to text represented as a percentage
//
// @(percent(0.54234)) -> 54%
// @(percent(1.2)) -> 120%
// @(percent("foo")) -> ERROR
//
// @function percent(num)
func Percent(env utils.Environment, num types.XNumber) types.XValue {
// multiply by 100 and floor
percent := num.Native().Mul(decimal.NewFromFloat(100)).Round(0)
// add on a %
return types.NewXText(fmt.Sprintf("%d%%", percent.IntPart()))
}
// URLEncode URL encodes `text` for use in a URL parameter
//
// @(url_encode("two words")) -> two+words
// @(url_encode(10)) -> 10
//
// @function url_encode(text)
func URLEncode(env utils.Environment, text types.XText) types.XValue {
return types.NewXText(url.QueryEscape(text.Native()))
}
//------------------------------------------------------------------------------------------
// Number Functions
//------------------------------------------------------------------------------------------
// Abs returns the absolute value of `num`
//
// @(abs(-10)) -> 10
// @(abs(10.5)) -> 10.5
// @(abs("foo")) -> ERROR
//
// @function abs(num)
func Abs(env utils.Environment, num types.XNumber) types.XValue {
return types.NewXNumber(num.Native().Abs())
}
// Round rounds `num` to the nearest value. You can optionally pass in the number of decimal places to round to as `places`.
//
// If places < 0, it will round the integer part to the nearest 10^(-places).
//
// @(round(12)) -> 12
// @(round(12.141)) -> 12
// @(round(12.6)) -> 13
// @(round(12.141, 2)) -> 12.14
// @(round(12.146, 2)) -> 12.15
// @(round(12.146, -1)) -> 10
// @(round("notnum", 2)) -> ERROR
//
// @function round(num [,places])
func Round(env utils.Environment, num types.XNumber, places int) types.XValue {
return types.NewXNumber(num.Native().Round(int32(places)))
}
// RoundUp rounds `num` up to the nearest integer value. You can optionally pass in the number of decimal places to round to as `places`.
//
// @(round_up(12)) -> 12
// @(round_up(12.141)) -> 13
// @(round_up(12.6)) -> 13
// @(round_up(12.141, 2)) -> 12.15
// @(round_up(12.146, 2)) -> 12.15
// @(round_up("foo")) -> ERROR
//
// @function round_up(num [,places])
func RoundUp(env utils.Environment, num types.XNumber, places int) types.XValue {
dec := num.Native()
if dec.Round(int32(places)).Equal(dec) {
return num
}
halfPrecision := decimal.New(5, -int32(places)-1)
roundedDec := dec.Add(halfPrecision).Round(int32(places))
return types.NewXNumber(roundedDec)
}
// RoundDown rounds `num` down to the nearest integer value. You can optionally pass in the number of decimal places to round to as `places`.
//
// @(round_down(12)) -> 12
// @(round_down(12.141)) -> 12
// @(round_down(12.6)) -> 12
// @(round_down(12.141, 2)) -> 12.14
// @(round_down(12.146, 2)) -> 12.14
// @(round_down("foo")) -> ERROR
//
// @function round_down(num [,places])
func RoundDown(env utils.Environment, num types.XNumber, places int) types.XValue {
dec := num.Native()
if dec.Round(int32(places)).Equal(dec) {
return num
}
halfPrecision := decimal.New(5, -int32(places)-1)
roundedDec := dec.Sub(halfPrecision).Round(int32(places))
return types.NewXNumber(roundedDec)
}
// Max takes a list of `values` and returns the greatest of them
//
// @(max(1, 2)) -> 2
// @(max(1, -1, 10)) -> 10
// @(max(1, 10, "foo")) -> ERROR
//
// @function max(values...)
func Max(env utils.Environment, args ...types.XValue) types.XValue {
max, xerr := types.ToXNumber(env, args[0])
if xerr != nil {
return xerr
}
for _, v := range args[1:] {
val, xerr := types.ToXNumber(env, v)
if xerr != nil {
return xerr
}
if val.Compare(max) > 0 {
max = val
}
}
return max
}
// Min takes a list of `values` and returns the smallest of them
//
// @(min(1, 2)) -> 1
// @(min(2, 2, -10)) -> -10
// @(min(1, 2, "foo")) -> ERROR
//
// @function min(values)
func Min(env utils.Environment, args ...types.XValue) types.XValue {
max, xerr := types.ToXNumber(env, args[0])
if xerr != nil {
return xerr
}
for _, v := range args[1:] {
val, xerr := types.ToXNumber(env, v)
if xerr != nil {
return xerr
}
if val.Compare(max) < 0 {
max = val
}
}
return max
}
// Mean takes a list of `values` and returns the arithmetic mean of them
//
// @(mean(1, 2)) -> 1.5
// @(mean(1, 2, 6)) -> 3
// @(mean(1, "foo")) -> ERROR
//
// @function mean(values)
func Mean(env utils.Environment, args ...types.XValue) types.XValue {
sum := decimal.Zero
for _, val := range args {
num, xerr := types.ToXNumber(env, val)
if xerr != nil {
return xerr
}
sum = sum.Add(num.Native())
}
return types.NewXNumber(sum.Div(decimal.New(int64(len(args)), 0)))
}
// Mod returns the remainder of the division of `divident` by `divisor`
//
// @(mod(5, 2)) -> 1
// @(mod(4, 2)) -> 0
// @(mod(5, "foo")) -> ERROR
//
// @function mod(dividend, divisor)
func Mod(env utils.Environment, num1 types.XNumber, num2 types.XNumber) types.XValue {
return types.NewXNumber(num1.Native().Mod(num2.Native()))
}
// Rand returns a single random number between [0.0-1.0).
//
// @(rand()) -> 0.3849275689214193274523267973563633859157562255859375
// @(rand()) -> 0.607552015674623913099594574305228888988494873046875
//
// @function rand()
func Rand(env utils.Environment) types.XValue {
return types.NewXNumber(utils.RandDecimal())
}
// RandBetween a single random integer in the given inclusive range.
//
// @(rand_between(1, 10)) -> 5
// @(rand_between(1, 10)) -> 10
//
// @function rand_between()
func RandBetween(env utils.Environment, min types.XNumber, max types.XNumber) types.XValue {
span := (max.Native().Sub(min.Native())).Add(decimal.New(1, 0))
val := utils.RandDecimal().Mul(span).Add(min.Native()).Floor()
return types.NewXNumber(val)
}
//------------------------------------------------------------------------------------------
// Date & Time Functions
//------------------------------------------------------------------------------------------
// ParseDateTime turns `text` into a date according to the `format` and optional `timezone` specified
//
// The format string can consist of the following characters. The characters
// ' ', ':', ',', 'T', '-' and '_' are ignored. Any other character is an error.
//
// * `YY` - last two digits of year 0-99
// * `YYYY` - four digits of year 0000-9999
// * `M` - month 1-12
// * `MM` - month 01-12
// * `D` - day of month, 1-31
// * `DD` - day of month, zero padded 0-31
// * `h` - hour of the day 1-12
// * `hh` - hour of the day 01-12
// * `tt` - twenty four hour of the day 01-23
// * `m` - minute 0-59
// * `mm` - minute 00-59
// * `s` - second 0-59
// * `ss` - second 00-59
// * `fff` - milliseconds
// * `ffffff` - microseconds
// * `fffffffff` - nanoseconds
// * `aa` - am or pm
// * `AA` - AM or PM
// * `Z` - hour and minute offset from UTC, or Z for UTC
// * `ZZZ` - hour and minute offset from UTC
//
// Timezone should be a location name as specified in the IANA Time Zone database, such
// as "America/Guayaquil" or "America/Los_Angeles". If not specified the timezone of your
// environment will be used. An error will be returned if the timezone is not recognized.
//
// Note that fractional seconds will be parsed even without an explicit format identifier.
// You should only specify fractional seconds when you want to assert the number of places
// in the input format.
//
// parse_datetime will return an error if it is unable to convert the text to a datetime.
//
// @(parse_datetime("1979-07-18", "YYYY-MM-DD")) -> 1979-07-18T00:00:00.000000-05:00
// @(parse_datetime("2010 5 10", "YYYY M DD")) -> 2010-05-10T00:00:00.000000-05:00
// @(parse_datetime("2010 5 10 12:50", "YYYY M DD tt:mm", "America/Los_Angeles")) -> 2010-05-10T12:50:00.000000-07:00
// @(parse_datetime("NOT DATE", "YYYY-MM-DD")) -> ERROR
//
// @function parse_datetime(text, format [,timezone])
func ParseDateTime(env utils.Environment, args ...types.XValue) types.XValue {
str, xerr := types.ToXText(env, args[0])
if xerr != nil {
return xerr
}
format, xerr := types.ToXText(env, args[1])
if xerr != nil {
return xerr
}
// try to turn it to a go format
goFormat, err := utils.ToGoDateFormat(format.Native(), utils.DateTimeFormatting)
if err != nil {
return types.NewXError(err)
}
// grab our location
location := env.Timezone()
if len(args) == 3 {
tzStr, xerr := types.ToXText(env, args[2])
if xerr != nil {
return xerr
}
location, err = time.LoadLocation(tzStr.Native())
if err != nil {
return types.NewXError(err)
}
}
// finally try to parse the date
parsed, err := time.ParseInLocation(goFormat, str.Native(), location)
if err != nil {
return types.NewXError(err)
}
return types.NewXDateTime(parsed.In(location))
}
// DateTimeFromParts converts the passed in `year`, `month` and `day`
//
// @(datetime_from_parts(2017, 1, 15)) -> 2017-01-15T00:00:00.000000-05:00
// @(datetime_from_parts(2017, 2, 31)) -> 2017-03-03T00:00:00.000000-05:00
// @(datetime_from_parts(2017, 13, 15)) -> ERROR
//
// @function datetime_from_parts(year, month, day)
func DateTimeFromParts(env utils.Environment, args ...types.XValue) types.XValue {
year, xerr := types.ToInteger(env, args[0])
if xerr != nil {
return xerr
}
month, xerr := types.ToInteger(env, args[1])
if xerr != nil {
return xerr
}
if month < 1 || month > 12 {
return types.NewXErrorf("invalid value for month, must be 1-12")
}
day, xerr := types.ToInteger(env, args[2])
if xerr != nil {
return xerr
}
return types.NewXDateTime(time.Date(year, time.Month(month), day, 0, 0, 0, 0, env.Timezone()))
}
// DateTimeDiff returns the integer duration between `date1` and `date2` in the `unit` specified.
//