amis-formula 1.3.13 → 2.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1938 @@
1
+ /**
2
+ * @file 公式内置函数
3
+ */
4
+
5
+ import moment from 'moment';
6
+ import upperFirst from 'lodash/upperFirst';
7
+ import padStart from 'lodash/padStart';
8
+ import capitalize from 'lodash/capitalize';
9
+ import escape from 'lodash/escape';
10
+ import truncate from 'lodash/truncate';
11
+
12
+ export interface FilterMap {
13
+ [propName: string]: (this: FilterContext, input: any, ...args: any[]) => any;
14
+ }
15
+
16
+ export interface FunctionMap {
17
+ [propName: string]: (this: Evaluator, ast: Object, data: any) => any;
18
+ }
19
+
20
+ export interface FilterContext {
21
+ data: Object;
22
+ filter?: {
23
+ name: string;
24
+ args: Array<any>;
25
+ };
26
+ restFilters: Array<{
27
+ name: string;
28
+ args: Array<any>;
29
+ }>;
30
+ }
31
+
32
+ export interface EvaluatorOptions {
33
+ /**
34
+ * 可以外部传入 ast 节点处理器,定制或者扩充自定义函数
35
+ */
36
+ functions?: FunctionMap;
37
+
38
+ /**
39
+ * 可以外部扩充 filter
40
+ */
41
+ filters?: FilterMap;
42
+
43
+ defaultFilter?: string;
44
+ }
45
+
46
+ export class Evaluator {
47
+ readonly filters: FilterMap;
48
+ readonly functions: FunctionMap = {};
49
+ readonly context: {
50
+ [propName: string]: any;
51
+ };
52
+ contextStack: Array<(varname: string) => any> = [];
53
+
54
+ static defaultFilters: FilterMap = {};
55
+ static setDefaultFilters(filters: FilterMap) {
56
+ Evaluator.defaultFilters = {
57
+ ...Evaluator.defaultFilters,
58
+ ...filters
59
+ };
60
+ }
61
+
62
+ constructor(
63
+ context: {
64
+ [propName: string]: any;
65
+ },
66
+ readonly options: EvaluatorOptions = {
67
+ defaultFilter: 'html'
68
+ }
69
+ ) {
70
+ this.context = context;
71
+ this.contextStack.push((varname: string) =>
72
+ varname === '&' ? context : context?.[varname]
73
+ );
74
+
75
+ this.filters = {
76
+ ...Evaluator.defaultFilters,
77
+ ...this.filters,
78
+ ...options?.filters
79
+ };
80
+ this.functions = {
81
+ ...this.functions,
82
+ ...options?.functions
83
+ };
84
+ }
85
+
86
+ // 主入口
87
+ evalute(ast: any) {
88
+ if (ast && ast.type) {
89
+ const name = (ast.type as string).replace(/(?:_|\-)(\w)/g, (_, l) =>
90
+ l.toUpperCase()
91
+ );
92
+ const fn = this.functions[name] || (this as any)[name];
93
+
94
+ if (!fn) {
95
+ throw new Error(`${ast.type} unkown.`);
96
+ }
97
+
98
+ return fn.call(this, ast);
99
+ } else {
100
+ return ast;
101
+ }
102
+ }
103
+
104
+ document(ast: {type: 'document'; body: Array<any>}) {
105
+ if (!ast.body.length) {
106
+ return undefined;
107
+ }
108
+ const isString = ast.body.length > 1;
109
+ const content = ast.body.map(item => {
110
+ let result = this.evalute(item);
111
+
112
+ if (isString && result == null) {
113
+ // 不要出现 undefined, null 之类的文案
114
+ return '';
115
+ }
116
+
117
+ return result;
118
+ });
119
+ return content.length === 1 ? content[0] : content.join('');
120
+ }
121
+
122
+ filter(ast: {
123
+ type: 'filter';
124
+ input: any;
125
+ filters: Array<{name: string; args: Array<any>}>;
126
+ }) {
127
+ let input = this.evalute(ast.input);
128
+ const filters = ast.filters.concat();
129
+ const context: FilterContext = {
130
+ filter: undefined,
131
+ data: this.context,
132
+ restFilters: filters
133
+ };
134
+
135
+ while (filters.length) {
136
+ const filter = filters.shift()!;
137
+ const fn = this.filters[filter.name];
138
+ if (!fn) {
139
+ throw new Error(`filter \`${filter.name}\` not exits`);
140
+ }
141
+ context.filter = filter;
142
+ input = fn.apply(
143
+ context,
144
+ [input].concat(
145
+ filter.args.map((item: any) => {
146
+ if (item?.type === 'mixed') {
147
+ return item.body
148
+ .map((item: any) =>
149
+ typeof item === 'string' ? item : this.evalute(item)
150
+ )
151
+ .join('');
152
+ } else if (item.type) {
153
+ return this.evalute(item);
154
+ }
155
+ return item;
156
+ })
157
+ )
158
+ );
159
+ }
160
+ return input;
161
+ }
162
+
163
+ raw(ast: {type: 'raw'; value: string}) {
164
+ return ast.value;
165
+ }
166
+
167
+ script(ast: {type: 'script'; body: any}) {
168
+ const defaultFilter = this.options.defaultFilter;
169
+
170
+ // 只给简单的变量取值用法自动补fitler
171
+ if (defaultFilter && ~['getter', 'variable'].indexOf(ast.body?.type)) {
172
+ ast.body = {
173
+ type: 'filter',
174
+ input: ast.body,
175
+ filters: [
176
+ {
177
+ name: defaultFilter.replace(/^\s*\|\s*/, ''),
178
+ args: []
179
+ }
180
+ ]
181
+ };
182
+ }
183
+
184
+ return this.evalute(ast.body);
185
+ }
186
+
187
+ expressionList(ast: {type: 'expression-list'; body: Array<any>}) {
188
+ return ast.body.reduce((prev, current) => this.evalute(current));
189
+ }
190
+
191
+ template(ast: {type: 'template'; body: Array<any>}) {
192
+ return ast.body.map(arg => this.evalute(arg)).join('');
193
+ }
194
+
195
+ templateRaw(ast: {type: 'template_raw'; value: any}) {
196
+ return ast.value;
197
+ }
198
+
199
+ // 下标获取
200
+ getter(ast: {host: any; key: any}) {
201
+ const host = this.evalute(ast.host);
202
+ let key = this.evalute(ast.key);
203
+ if (typeof key === 'undefined' && ast.key?.type === 'variable') {
204
+ key = ast.key.name;
205
+ }
206
+ return host?.[key];
207
+ }
208
+
209
+ // 位操作如 +2 ~3 !
210
+ unary(ast: {op: '+' | '-' | '~' | '!'; value: any}) {
211
+ let value = this.evalute(ast.value);
212
+
213
+ switch (ast.op) {
214
+ case '+':
215
+ return +value;
216
+ case '-':
217
+ return -value;
218
+ case '~':
219
+ return ~value;
220
+ case '!':
221
+ return !value;
222
+ }
223
+ }
224
+
225
+ formatNumber(value: any, int = false) {
226
+ const typeName = typeof value;
227
+ if (typeName === 'string') {
228
+ return (int ? parseInt(value, 10) : parseFloat(value)) || 0;
229
+ } else if (typeName === 'number' && int) {
230
+ return Math.round(value);
231
+ }
232
+
233
+ return value ?? 0;
234
+ }
235
+
236
+ power(ast: {left: any; right: any}) {
237
+ const left = this.evalute(ast.left);
238
+ const right = this.evalute(ast.right);
239
+ return Math.pow(this.formatNumber(left), this.formatNumber(right));
240
+ }
241
+
242
+ multiply(ast: {left: any; right: any}) {
243
+ const left = this.evalute(ast.left);
244
+ const right = this.evalute(ast.right);
245
+ return stripNumber(this.formatNumber(left) * this.formatNumber(right));
246
+ }
247
+
248
+ divide(ast: {left: any; right: any}) {
249
+ const left = this.evalute(ast.left);
250
+ const right = this.evalute(ast.right);
251
+ return stripNumber(this.formatNumber(left) / this.formatNumber(right));
252
+ }
253
+
254
+ remainder(ast: {left: any; right: any}) {
255
+ const left = this.evalute(ast.left);
256
+ const right = this.evalute(ast.right);
257
+ return this.formatNumber(left) % this.formatNumber(right);
258
+ }
259
+
260
+ add(ast: {left: any; right: any}) {
261
+ const left = this.evalute(ast.left);
262
+ const right = this.evalute(ast.right);
263
+ return stripNumber(this.formatNumber(left) + this.formatNumber(right));
264
+ }
265
+
266
+ minus(ast: {left: any; right: any}) {
267
+ const left = this.evalute(ast.left);
268
+ const right = this.evalute(ast.right);
269
+ return stripNumber(this.formatNumber(left) - this.formatNumber(right));
270
+ }
271
+
272
+ shift(ast: {op: '<<' | '>>' | '>>>'; left: any; right: any}) {
273
+ const left = this.evalute(ast.left);
274
+ const right = this.formatNumber(this.evalute(ast.right), true);
275
+
276
+ if (ast.op === '<<') {
277
+ return left << right;
278
+ } else if (ast.op == '>>') {
279
+ return left >> right;
280
+ } else {
281
+ return left >>> right;
282
+ }
283
+ }
284
+
285
+ lt(ast: {left: any; right: any}) {
286
+ const left = this.evalute(ast.left);
287
+ const right = this.evalute(ast.right);
288
+
289
+ // todo 如果是日期的对比,这个地方可以优化一下。
290
+
291
+ return left < right;
292
+ }
293
+
294
+ gt(ast: {left: any; right: any}) {
295
+ const left = this.evalute(ast.left);
296
+ const right = this.evalute(ast.right);
297
+
298
+ // todo 如果是日期的对比,这个地方可以优化一下。
299
+ return left > right;
300
+ }
301
+
302
+ le(ast: {left: any; right: any}) {
303
+ const left = this.evalute(ast.left);
304
+ const right = this.evalute(ast.right);
305
+
306
+ // todo 如果是日期的对比,这个地方可以优化一下。
307
+
308
+ return left <= right;
309
+ }
310
+
311
+ ge(ast: {left: any; right: any}) {
312
+ const left = this.evalute(ast.left);
313
+ const right = this.evalute(ast.right);
314
+
315
+ // todo 如果是日期的对比,这个地方可以优化一下。
316
+
317
+ return left >= right;
318
+ }
319
+
320
+ eq(ast: {left: any; right: any}) {
321
+ const left = this.evalute(ast.left);
322
+ const right = this.evalute(ast.right);
323
+
324
+ // todo 如果是日期的对比,这个地方可以优化一下。
325
+
326
+ return left == right;
327
+ }
328
+
329
+ ne(ast: {left: any; right: any}) {
330
+ const left = this.evalute(ast.left);
331
+ const right = this.evalute(ast.right);
332
+
333
+ // todo 如果是日期的对比,这个地方可以优化一下。
334
+
335
+ return left != right;
336
+ }
337
+
338
+ streq(ast: {left: any; right: any}) {
339
+ const left = this.evalute(ast.left);
340
+ const right = this.evalute(ast.right);
341
+
342
+ // todo 如果是日期的对比,这个地方可以优化一下。
343
+
344
+ return left === right;
345
+ }
346
+
347
+ strneq(ast: {left: any; right: any}) {
348
+ const left = this.evalute(ast.left);
349
+ const right = this.evalute(ast.right);
350
+
351
+ // todo 如果是日期的对比,这个地方可以优化一下。
352
+
353
+ return left !== right;
354
+ }
355
+
356
+ binary(ast: {op: '&' | '^' | '|'; left: any; right: any}) {
357
+ const left = this.evalute(ast.left);
358
+ const right = this.evalute(ast.right);
359
+
360
+ if (ast.op === '&') {
361
+ return left & right;
362
+ } else if (ast.op === '^') {
363
+ return left ^ right;
364
+ } else {
365
+ return left | right;
366
+ }
367
+ }
368
+
369
+ and(ast: {left: any; right: any}) {
370
+ const left = this.evalute(ast.left);
371
+ return left && this.evalute(ast.right);
372
+ }
373
+
374
+ or(ast: {left: any; right: any}) {
375
+ const left = this.evalute(ast.left);
376
+ return left || this.evalute(ast.right);
377
+ }
378
+
379
+ number(ast: {value: any; raw: string}) {
380
+ // todo 以后可以在这支持大数字。
381
+ return ast.value;
382
+ }
383
+
384
+ nsVariable(ast: {namespace: string; body: any}) {
385
+ if (ast.namespace === 'window') {
386
+ this.contextStack.push((name: string) =>
387
+ name === '&' ? window : (window as any)[name]
388
+ );
389
+ } else if (ast.namespace === 'cookie') {
390
+ this.contextStack.push((name: string) => {
391
+ return getCookie(name);
392
+ });
393
+ } else if (ast.namespace === 'ls' || ast.namespace === 'ss') {
394
+ const ns = ast.namespace;
395
+ this.contextStack.push((name: string) => {
396
+ const raw =
397
+ ns === 'ss'
398
+ ? sessionStorage.getItem(name)
399
+ : localStorage.getItem(name);
400
+
401
+ if (typeof raw === 'string') {
402
+ // 判断字符串是否一个纯数字字符串,如果是,则对比parse后的值和原值是否相同,
403
+ // 如果不同则返回原值,因为原值如果是一个很长的纯数字字符串,则 parse 后可能会丢失精度
404
+ if (/^\d+$/.test(raw)) {
405
+ const parsed = JSON.parse(raw);
406
+ return `${parsed}` === raw ? parsed : raw;
407
+ }
408
+
409
+ return parseJson(raw, raw);
410
+ }
411
+
412
+ return undefined;
413
+ });
414
+ } else {
415
+ throw new Error('Unsupported namespace: ' + ast.namespace);
416
+ }
417
+
418
+ const result = this.evalute(ast.body);
419
+ this.contextStack.pop();
420
+ return result;
421
+ }
422
+
423
+ variable(ast: {name: string}) {
424
+ const contextGetter = this.contextStack[this.contextStack.length - 1];
425
+ return contextGetter(ast.name);
426
+ }
427
+
428
+ identifier(ast: {name: string}) {
429
+ return ast.name;
430
+ }
431
+
432
+ array(ast: {type: 'array'; members: Array<any>}) {
433
+ return ast.members.map(member => this.evalute(member));
434
+ }
435
+
436
+ literal(ast: {type: 'literal'; value: any}) {
437
+ return ast.value;
438
+ }
439
+
440
+ string(ast: {type: 'string'; value: string}) {
441
+ return ast.value;
442
+ }
443
+
444
+ object(ast: {members: Array<{key: string; value: any}>}) {
445
+ let object: any = {};
446
+ ast.members.forEach(({key, value}) => {
447
+ object[this.evalute(key)] = this.evalute(value);
448
+ });
449
+ return object;
450
+ }
451
+
452
+ conditional(ast: {
453
+ type: 'conditional';
454
+ test: any;
455
+ consequent: any;
456
+ alternate: any;
457
+ }) {
458
+ return this.evalute(ast.test)
459
+ ? this.evalute(ast.consequent)
460
+ : this.evalute(ast.alternate);
461
+ }
462
+
463
+ funcCall(this: any, ast: {identifier: string; args: Array<any>}) {
464
+ const fnName = `fn${ast.identifier}`;
465
+ const fn =
466
+ this.functions[fnName] || this[fnName] || this.filters[ast.identifier];
467
+
468
+ if (!fn) {
469
+ throw new Error(`${ast.identifier}函数没有定义`);
470
+ }
471
+
472
+ let args: Array<any> = ast.args;
473
+
474
+ // 逻辑函数特殊处理,因为有时候有些运算是可以跳过的。
475
+ if (~['IF', 'AND', 'OR', 'XOR', 'IFS'].indexOf(ast.identifier)) {
476
+ args = args.map(a => () => this.evalute(a));
477
+ } else {
478
+ args = args.map(a => this.evalute(a));
479
+ }
480
+
481
+ return fn.apply(this, args);
482
+ }
483
+
484
+ anonymousFunction(ast: any) {
485
+ return ast;
486
+ }
487
+
488
+ callAnonymousFunction(
489
+ ast: {
490
+ args: any[];
491
+ return: any;
492
+ },
493
+ args: Array<any>
494
+ ) {
495
+ const ctx: any = createObject(
496
+ this.contextStack[this.contextStack.length - 1]('&') || {},
497
+ {}
498
+ );
499
+ ast.args.forEach((arg: any) => {
500
+ if (arg.type !== 'variable') {
501
+ throw new Error('expected a variable as argument');
502
+ }
503
+ ctx[arg.name] = args.shift();
504
+ });
505
+ this.contextStack.push((varName: string) =>
506
+ varName === '&' ? ctx : ctx[varName]
507
+ );
508
+ const result = this.evalute(ast.return);
509
+ this.contextStack.pop();
510
+ return result;
511
+ }
512
+
513
+ /**
514
+ * 示例:IF(A, B, C)
515
+ *
516
+ * 如果满足条件A,则返回B,否则返回C,支持多层嵌套IF函数。
517
+ *
518
+ * 也可以用表达式如:A ? B : C
519
+ *
520
+ * @example IF(condition, consequent, alternate)
521
+ * @param {expression} condition - 条件表达式.
522
+ * @param {any} consequent 条件判断通过的返回结果
523
+ * @param {any} alternate 条件判断不通过的返回结果
524
+ * @namespace 逻辑函数
525
+ *
526
+ * @returns {any} 根据条件返回不同的结果
527
+ */
528
+ fnIF(condition: () => any, trueValue: () => any, falseValue: () => any) {
529
+ return condition() ? trueValue() : falseValue();
530
+ }
531
+
532
+ /**
533
+ * 条件全部符合,返回 true,否则返回 false
534
+ *
535
+ * 示例:AND(语文成绩>80, 数学成绩>80)
536
+ *
537
+ * 语文成绩和数学成绩都大于 80,则返回 true,否则返回 false
538
+ *
539
+ * 也可以直接用表达式如:语文成绩>80 && 数学成绩>80
540
+ *
541
+ * @example AND(expression1, expression2, ...expressionN)
542
+ * @param {...expression} conditions - 条件表达式.
543
+ * @namespace 逻辑函数
544
+ *
545
+ * @returns {boolean}
546
+ */
547
+ fnAND(...condtions: Array<() => any>) {
548
+ return condtions.every(c => c());
549
+ }
550
+
551
+ /**
552
+ * 条件任意一个满足条件,返回 true,否则返回 false
553
+ *
554
+ * 示例:OR(语文成绩>80, 数学成绩>80)
555
+ *
556
+ * 语文成绩和数学成绩任意一个大于 80,则返回 true,否则返回 false
557
+ *
558
+ * 也可以直接用表达式如:语文成绩>80 || 数学成绩>80
559
+ *
560
+ * @example OR(expression1, expression2, ...expressionN)
561
+ * @param {...expression} conditions - 条件表达式.
562
+ * @namespace 逻辑函数
563
+ *
564
+ * @returns {boolean}
565
+ */
566
+ fnOR(...condtions: Array<() => any>) {
567
+ return condtions.some(c => c());
568
+ }
569
+
570
+ /**
571
+ * 异或处理,两个表达式同时为「真」,或者同时为「假」,则结果返回为「真」
572
+ *
573
+ * @example XOR(condition1, condition2)
574
+ * @param {expression} condition1 - 条件表达式1
575
+ * @param {expression} condition2 - 条件表达式2
576
+ * @namespace 逻辑函数
577
+ *
578
+ * @returns {boolean}
579
+ */
580
+ fnXOR(c1: () => any, c2: () => any) {
581
+ return !!c1() === !!c2();
582
+ }
583
+
584
+ /**
585
+ * 判断函数集合,相当于多个 else if 合并成一个。
586
+ *
587
+ * 示例:IFS(语文成绩 > 80, "优秀", 语文成绩 > 60, "良", "继续努力")
588
+ *
589
+ * 如果语文成绩大于 80,则返回优秀,否则判断大于 60 分,则返回良,否则返回继续努力。
590
+ *
591
+ * @example IFS(condition1, result1, condition2, result2,...conditionN, resultN)
592
+ * @param {...any} args - 条件,返回值集合
593
+ * @namespace 逻辑函数
594
+ * @returns {any} 第一个满足条件的结果,没有命中的返回 false。
595
+ */
596
+ fnIFS(...args: Array<() => any>) {
597
+ if (args.length % 2) {
598
+ args.splice(args.length - 1, 0, () => true);
599
+ }
600
+
601
+ while (args.length) {
602
+ const c = args.shift()!;
603
+ const v = args.shift()!;
604
+
605
+ if (c()) {
606
+ return v();
607
+ }
608
+ }
609
+ return;
610
+ }
611
+
612
+ /**
613
+ * 返回传入数字的绝对值
614
+ *
615
+ * @example ABS(num)
616
+ * @param {number} num - 数值
617
+ * @namespace 数学函数
618
+ *
619
+ * @returns {number} 传入数值的绝对值
620
+ */
621
+ fnABS(a: number) {
622
+ a = this.formatNumber(a);
623
+ return Math.abs(a);
624
+ }
625
+
626
+ /**
627
+ * 获取最大值,如果只有一个参数且是数组,则计算这个数组内的值
628
+ *
629
+ * @example MAX(num1, num2, ...numN)
630
+ * @param {...number} num - 数值
631
+ * @namespace 数学函数
632
+ *
633
+ * @returns {number} 所有传入值中最大的那个
634
+ */
635
+ fnMAX(...args: Array<any>) {
636
+ let arr = args;
637
+ if (args.length === 1 && Array.isArray(args[0])) {
638
+ arr = args[0];
639
+ }
640
+ return Math.max.apply(
641
+ Math,
642
+ arr.map(item => this.formatNumber(item))
643
+ );
644
+ }
645
+
646
+ /**
647
+ * 获取最小值,如果只有一个参数且是数组,则计算这个数组内的值
648
+ *
649
+ * @example MIN(num1, num2, ...numN)
650
+ * @param {...number} num - 数值
651
+ * @namespace 数学函数
652
+ *
653
+ * @returns {number} 所有传入值中最小的那个
654
+ */
655
+ fnMIN(...args: Array<number>) {
656
+ let arr = args;
657
+ if (args.length === 1 && Array.isArray(args[0])) {
658
+ arr = args[0];
659
+ }
660
+ return Math.min.apply(
661
+ Math,
662
+ arr.map(item => this.formatNumber(item))
663
+ );
664
+ }
665
+
666
+ /**
667
+ * 求和,如果只有一个参数且是数组,则计算这个数组内的值
668
+ *
669
+ * @example SUM(num1, num2, ...numN)
670
+ * @param {...number} num - 数值
671
+ * @namespace 数学函数
672
+ *
673
+ * @returns {number} 所有传入数值的总和
674
+ */
675
+ fnSUM(...args: Array<number>) {
676
+ let arr = args;
677
+ if (args.length === 1 && Array.isArray(args[0])) {
678
+ arr = args[0];
679
+ }
680
+ return arr.reduce((sum, a) => sum + this.formatNumber(a) || 0, 0);
681
+ }
682
+
683
+ /**
684
+ * 将数值向下取整为最接近的整数
685
+ *
686
+ * @example INT(num)
687
+ * @param {number} num - 数值
688
+ * @namespace 数学函数
689
+ *
690
+ * @returns {number} 数值对应的整形
691
+ */
692
+ fnINT(n: number) {
693
+ return Math.floor(this.formatNumber(n));
694
+ }
695
+
696
+ /**
697
+ * 返回两数相除的余数,参数 number 是被除数,divisor 是除数
698
+ *
699
+ * @example MOD(num, divisor)
700
+ * @param {number} num - 被除数
701
+ * @param {number} divisor - 除数
702
+ * @namespace 数学函数
703
+ *
704
+ * @returns {number} 两数相除的余数
705
+ */
706
+ fnMOD(a: number, b: number) {
707
+ return this.formatNumber(a) % this.formatNumber(b);
708
+ }
709
+
710
+ /**
711
+ * 圆周率 3.1415...
712
+ *
713
+ * @example PI()
714
+ * @namespace 数学函数
715
+ *
716
+ * @returns {number} 圆周率数值
717
+ */
718
+ fnPI() {
719
+ return Math.PI;
720
+ }
721
+
722
+ /**
723
+ * 将数字四舍五入到指定的位数,可以设置小数位。
724
+ *
725
+ * @example ROUND(num[, numDigits = 2])
726
+ * @param {number} num - 要处理的数字
727
+ * @param {number} numDigits - 小数位数
728
+ * @namespace 数学函数
729
+ *
730
+ * @returns {number} 传入数值四舍五入后的结果
731
+ */
732
+ fnROUND(a: number, b: number) {
733
+ a = this.formatNumber(a);
734
+ b = this.formatNumber(b);
735
+ const bResult = Math.round(b);
736
+
737
+ if (bResult) {
738
+ const c = Math.pow(10, bResult);
739
+ return Math.round(a * c) / c;
740
+ }
741
+
742
+ return Math.round(a);
743
+ }
744
+
745
+ /**
746
+ * 将数字向下取整到指定的位数,可以设置小数位。
747
+ *
748
+ * @example FLOOR(num[, numDigits=2])
749
+ * @param {number} num - 要处理的数字
750
+ * @param {number} numDigits - 小数位数
751
+ * @namespace 数学函数
752
+ *
753
+ * @returns {number} 传入数值向下取整后的结果
754
+ */
755
+ fnFLOOR(a: number, b: number) {
756
+ a = this.formatNumber(a);
757
+ b = this.formatNumber(b);
758
+ const bResult = Math.round(b);
759
+
760
+ if (bResult) {
761
+ const c = Math.pow(10, bResult);
762
+ return Math.floor(a * c) / c;
763
+ }
764
+
765
+ return Math.floor(a);
766
+ }
767
+
768
+ /**
769
+ * 将数字向上取整到指定的位数,可以设置小数位。
770
+ *
771
+ * @example CEIL(num[, numDigits=2])
772
+ * @param {number} num - 要处理的数字
773
+ * @param {number} numDigits - 小数位数
774
+ * @namespace 数学函数
775
+ *
776
+ * @returns {number} 传入数值向上取整后的结果
777
+ */
778
+ fnCEIL(a: number, b: number) {
779
+ a = this.formatNumber(a);
780
+ b = this.formatNumber(b);
781
+ const bResult = Math.round(b);
782
+
783
+ if (bResult) {
784
+ const c = Math.pow(10, bResult);
785
+ return Math.ceil(a * c) / c;
786
+ }
787
+
788
+ return Math.ceil(a);
789
+ }
790
+
791
+ /**
792
+ * 开平方,参数 number 为非负数
793
+ *
794
+ * @example SQRT(num)
795
+ * @param {number} num - 要处理的数字
796
+ * @namespace 数学函数
797
+ *
798
+ * @returns {number} 开平方的结果
799
+ */
800
+ fnSQRT(n: number) {
801
+ return Math.sqrt(this.formatNumber(n));
802
+ }
803
+
804
+ /**
805
+ * 返回所有参数的平均值,如果只有一个参数且是数组,则计算这个数组内的值
806
+ *
807
+ * @example AVG(num1, num2, ...numN)
808
+ * @param {...number} num - 要处理的数字
809
+ * @namespace 数学函数
810
+ *
811
+ * @returns {number} 所有数值的平均值
812
+ */
813
+ fnAVG(...args: Array<any>) {
814
+ let arr = args;
815
+ if (args.length === 1 && Array.isArray(args[0])) {
816
+ arr = args[0];
817
+ }
818
+ return (
819
+ this.fnSUM.apply(
820
+ this,
821
+ arr.map(item => this.formatNumber(item))
822
+ ) / arr.length
823
+ );
824
+ }
825
+
826
+ /**
827
+ * 返回数据点与数据均值点之差(数据偏差)的平方和,如果只有一个参数且是数组,则计算这个数组内的值
828
+ *
829
+ * @example DEVSQ(num1, num2, ...numN)
830
+ * @param {...number} num - 要处理的数字
831
+ * @namespace 数学函数
832
+ *
833
+ * @returns {number} 所有数值的平均值
834
+ */
835
+ fnDEVSQ(...args: Array<any>) {
836
+ if (args.length === 0) {
837
+ return null;
838
+ }
839
+ let arr = args;
840
+ if (args.length === 1 && Array.isArray(args[0])) {
841
+ arr = args[0];
842
+ }
843
+
844
+ const nums = arr.map(item => this.formatNumber(item));
845
+ const sum = nums.reduce((sum, a) => sum + a || 0, 0);
846
+ const mean = sum / nums.length;
847
+ let result = 0;
848
+ for (const num of nums) {
849
+ result += Math.pow(num - mean, 2);
850
+ }
851
+ return result;
852
+ }
853
+
854
+ /**
855
+ * 数据点到其算术平均值的绝对偏差的平均值
856
+ *
857
+ * @example AVEDEV(num1, num2, ...numN)
858
+ * @param {...number} num - 要处理的数字
859
+ * @namespace 数学函数
860
+ *
861
+ * @returns {number} 所有数值的平均值
862
+ */
863
+ fnAVEDEV(...args: Array<any>) {
864
+ if (args.length === 0) {
865
+ return null;
866
+ }
867
+ let arr = args;
868
+ if (args.length === 1 && Array.isArray(args[0])) {
869
+ arr = args[0];
870
+ }
871
+ const nums = arr.map(item => this.formatNumber(item));
872
+ const sum = nums.reduce((sum, a) => sum + a || 0, 0);
873
+ const mean = sum / nums.length;
874
+ let result = 0;
875
+ for (const num of nums) {
876
+ result += Math.abs(num - mean);
877
+ }
878
+ return result / nums.length;
879
+ }
880
+
881
+ /**
882
+ * 数据点的调和平均值,如果只有一个参数且是数组,则计算这个数组内的值
883
+ *
884
+ * @example HARMEAN(num1, num2, ...numN)
885
+ * @param {...number} num - 要处理的数字
886
+ * @namespace 数学函数
887
+ *
888
+ * @returns {number} 所有数值的平均值
889
+ */
890
+ fnHARMEAN(...args: Array<any>) {
891
+ if (args.length === 0) {
892
+ return null;
893
+ }
894
+ let arr = args;
895
+ if (args.length === 1 && Array.isArray(args[0])) {
896
+ arr = args[0];
897
+ }
898
+ const nums = arr.map(item => this.formatNumber(item));
899
+ let den = 0;
900
+ for (const num of nums) {
901
+ den += 1 / num;
902
+ }
903
+ return nums.length / den;
904
+ }
905
+
906
+ /**
907
+ * 数据集中第 k 个最大值
908
+ *
909
+ * @example LARGE(array, k)
910
+ * @param {array} nums - 要处理的数字
911
+ * @param {number} k - 第几大
912
+ * @namespace 数学函数
913
+ *
914
+ * @returns {number} 所有数值的平均值
915
+ */
916
+ fnLARGE(nums: Array<any>, k: number) {
917
+ if (nums.length === 0) {
918
+ return null;
919
+ }
920
+ const numsFormat = nums.map(item => this.formatNumber(item));
921
+ if (k < 0 || numsFormat.length < k) {
922
+ return null;
923
+ }
924
+ return numsFormat.sort(function (a, b) {
925
+ return b - a;
926
+ })[k - 1];
927
+ }
928
+
929
+ /**
930
+ * 将数值转为中文大写金额
931
+ *
932
+ * @example UPPERMONEY(num)
933
+ * @param {number} num - 要处理的数字
934
+ * @namespace 数学函数
935
+ *
936
+ * @returns {string} 数值中文大写字符
937
+ */
938
+ fnUPPERMONEY(n: number) {
939
+ n = this.formatNumber(n);
940
+ const fraction = ['角', '分'];
941
+ const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
942
+ const unit = [
943
+ ['元', '万', '亿'],
944
+ ['', '拾', '佰', '仟']
945
+ ];
946
+ const head = n < 0 ? '欠' : '';
947
+ n = Math.abs(n);
948
+ let s = '';
949
+ for (let i = 0; i < fraction.length; i++) {
950
+ s += (
951
+ digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]
952
+ ).replace(/零./, '');
953
+ }
954
+ s = s || '整';
955
+ n = Math.floor(n);
956
+ for (let i = 0; i < unit[0].length && n > 0; i++) {
957
+ let p = '';
958
+ for (let j = 0; j < unit[1].length && n > 0; j++) {
959
+ p = digit[n % 10] + unit[1][j] + p;
960
+ n = Math.floor(n / 10);
961
+ }
962
+ s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
963
+ }
964
+ return (
965
+ head +
966
+ s
967
+ .replace(/(零.)*零元/, '元')
968
+ .replace(/(零.)+/g, '零')
969
+ .replace(/^整$/, '零元整')
970
+ );
971
+ }
972
+
973
+ /**
974
+ * 返回大于等于 0 且小于 1 的均匀分布随机实数。每一次触发计算都会变化。
975
+ *
976
+ * 示例:`RAND()*100`
977
+ *
978
+ * 返回 0-100 之间的随机数
979
+ *
980
+ * @example RAND()
981
+ * @namespace 数学函数
982
+ *
983
+ * @returns {number} 随机数
984
+ */
985
+ fnRAND() {
986
+ return Math.random();
987
+ }
988
+
989
+ /**
990
+ * 取数据最后一个
991
+ *
992
+ * @example LAST(array)
993
+ * @param {...number} arr - 要处理的数组
994
+ * @namespace 数学函数
995
+ *
996
+ * @returns {any} 最后一个值
997
+ */
998
+ fnLAST(arr: Array<any>) {
999
+ return arr.length ? arr[arr.length - 1] : null;
1000
+ }
1001
+
1002
+ // 文本函数
1003
+
1004
+ normalizeText(raw: any) {
1005
+ if (raw instanceof Date) {
1006
+ return moment(raw).format();
1007
+ }
1008
+
1009
+ return `${raw}`;
1010
+ }
1011
+
1012
+ /**
1013
+ * 返回传入文本左侧的指定长度字符串。
1014
+ *
1015
+ * @example LEFT(text, len)
1016
+ * @param {string} text - 要处理的文本
1017
+ * @param {number} len - 要处理的长度
1018
+ * @namespace 文本函数
1019
+ *
1020
+ * @returns {string} 对应字符串
1021
+ */
1022
+ fnLEFT(text: string, len: number) {
1023
+ text = this.normalizeText(text);
1024
+ return text.substring(0, len);
1025
+ }
1026
+
1027
+ /**
1028
+ * 返回传入文本右侧的指定长度字符串。
1029
+ *
1030
+ * @example RIGHT(text, len)
1031
+ * @param {string} text - 要处理的文本
1032
+ * @param {number} len - 要处理的长度
1033
+ * @namespace 文本函数
1034
+ *
1035
+ * @returns {string} 对应字符串
1036
+ */
1037
+ fnRIGHT(text: string, len: number) {
1038
+ text = this.normalizeText(text);
1039
+ return text.substring(text.length - len, text.length);
1040
+ }
1041
+
1042
+ /**
1043
+ * 计算文本的长度
1044
+ *
1045
+ * @example LEN(text)
1046
+ * @param {string} text - 要处理的文本
1047
+ * @namespace 文本函数
1048
+ *
1049
+ * @returns {number} 长度
1050
+ */
1051
+ fnLEN(text: string) {
1052
+ text = this.normalizeText(text);
1053
+ return text?.length;
1054
+ }
1055
+
1056
+ /**
1057
+ * 计算文本集合中所有文本的长度
1058
+ *
1059
+ * @example LENGTH(textArr)
1060
+ * @param {string[]} textArr - 要处理的文本集合
1061
+ * @namespace 文本函数
1062
+ *
1063
+ * @returns {number[]} 长度集合
1064
+ */
1065
+ fnLENGTH(...args: any[]) {
1066
+ return this.fnLEN.call(this, args);
1067
+ }
1068
+
1069
+ /**
1070
+ * 判断文本是否为空
1071
+ *
1072
+ * @example ISEMPTY(text)
1073
+ * @param {string} text - 要处理的文本
1074
+ * @namespace 文本函数
1075
+ *
1076
+ * @returns {boolean} 判断结果
1077
+ */
1078
+ fnISEMPTY(text: string) {
1079
+ return !text || !String(text).trim();
1080
+ }
1081
+
1082
+ /**
1083
+ * 将多个传入值连接成文本
1084
+ *
1085
+ * @example CONCATENATE(text1, text2, ...textN)
1086
+ * @param {...string} text - 文本集合
1087
+ * @namespace 文本函数
1088
+ *
1089
+ * @returns {string} 连接后的文本
1090
+ */
1091
+ fnCONCATENATE(...args: Array<any>) {
1092
+ return args.join('');
1093
+ }
1094
+
1095
+ /**
1096
+ * 返回计算机字符集的数字代码所对应的字符。
1097
+ *
1098
+ * `CHAR(97)` 等价于 "a"
1099
+ *
1100
+ * @example CHAR(code)
1101
+ * @param {number} code - 编码值
1102
+ * @namespace 文本函数
1103
+ *
1104
+ * @returns {string} 指定位置的字符
1105
+ */
1106
+ fnCHAR(code: number) {
1107
+ return String.fromCharCode(code);
1108
+ }
1109
+
1110
+ /**
1111
+ * 将传入文本转成小写
1112
+ *
1113
+ * @example LOWER(text)
1114
+ * @param {string} text - 文本
1115
+ * @namespace 文本函数
1116
+ *
1117
+ * @returns {string} 结果文本
1118
+ */
1119
+ fnLOWER(text: string) {
1120
+ text = this.normalizeText(text);
1121
+ return text.toLowerCase();
1122
+ }
1123
+
1124
+ /**
1125
+ * 将传入文本转成大写
1126
+ *
1127
+ * @example UPPER(text)
1128
+ * @param {string} text - 文本
1129
+ * @namespace 文本函数
1130
+ *
1131
+ * @returns {string} 结果文本
1132
+ */
1133
+ fnUPPER(text: string) {
1134
+ text = this.normalizeText(text);
1135
+ return text.toUpperCase();
1136
+ }
1137
+
1138
+ /**
1139
+ * 将传入文本首字母转成大写
1140
+ *
1141
+ * @example UPPERFIRST(text)
1142
+ * @param {string} text - 文本
1143
+ * @namespace 文本函数
1144
+ *
1145
+ * @returns {string} 结果文本
1146
+ */
1147
+ fnUPPERFIRST(text: string) {
1148
+ text = this.normalizeText(text);
1149
+ return upperFirst(text);
1150
+ }
1151
+
1152
+ /**
1153
+ * 向前补齐文本长度
1154
+ *
1155
+ * 示例 `PADSTART("6", 2, "0")`
1156
+ *
1157
+ * 返回 `06`
1158
+ *
1159
+ * @example PADSTART(text)
1160
+ * @param {string} text - 文本
1161
+ * @param {number} num - 目标长度
1162
+ * @param {string} pad - 用于补齐的文本
1163
+ * @namespace 文本函数
1164
+ *
1165
+ * @returns {string} 结果文本
1166
+ */
1167
+ fnPADSTART(text: string, num: number, pad: string): string {
1168
+ text = this.normalizeText(text);
1169
+ return padStart(text, num, pad);
1170
+ }
1171
+
1172
+ /**
1173
+ * 将文本转成标题
1174
+ *
1175
+ * 示例 `CAPITALIZE("star")`
1176
+ *
1177
+ * 返回 `Star`
1178
+ *
1179
+ * @example CAPITALIZE(text)
1180
+ * @param {string} text - 文本
1181
+ * @namespace 文本函数
1182
+ *
1183
+ * @returns {string} 结果文本
1184
+ */
1185
+ fnCAPITALIZE(text: string): string {
1186
+ text = this.normalizeText(text);
1187
+ return capitalize(text);
1188
+ }
1189
+
1190
+ /**
1191
+ * 对文本进行 HTML 转义
1192
+ *
1193
+ * 示例 `ESCAPE("star")`
1194
+ *
1195
+ * 返回 `Star`
1196
+ *
1197
+ * @example ESCAPE(text)
1198
+ * @param {string} text - 文本
1199
+ * @namespace 文本函数
1200
+ *
1201
+ * @returns {string} 结果文本
1202
+ */
1203
+ fnESCAPE(text: string): string {
1204
+ text = this.normalizeText(text);
1205
+ return escape(text);
1206
+ }
1207
+
1208
+ /**
1209
+ * 对文本长度进行截断
1210
+ *
1211
+ * 示例 `TRUNCATE("amis.baidu.com", 6)`
1212
+ *
1213
+ * 返回 `amis...`
1214
+ *
1215
+ * @example TRUNCATE(text, 6)
1216
+ * @param {string} text - 文本
1217
+ * @param {number} text - 最长长度
1218
+ * @namespace 文本函数
1219
+ *
1220
+ * @returns {string} 结果文本
1221
+ */
1222
+ fnTRUNCATE(text: string, length: number): string {
1223
+ text = this.normalizeText(text);
1224
+ return truncate(text, {length});
1225
+ }
1226
+
1227
+ /**
1228
+ * 取在某个分隔符之前的所有字符串
1229
+ *
1230
+ * @example BEFORELAST(text, '.')
1231
+ * @param {string} text - 文本
1232
+ * @param {string} delimiter - 结束文本
1233
+ * @namespace 文本函数
1234
+ *
1235
+ * @returns {string} 判断结果
1236
+ */
1237
+ fnBEFORELAST(text: string, delimiter: string = '.') {
1238
+ text = this.normalizeText(text);
1239
+ return text.split(delimiter).slice(0, -1).join(delimiter) || text + '';
1240
+ }
1241
+
1242
+ /**
1243
+ * 将文本根据指定片段分割成数组
1244
+ *
1245
+ * 示例:`SPLIT("a,b,c", ",")`
1246
+ *
1247
+ * 返回 `["a", "b", "c"]`
1248
+ *
1249
+ * @example SPLIT(text, ',')
1250
+ * @param {string} text - 文本
1251
+ * @param {string} delimiter - 文本片段
1252
+ * @namespace 文本函数
1253
+ *
1254
+ * @returns {Array<string>} 文本集
1255
+ */
1256
+ fnSPLIT(text: string, sep: string = ',') {
1257
+ text = this.normalizeText(text);
1258
+ return text.split(sep);
1259
+ }
1260
+
1261
+ /**
1262
+ * 将文本去除前后空格
1263
+ *
1264
+ * @example TRIM(text)
1265
+ * @param {string} text - 文本
1266
+ * @namespace 文本函数
1267
+ *
1268
+ * @returns {string} 处理后的文本
1269
+ */
1270
+ fnTRIM(text: string) {
1271
+ text = this.normalizeText(text);
1272
+ return text.trim();
1273
+ }
1274
+
1275
+ /**
1276
+ * 去除文本中的 HTML 标签
1277
+ *
1278
+ * 示例:`STRIPTAG("<b>amis</b>")`
1279
+ *
1280
+ * 返回:`amis`
1281
+ *
1282
+ * @example STRIPTAG(text)
1283
+ * @param {string} text - 文本
1284
+ * @namespace 文本函数
1285
+ *
1286
+ * @returns {string} 处理后的文本
1287
+ */
1288
+ fnSTRIPTAG(text: string) {
1289
+ text = this.normalizeText(text);
1290
+ return text.replace(/<\/?[^>]+(>|$)/g, '');
1291
+ }
1292
+
1293
+ /**
1294
+ * 将字符串中的换行转成 HTML `<br>`,用于简单换行的场景
1295
+ *
1296
+ * 示例:`LINEBREAK("\n")`
1297
+ *
1298
+ * 返回:`<br/>`
1299
+ *
1300
+ * @example LINEBREAK(text)
1301
+ * @param {string} text - 文本
1302
+ * @namespace 文本函数
1303
+ *
1304
+ * @returns {string} 处理后的文本
1305
+ */
1306
+ fnLINEBREAK(text: string) {
1307
+ text = this.normalizeText(text);
1308
+ return text.replace(/(?:\r\n|\r|\n)/g, '<br/>');
1309
+ }
1310
+
1311
+ /**
1312
+ * 判断字符串(text)是否以特定字符串(startString)开始,是则返回 True,否则返回 False
1313
+ *
1314
+ * @example STARTSWITH(text, '片段')
1315
+ * @param {string} text - 文本
1316
+ * @param {string} startString - 起始文本
1317
+ * @namespace 文本函数
1318
+ *
1319
+ * @returns {string} 判断结果
1320
+ */
1321
+ fnSTARTSWITH(text: string, search: string) {
1322
+ if (!search) {
1323
+ return false;
1324
+ }
1325
+
1326
+ text = this.normalizeText(text);
1327
+ return text.indexOf(search) === 0;
1328
+ }
1329
+
1330
+ /**
1331
+ * 判断字符串(text)是否以特定字符串(endString)结束,是则返回 True,否则返回 False
1332
+ *
1333
+ * @example ENDSWITH(text, '片段')
1334
+ * @param {string} text - 文本
1335
+ * @param {string} endString - 结束文本
1336
+ * @namespace 文本函数
1337
+ *
1338
+ * @returns {string} 判断结果
1339
+ */
1340
+ fnENDSWITH(text: string, search: string) {
1341
+ if (!search) {
1342
+ return false;
1343
+ }
1344
+
1345
+ text = this.normalizeText(text);
1346
+ return text.indexOf(search, text.length - search.length) !== -1;
1347
+ }
1348
+
1349
+ /**
1350
+ * 判断参数 1 中的文本是否包含参数 2 中的文本。
1351
+ *
1352
+ * @example CONTAINS(text, searchText)
1353
+ * @param {string} text - 文本
1354
+ * @param {string} searchText - 搜索文本
1355
+ * @namespace 文本函数
1356
+ *
1357
+ * @returns {string} 判断结果
1358
+ */
1359
+ fnCONTAINS(text: string, search: string) {
1360
+ if (!search) {
1361
+ return false;
1362
+ }
1363
+
1364
+ text = this.normalizeText(text);
1365
+ return !!~text.indexOf(search);
1366
+ }
1367
+
1368
+ /**
1369
+ * 对文本进行全量替换。
1370
+ *
1371
+ * @example REPLACE(text, search, replace)
1372
+ * @param {string} text - 要处理的文本
1373
+ * @param {string} search - 要被替换的文本
1374
+ * @param {string} replace - 要替换的文本
1375
+ * @namespace 文本函数
1376
+ *
1377
+ * @returns {string} 处理结果
1378
+ */
1379
+ fnREPLACE(text: string, search: string, replace: string) {
1380
+ text = this.normalizeText(text);
1381
+ let result = text;
1382
+
1383
+ while (true) {
1384
+ const idx = result.indexOf(search);
1385
+
1386
+ if (!~idx) {
1387
+ break;
1388
+ }
1389
+
1390
+ result =
1391
+ result.substring(0, idx) +
1392
+ replace +
1393
+ result.substring(idx + search.length);
1394
+ }
1395
+
1396
+ return result;
1397
+ }
1398
+
1399
+ /**
1400
+ * 对文本进行搜索,返回命中的位置
1401
+ *
1402
+ * @example SEARCH(text, search, 0)
1403
+ * @param {string} text - 要处理的文本
1404
+ * @param {string} search - 用来搜索的文本
1405
+ * @param {number} start - 起始位置
1406
+ * @namespace 文本函数
1407
+ *
1408
+ * @returns {number} 命中的位置
1409
+ */
1410
+ fnSEARCH(text: string, search: string, start: number = 0) {
1411
+ text = this.normalizeText(text);
1412
+ start = this.formatNumber(start);
1413
+
1414
+ const idx = text.indexOf(search, start);
1415
+ if (~idx) {
1416
+ return idx;
1417
+ }
1418
+
1419
+ return -1;
1420
+ }
1421
+
1422
+ /**
1423
+ * 返回文本字符串中从指定位置开始的特定数目的字符
1424
+ *
1425
+ * @example MID(text, from, len)
1426
+ * @param {string} text - 要处理的文本
1427
+ * @param {number} from - 起始位置
1428
+ * @param {number} len - 处理长度
1429
+ * @namespace 文本函数
1430
+ *
1431
+ * @returns {number} 命中的位置
1432
+ */
1433
+ fnMID(text: string, from: number, len: number) {
1434
+ text = this.normalizeText(text);
1435
+ return text.substring(from, from + len);
1436
+ }
1437
+
1438
+ /**
1439
+ * 返回路径中的文件名
1440
+ *
1441
+ * 示例:`/home/amis/a.json`
1442
+ *
1443
+ * 返回:a.json`
1444
+ *
1445
+ * @example BASENAME(text)
1446
+ * @param {string} text - 要处理的文本
1447
+ * @namespace 文本函数
1448
+ *
1449
+ * @returns {string} 文件名
1450
+ */
1451
+ fnBASENAME(text: string) {
1452
+ text = this.normalizeText(text);
1453
+ return text.split(/[\\/]/).pop();
1454
+ }
1455
+
1456
+ // 日期函数
1457
+
1458
+ /**
1459
+ * 创建日期对象,可以通过特定格式的字符串,或者数值。
1460
+ *
1461
+ * 需要注意的是,其中月份的数值是从0开始的,也就是说,
1462
+ * 如果是12月份,你应该传入数值11。
1463
+ *
1464
+ * @example DATE(2021, 11, 6, 8, 20, 0)
1465
+ * @example DATE('2021-12-06 08:20:00')
1466
+ * @namespace 日期函数
1467
+ *
1468
+ * @returns {Date} 日期对象
1469
+ */
1470
+ fnDATE(
1471
+ year: number,
1472
+ month: number,
1473
+ day: number,
1474
+ hour: number,
1475
+ minute: number,
1476
+ second: number
1477
+ ) {
1478
+ if (month === undefined) {
1479
+ return new Date(year);
1480
+ }
1481
+
1482
+ return new Date(year, month, day, hour, minute, second);
1483
+ }
1484
+
1485
+ /**
1486
+ * 返回时间的时间戳
1487
+ *
1488
+ * @example TIMESTAMP(date[, format = "X"])
1489
+ * @namespace 日期函数
1490
+ * @param {date} date 日期对象
1491
+ * @param {string} format 时间戳格式,带毫秒传入 'x'。默认为 'X' 不带毫秒的。
1492
+ *
1493
+ * @returns {number} 时间戳
1494
+ */
1495
+ fnTIMESTAMP(date: Date, format?: 'x' | 'X') {
1496
+ return parseInt(moment(date).format(format === 'x' ? 'x' : 'X'), 10);
1497
+ }
1498
+
1499
+ /**
1500
+ * 返回今天的日期
1501
+ *
1502
+ * @example TODAY()
1503
+ * @namespace 日期函数
1504
+ *
1505
+ * @returns {number} 日期
1506
+ */
1507
+ fnTODAY() {
1508
+ return new Date();
1509
+ }
1510
+
1511
+ /**
1512
+ * 返回现在的日期
1513
+ *
1514
+ * @example NOW()
1515
+ * @namespace 日期函数
1516
+ *
1517
+ * @returns {number} 日期
1518
+ */
1519
+ fnNOW() {
1520
+ return new Date();
1521
+ }
1522
+
1523
+ /**
1524
+ * 将日期转成日期字符串
1525
+ *
1526
+ * @example DATETOSTR(date[, format="YYYY-MM-DD HH:mm:ss"])
1527
+ * @namespace 日期函数
1528
+ * @param {date} date 日期对象
1529
+ * @param {string} format 日期格式,默认为 "YYYY-MM-DD HH:mm:ss"
1530
+ *
1531
+ * @returns {number} 日期字符串
1532
+ */
1533
+ fnDATETOSTR(date: Date, format = 'YYYY-MM-DD HH:mm:ss') {
1534
+ return moment(date).format(format);
1535
+ }
1536
+
1537
+ /**
1538
+ * 返回日期的指定范围的开端
1539
+ *
1540
+ * @namespace 日期函数
1541
+ * @example STARTOF(date[unit = "day"])
1542
+ * @param {date} date 日期对象
1543
+ * @param {string} unit 比如可以传入 'day'、'month'、'year' 或者 `week` 等等
1544
+ * @returns {date} 新的日期对象
1545
+ */
1546
+ fnSTARTOF(date: Date, unit?: any) {
1547
+ return moment(date)
1548
+ .startOf(unit || 'day')
1549
+ .toDate();
1550
+ }
1551
+
1552
+ /**
1553
+ * 返回日期的指定范围的末尾
1554
+ * @namespace 日期函数
1555
+ * @example ENDOF(date[unit = "day"])
1556
+ * @param {date} date 日期对象
1557
+ * @param {string} unit 比如可以传入 'day'、'month'、'year' 或者 `week` 等等
1558
+ * @returns {date} 新的日期对象
1559
+ */
1560
+ fnENDOF(date: Date, unit?: any) {
1561
+ return moment(date)
1562
+ .endOf(unit || 'day')
1563
+ .toDate();
1564
+ }
1565
+
1566
+ normalizeDate(raw: any): Date {
1567
+ if (typeof raw === 'string') {
1568
+ const formats = ['', 'YYYY-MM-DD HH:mm:ss'];
1569
+
1570
+ while (formats.length) {
1571
+ const format = formats.shift()!;
1572
+ const date = moment(raw, format);
1573
+
1574
+ if (date.isValid()) {
1575
+ return date.toDate();
1576
+ }
1577
+ }
1578
+ } else if (typeof raw === 'number') {
1579
+ return new Date(raw);
1580
+ }
1581
+
1582
+ return raw;
1583
+ }
1584
+
1585
+ /**
1586
+ * 返回日期的年份
1587
+ * @namespace 日期函数
1588
+ * @example YEAR(date)
1589
+ * @param {date} date 日期对象
1590
+ * @returns {number} 数值
1591
+ */
1592
+ fnYEAR(date: Date) {
1593
+ date = this.normalizeDate(date);
1594
+ return date.getFullYear();
1595
+ }
1596
+
1597
+ /**
1598
+ * 返回日期的月份,这里就是自然月份。
1599
+ *
1600
+ * @namespace 日期函数
1601
+ * @example MONTH(date)
1602
+ * @param {date} date 日期对象
1603
+ * @returns {number} 数值
1604
+ */
1605
+ fnMONTH(date: Date) {
1606
+ date = this.normalizeDate(date);
1607
+ return date.getMonth() + 1;
1608
+ }
1609
+
1610
+ /**
1611
+ * 返回日期的天
1612
+ * @namespace 日期函数
1613
+ * @example DAY(date)
1614
+ * @param {date} date 日期对象
1615
+ * @returns {number} 数值
1616
+ */
1617
+ fnDAY(date: Date) {
1618
+ date = this.normalizeDate(date);
1619
+ return date.getDate();
1620
+ }
1621
+
1622
+ /**
1623
+ * 返回日期的小时
1624
+ * @param {date} date 日期对象
1625
+ * @namespace 日期函数
1626
+ * @example HOUR(date)
1627
+ * @returns {number} 数值
1628
+ */
1629
+ fnHOUR(date: Date) {
1630
+ date = this.normalizeDate(date);
1631
+ return date.getHours();
1632
+ }
1633
+
1634
+ /**
1635
+ * 返回日期的分
1636
+ * @param {date} date 日期对象
1637
+ * @namespace 日期函数
1638
+ * @example MINUTE(date)
1639
+ * @returns {number} 数值
1640
+ */
1641
+ fnMINUTE(date: Date) {
1642
+ date = this.normalizeDate(date);
1643
+ return date.getMinutes();
1644
+ }
1645
+
1646
+ /**
1647
+ * 返回日期的秒
1648
+ * @param {date} date 日期对象
1649
+ * @namespace 日期函数
1650
+ * @example SECOND(date)
1651
+ * @returns {number} 数值
1652
+ */
1653
+ fnSECOND(date: Date) {
1654
+ date = this.normalizeDate(date);
1655
+ return date.getSeconds();
1656
+ }
1657
+
1658
+ /**
1659
+ * 返回两个日期相差多少年
1660
+ * @param {date} endDate 日期对象
1661
+ * @param {date} startDate 日期对象
1662
+ * @namespace 日期函数
1663
+ * @example YEARS(endDate, startDate)
1664
+ * @returns {number} 数值
1665
+ */
1666
+ fnYEARS(endDate: Date, startDate: Date) {
1667
+ endDate = this.normalizeDate(endDate);
1668
+ startDate = this.normalizeDate(startDate);
1669
+ return moment(endDate).diff(moment(startDate), 'year');
1670
+ }
1671
+
1672
+ /**
1673
+ * 返回两个日期相差多少分钟
1674
+ * @param {date} endDate 日期对象
1675
+ * @param {date} startDate 日期对象
1676
+ * @namespace 日期函数
1677
+ * @example MINUTES(endDate, startDate)
1678
+ * @returns {number} 数值
1679
+ */
1680
+ fnMINUTES(endDate: Date, startDate: Date) {
1681
+ endDate = this.normalizeDate(endDate);
1682
+ startDate = this.normalizeDate(startDate);
1683
+ return moment(endDate).diff(moment(startDate), 'minutes');
1684
+ }
1685
+
1686
+ /**
1687
+ * 返回两个日期相差多少天
1688
+ * @param {date} endDate 日期对象
1689
+ * @param {date} startDate 日期对象
1690
+ * @namespace 日期函数
1691
+ * @example DAYS(endDate, startDate)
1692
+ * @returns {number} 数值
1693
+ */
1694
+ fnDAYS(endDate: Date, startDate: Date) {
1695
+ endDate = this.normalizeDate(endDate);
1696
+ startDate = this.normalizeDate(startDate);
1697
+ return moment(endDate).diff(moment(startDate), 'days');
1698
+ }
1699
+
1700
+ /**
1701
+ * 返回两个日期相差多少小时
1702
+ * @param {date} endDate 日期对象
1703
+ * @param {date} startDate 日期对象
1704
+ * @namespace 日期函数
1705
+ * @example HOURS(endDate, startDate)
1706
+ * @returns {number} 数值
1707
+ */
1708
+ fnHOURS(endDate: Date, startDate: Date) {
1709
+ endDate = this.normalizeDate(endDate);
1710
+ startDate = this.normalizeDate(startDate);
1711
+ return moment(endDate).diff(moment(startDate), 'hour');
1712
+ }
1713
+
1714
+ /**
1715
+ * 修改日期,对日期进行加减天、月份、年等操作
1716
+ *
1717
+ * 示例:
1718
+ *
1719
+ * DATEMODIFY(A, -2, 'month')
1720
+ *
1721
+ * 对日期 A 进行往前减2月的操作。
1722
+ *
1723
+ * @param {date} date 日期对象
1724
+ * @param {number} num 数值
1725
+ * @param {string} unit 单位:支持年、月、天等等
1726
+ * @namespace 日期函数
1727
+ * @example DATEMODIFY(date, 2, 'days')
1728
+ * @returns {date} 日期对象
1729
+ */
1730
+ fnDATEMODIFY(date: Date, num: number, format: any) {
1731
+ date = this.normalizeDate(date);
1732
+ return moment(date).add(num, format).toDate();
1733
+ }
1734
+
1735
+ /**
1736
+ * 将字符日期转成日期对象,可以指定日期格式。
1737
+ *
1738
+ * 示例:STRTODATE('2021/12/6', 'YYYY/MM/DD')
1739
+ *
1740
+ * @param {string} value 日期字符
1741
+ * @param {string} format 日期格式
1742
+ * @namespace 日期函数
1743
+ * @example STRTODATE(value[, format=""])
1744
+ * @returns {date} 日期对象
1745
+ */
1746
+ fnSTRTODATE(value: any, format: string = '') {
1747
+ return moment(value, format).toDate();
1748
+ }
1749
+
1750
+ /**
1751
+ * 判断两个日期,是否第一个日期在第二个日期的前面
1752
+ *
1753
+ * @param {date} a 第一个日期
1754
+ * @param {date} b 第二个日期
1755
+ * @param {string} unit 单位,默认是 'day', 即之比较到天
1756
+ * @namespace 日期函数
1757
+ * @example ISBEFORE(a, b)
1758
+ * @returns {boolean} 判断结果
1759
+ */
1760
+ fnISBEFORE(a: Date, b: Date, unit: any = 'day') {
1761
+ a = this.normalizeDate(a);
1762
+ b = this.normalizeDate(b);
1763
+ return moment(a).isBefore(moment(b), unit);
1764
+ }
1765
+
1766
+ /**
1767
+ * 判断两个日期,是否第一个日期在第二个日期的后面
1768
+ *
1769
+ * @param {date} a 第一个日期
1770
+ * @param {date} b 第二个日期
1771
+ * @param {string} unit 单位,默认是 'day', 即之比较到天
1772
+ * @namespace 日期函数
1773
+ * @example ISAFTER(a, b)
1774
+ * @returns {boolean} 判断结果
1775
+ */
1776
+ fnISAFTER(a: Date, b: Date, unit: any = 'day') {
1777
+ a = this.normalizeDate(a);
1778
+ b = this.normalizeDate(b);
1779
+ return moment(a).isAfter(moment(b), unit);
1780
+ }
1781
+
1782
+ /**
1783
+ * 判断两个日期,是否第一个日期在第二个日期的前面或者相等
1784
+ *
1785
+ * @param {date} a 第一个日期
1786
+ * @param {date} b 第二个日期
1787
+ * @param {string} unit 单位,默认是 'day', 即之比较到天
1788
+ * @namespace 日期函数
1789
+ * @example ISSAMEORBEFORE(a, b)
1790
+ * @returns {boolean} 判断结果
1791
+ */
1792
+ fnISSAMEORBEFORE(a: Date, b: Date, unit: any = 'day') {
1793
+ a = this.normalizeDate(a);
1794
+ b = this.normalizeDate(b);
1795
+ return moment(a).isSameOrBefore(moment(b), unit);
1796
+ }
1797
+
1798
+ /**
1799
+ * 判断两个日期,是否第一个日期在第二个日期的后面或者相等
1800
+ *
1801
+ * @param {date} a 第一个日期
1802
+ * @param {date} b 第二个日期
1803
+ * @param {string} unit 单位,默认是 'day', 即之比较到天
1804
+ * @namespace 日期函数
1805
+ * @example ISSAMEORAFTER(a, b)
1806
+ * @returns {boolean} 判断结果
1807
+ */
1808
+ fnISSAMEORAFTER(a: Date, b: Date, unit: any = 'day') {
1809
+ a = this.normalizeDate(a);
1810
+ b = this.normalizeDate(b);
1811
+ return moment(a).isSameOrAfter(moment(b), unit);
1812
+ }
1813
+
1814
+ /**
1815
+ * 返回数组的长度
1816
+ *
1817
+ * @param {Array<any>} arr 数组
1818
+ * @namespace 数组
1819
+ * @example COUNT(arr)
1820
+ * @returns {boolean} 结果
1821
+ */
1822
+ fnCOUNT(value: any) {
1823
+ return Array.isArray(value) ? value.length : value ? 1 : 0;
1824
+ }
1825
+
1826
+ /**
1827
+ * 数组做数据转换,需要搭配箭头函数一起使用,注意箭头函数只支持单表达式用法。
1828
+ *
1829
+ * @param {Array<any>} arr 数组
1830
+ * @param {Function<any>} iterator 箭头函数
1831
+ * @namespace 数组
1832
+ * @example ARRAYMAP(arr, item => item)
1833
+ * @returns {boolean} 结果
1834
+ */
1835
+ fnARRAYMAP(value: any, iterator: any) {
1836
+ if (!iterator || iterator.type !== 'anonymous_function') {
1837
+ throw new Error('expected an anonymous function get ' + iterator);
1838
+ }
1839
+
1840
+ return (Array.isArray(value) ? value : []).map((item, index) =>
1841
+ this.callAnonymousFunction(iterator, [item, index])
1842
+ );
1843
+ }
1844
+
1845
+ /**
1846
+ * 数组过滤掉 false、null、0 和 ""
1847
+ *
1848
+ * 示例:
1849
+ *
1850
+ * COMPACT([0, 1, false, 2, '', 3]) 得到 [1, 2, 3]
1851
+ *
1852
+ * @param {Array<any>} arr 数组
1853
+ * @namespace 数组
1854
+ * @example COMPACT(arr)
1855
+ * @returns {Array<any>} 结果
1856
+ */
1857
+ fnCOMPACT(arr: any[]) {
1858
+ if (Array.isArray(arr)) {
1859
+ let resIndex = 0;
1860
+ const result = [];
1861
+ for (const item of arr) {
1862
+ if (item) {
1863
+ result[resIndex++] = item;
1864
+ }
1865
+ }
1866
+ return result;
1867
+ } else {
1868
+ return [];
1869
+ }
1870
+ }
1871
+
1872
+ /**
1873
+ * 数组转成字符串
1874
+ *
1875
+ * 示例:
1876
+ *
1877
+ * JOIN(['a', 'b', 'c'], '~') 得到 'a~b~c'
1878
+ *
1879
+ * @param {Array<any>} arr 数组
1880
+ * @param { String} separator 分隔符
1881
+ * @namespace 数组
1882
+ * @example JOIN(arr, string)
1883
+ * @returns {String} 结果
1884
+ */
1885
+ fnJOIN(arr: any[], separator = '') {
1886
+ if (Array.isArray(arr)) {
1887
+ return arr.join(separator);
1888
+ } else {
1889
+ return '';
1890
+ }
1891
+ }
1892
+ }
1893
+
1894
+ function getCookie(name: string) {
1895
+ const value = `; ${document.cookie}`;
1896
+ const parts = value.split(`; ${name}=`);
1897
+ if (parts.length === 2) {
1898
+ return parts.pop()!.split(';').shift();
1899
+ }
1900
+ return undefined;
1901
+ }
1902
+
1903
+ function parseJson(str: string, defaultValue?: any) {
1904
+ try {
1905
+ return JSON.parse(str);
1906
+ } catch (e) {
1907
+ return defaultValue;
1908
+ }
1909
+ }
1910
+
1911
+ function stripNumber(number: number) {
1912
+ if (typeof number === 'number') {
1913
+ return parseFloat(number.toPrecision(12));
1914
+ } else {
1915
+ return number;
1916
+ }
1917
+ }
1918
+
1919
+ export function createObject(
1920
+ superProps?: {[propName: string]: any},
1921
+ props?: {[propName: string]: any},
1922
+ properties?: any
1923
+ ): object {
1924
+ const obj = superProps
1925
+ ? Object.create(superProps, {
1926
+ ...properties,
1927
+ __super: {
1928
+ value: superProps,
1929
+ writable: false,
1930
+ enumerable: false
1931
+ }
1932
+ })
1933
+ : Object.create(Object.prototype, properties);
1934
+
1935
+ props && Object.keys(props).forEach(key => (obj[key] = props[key]));
1936
+
1937
+ return obj;
1938
+ }