calc.go
84.2 KB
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
// Copyright 2016 - 2020 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX / XLSM / XLTM files. Supports reading and writing
// spreadsheet documents generated by Microsoft Exce™ 2007 and later. Supports
// complex components by high compatibility, and provided streaming API for
// generating or reading data from a worksheet with huge amounts of data. This
// library needs Go version 1.10 or later.
package excelize
import (
"bytes"
"container/list"
"errors"
"fmt"
"math"
"math/rand"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/xuri/efp"
)
// Excel formula errors
const (
formulaErrorDIV = "#DIV/0!"
formulaErrorNAME = "#NAME?"
formulaErrorNA = "#N/A"
formulaErrorNUM = "#NUM!"
formulaErrorVALUE = "#VALUE!"
formulaErrorREF = "#REF!"
formulaErrorNULL = "#NULL"
formulaErrorSPILL = "#SPILL!"
formulaErrorCALC = "#CALC!"
formulaErrorGETTINGDATA = "#GETTING_DATA"
)
// cellRef defines the structure of a cell reference.
type cellRef struct {
Col int
Row int
Sheet string
}
// cellRef defines the structure of a cell range.
type cellRange struct {
From cellRef
To cellRef
}
// formula criteria condition enumeration.
const (
_ byte = iota
criteriaEq
criteriaLe
criteriaGe
criteriaL
criteriaG
criteriaBeg
criteriaEnd
)
// formulaCriteria defined formula criteria parser result.
type formulaCriteria struct {
Type byte
Condition string
}
// ArgType is the type if formula argument type.
type ArgType byte
// Formula argument types enumeration.
const (
ArgUnknown ArgType = iota
ArgString
ArgMatrix
)
// formulaArg is the argument of a formula or function.
type formulaArg struct {
String string
Matrix [][]formulaArg
Type ArgType
}
// formulaFuncs is the type of the formula functions.
type formulaFuncs struct{}
// CalcCellValue provides a function to get calculated cell value. This
// feature is currently in working processing. Array formula, table formula
// and some other formulas are not supported currently.
//
// Supported formulas:
//
// ABS, ACOS, ACOSH, ACOT, ACOTH, ARABIC, ASIN, ASINH, ATAN2, ATANH, BASE,
// CEILING, CEILING.MATH, CEILING.PRECISE, COMBIN, COMBINA, COS, COSH, COT,
// COTH, COUNTA, CSC, CSCH, DECIMAL, DEGREES, EVEN, EXP, FACT, FACTDOUBLE,
// FLOOR, FLOOR.MATH, FLOOR.PRECISE, GCD, INT, ISBLANK, ISERR, ISERROR,
// ISEVEN, ISNA, ISNONTEXT, ISNUMBER, ISO.CEILING, ISODD, LCM, LN, LOG,
// LOG10, MDETERM, MEDIAN, MOD, MROUND, MULTINOMIAL, MUNIT, NA, ODD, PI,
// POWER, PRODUCT, QUOTIENT, RADIANS, RAND, RANDBETWEEN, ROUND, ROUNDDOWN,
// ROUNDUP, SEC, SECH, SIGN, SIN, SINH, SQRT, SQRTPI, SUM, SUMIF, SUMSQ,
// TAN, TANH, TRUNC
//
func (f *File) CalcCellValue(sheet, cell string) (result string, err error) {
var (
formula string
token efp.Token
)
if formula, err = f.GetCellFormula(sheet, cell); err != nil {
return
}
ps := efp.ExcelParser()
tokens := ps.Parse(formula)
if tokens == nil {
return
}
if token, err = f.evalInfixExp(sheet, tokens); err != nil {
return
}
result = token.TValue
return
}
// getPriority calculate arithmetic operator priority.
func getPriority(token efp.Token) (pri int) {
var priority = map[string]int{
"*": 2,
"/": 2,
"+": 1,
"-": 1,
}
pri, _ = priority[token.TValue]
if token.TValue == "-" && token.TType == efp.TokenTypeOperatorPrefix {
pri = 3
}
if token.TSubType == efp.TokenSubTypeStart && token.TType == efp.TokenTypeSubexpression { // (
pri = 0
}
return
}
// evalInfixExp evaluate syntax analysis by given infix expression after
// lexical analysis. Evaluate an infix expression containing formulas by
// stacks:
//
// opd - Operand
// opt - Operator
// opf - Operation formula
// opfd - Operand of the operation formula
// opft - Operator of the operation formula
//
// Evaluate arguments of the operation formula by list:
//
// args - Arguments of the operation formula
//
// TODO: handle subtypes: Nothing, Text, Logical, Error, Concatenation, Intersection, Union
//
func (f *File) evalInfixExp(sheet string, tokens []efp.Token) (efp.Token, error) {
var err error
opdStack, optStack, opfStack, opfdStack, opftStack := NewStack(), NewStack(), NewStack(), NewStack(), NewStack()
argsList := list.New()
for i := 0; i < len(tokens); i++ {
token := tokens[i]
// out of function stack
if opfStack.Len() == 0 {
if err = f.parseToken(sheet, token, opdStack, optStack); err != nil {
return efp.Token{}, err
}
}
// function start
if token.TType == efp.TokenTypeFunction && token.TSubType == efp.TokenSubTypeStart {
opfStack.Push(token)
continue
}
// in function stack, walk 2 token at once
if opfStack.Len() > 0 {
var nextToken efp.Token
if i+1 < len(tokens) {
nextToken = tokens[i+1]
}
// current token is args or range, skip next token, order required: parse reference first
if token.TSubType == efp.TokenSubTypeRange {
if !opftStack.Empty() {
// parse reference: must reference at here
result, err := f.parseReference(sheet, token.TValue)
if err != nil {
return efp.Token{TValue: formulaErrorNAME}, err
}
if result.Type != ArgString {
return efp.Token{}, errors.New(formulaErrorVALUE)
}
opfdStack.Push(efp.Token{
TType: efp.TokenTypeOperand,
TSubType: efp.TokenSubTypeNumber,
TValue: result.String,
})
continue
}
if nextToken.TType == efp.TokenTypeArgument || nextToken.TType == efp.TokenTypeFunction {
// parse reference: reference or range at here
result, err := f.parseReference(sheet, token.TValue)
if err != nil {
return efp.Token{TValue: formulaErrorNAME}, err
}
if result.Type == ArgUnknown {
return efp.Token{}, errors.New(formulaErrorVALUE)
}
argsList.PushBack(result)
continue
}
}
// check current token is opft
if err = f.parseToken(sheet, token, opfdStack, opftStack); err != nil {
return efp.Token{}, err
}
// current token is arg
if token.TType == efp.TokenTypeArgument {
for !opftStack.Empty() {
// calculate trigger
topOpt := opftStack.Peek().(efp.Token)
if err := calculate(opfdStack, topOpt); err != nil {
return efp.Token{}, err
}
opftStack.Pop()
}
if !opfdStack.Empty() {
argsList.PushBack(formulaArg{
String: opfdStack.Pop().(efp.Token).TValue,
Type: ArgString,
})
}
continue
}
// current token is logical
if token.TType == efp.OperatorsInfix && token.TSubType == efp.TokenSubTypeLogical {
}
// current token is text
if token.TType == efp.TokenTypeOperand && token.TSubType == efp.TokenSubTypeText {
argsList.PushBack(formulaArg{
String: token.TValue,
Type: ArgString,
})
}
// current token is function stop
if token.TType == efp.TokenTypeFunction && token.TSubType == efp.TokenSubTypeStop {
for !opftStack.Empty() {
// calculate trigger
topOpt := opftStack.Peek().(efp.Token)
if err := calculate(opfdStack, topOpt); err != nil {
return efp.Token{}, err
}
opftStack.Pop()
}
// push opfd to args
if opfdStack.Len() > 0 {
argsList.PushBack(formulaArg{
String: opfdStack.Pop().(efp.Token).TValue,
Type: ArgString,
})
}
// call formula function to evaluate
result, err := callFuncByName(&formulaFuncs{}, strings.NewReplacer(
"_xlfn", "", ".", "").Replace(opfStack.Peek().(efp.Token).TValue),
[]reflect.Value{reflect.ValueOf(argsList)})
if err != nil {
return efp.Token{}, err
}
argsList.Init()
opfStack.Pop()
if opfStack.Len() > 0 { // still in function stack
opfdStack.Push(efp.Token{TValue: result, TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
} else {
opdStack.Push(efp.Token{TValue: result, TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
}
}
}
}
for optStack.Len() != 0 {
topOpt := optStack.Peek().(efp.Token)
if err = calculate(opdStack, topOpt); err != nil {
return efp.Token{}, err
}
optStack.Pop()
}
if opdStack.Len() == 0 {
return efp.Token{}, errors.New("formula not valid")
}
return opdStack.Peek().(efp.Token), err
}
// calcAdd evaluate addition arithmetic operations.
func calcAdd(opdStack *Stack) error {
if opdStack.Len() < 2 {
return errors.New("formula not valid")
}
rOpd := opdStack.Pop().(efp.Token)
lOpd := opdStack.Pop().(efp.Token)
lOpdVal, err := strconv.ParseFloat(lOpd.TValue, 64)
if err != nil {
return err
}
rOpdVal, err := strconv.ParseFloat(rOpd.TValue, 64)
if err != nil {
return err
}
result := lOpdVal + rOpdVal
opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
return nil
}
// calcSubtract evaluate subtraction arithmetic operations.
func calcSubtract(opdStack *Stack) error {
if opdStack.Len() < 2 {
return errors.New("formula not valid")
}
rOpd := opdStack.Pop().(efp.Token)
lOpd := opdStack.Pop().(efp.Token)
lOpdVal, err := strconv.ParseFloat(lOpd.TValue, 64)
if err != nil {
return err
}
rOpdVal, err := strconv.ParseFloat(rOpd.TValue, 64)
if err != nil {
return err
}
result := lOpdVal - rOpdVal
opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
return nil
}
// calcMultiply evaluate multiplication arithmetic operations.
func calcMultiply(opdStack *Stack) error {
if opdStack.Len() < 2 {
return errors.New("formula not valid")
}
rOpd := opdStack.Pop().(efp.Token)
lOpd := opdStack.Pop().(efp.Token)
lOpdVal, err := strconv.ParseFloat(lOpd.TValue, 64)
if err != nil {
return err
}
rOpdVal, err := strconv.ParseFloat(rOpd.TValue, 64)
if err != nil {
return err
}
result := lOpdVal * rOpdVal
opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
return nil
}
// calcDivide evaluate division arithmetic operations.
func calcDivide(opdStack *Stack) error {
if opdStack.Len() < 2 {
return errors.New("formula not valid")
}
rOpd := opdStack.Pop().(efp.Token)
lOpd := opdStack.Pop().(efp.Token)
lOpdVal, err := strconv.ParseFloat(lOpd.TValue, 64)
if err != nil {
return err
}
rOpdVal, err := strconv.ParseFloat(rOpd.TValue, 64)
if err != nil {
return err
}
result := lOpdVal / rOpdVal
if rOpdVal == 0 {
return errors.New(formulaErrorDIV)
}
opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
return nil
}
// calculate evaluate basic arithmetic operations.
func calculate(opdStack *Stack, opt efp.Token) error {
if opt.TValue == "-" && opt.TType == efp.TokenTypeOperatorPrefix {
if opdStack.Len() < 1 {
return errors.New("formula not valid")
}
opd := opdStack.Pop().(efp.Token)
opdVal, err := strconv.ParseFloat(opd.TValue, 64)
if err != nil {
return err
}
result := 0 - opdVal
opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
}
if opt.TValue == "+" {
if err := calcAdd(opdStack); err != nil {
return err
}
}
if opt.TValue == "-" && opt.TType == efp.TokenTypeOperatorInfix {
if err := calcSubtract(opdStack); err != nil {
return err
}
}
if opt.TValue == "*" {
if err := calcMultiply(opdStack); err != nil {
return err
}
}
if opt.TValue == "/" {
if err := calcDivide(opdStack); err != nil {
return err
}
}
return nil
}
// parseOperatorPrefixToken parse operator prefix token.
func (f *File) parseOperatorPrefixToken(optStack, opdStack *Stack, token efp.Token) (err error) {
if optStack.Len() == 0 {
optStack.Push(token)
} else {
tokenPriority := getPriority(token)
topOpt := optStack.Peek().(efp.Token)
topOptPriority := getPriority(topOpt)
if tokenPriority > topOptPriority {
optStack.Push(token)
} else {
for tokenPriority <= topOptPriority {
optStack.Pop()
if err = calculate(opdStack, topOpt); err != nil {
return
}
if optStack.Len() > 0 {
topOpt = optStack.Peek().(efp.Token)
topOptPriority = getPriority(topOpt)
continue
}
break
}
optStack.Push(token)
}
}
return
}
// isOperatorPrefixToken determine if the token is parse operator prefix
// token.
func isOperatorPrefixToken(token efp.Token) bool {
if (token.TValue == "-" && token.TType == efp.TokenTypeOperatorPrefix) ||
token.TValue == "+" || token.TValue == "-" || token.TValue == "*" || token.TValue == "/" {
return true
}
return false
}
func (f *File) getDefinedNameRefTo(definedNameName string, currentSheet string) (refTo string) {
for _, definedName := range f.GetDefinedName() {
if definedName.Name == definedNameName {
refTo = definedName.RefersTo
// worksheet scope takes precedence over scope workbook when both definedNames exist
if definedName.Scope == currentSheet {
break
}
}
}
return refTo
}
// parseToken parse basic arithmetic operator priority and evaluate based on
// operators and operands.
func (f *File) parseToken(sheet string, token efp.Token, opdStack, optStack *Stack) error {
// parse reference: must reference at here
if token.TSubType == efp.TokenSubTypeRange {
refTo := f.getDefinedNameRefTo(token.TValue, sheet)
if refTo != "" {
token.TValue = refTo
}
result, err := f.parseReference(sheet, token.TValue)
if err != nil {
return errors.New(formulaErrorNAME)
}
if result.Type != ArgString {
return errors.New(formulaErrorVALUE)
}
token.TValue = result.String
token.TType = efp.TokenTypeOperand
token.TSubType = efp.TokenSubTypeNumber
}
if isOperatorPrefixToken(token) {
if err := f.parseOperatorPrefixToken(optStack, opdStack, token); err != nil {
return err
}
}
if token.TType == efp.TokenTypeSubexpression && token.TSubType == efp.TokenSubTypeStart { // (
optStack.Push(token)
}
if token.TType == efp.TokenTypeSubexpression && token.TSubType == efp.TokenSubTypeStop { // )
for optStack.Peek().(efp.Token).TSubType != efp.TokenSubTypeStart && optStack.Peek().(efp.Token).TType != efp.TokenTypeSubexpression { // != (
topOpt := optStack.Peek().(efp.Token)
if err := calculate(opdStack, topOpt); err != nil {
return err
}
optStack.Pop()
}
optStack.Pop()
}
// opd
if token.TType == efp.TokenTypeOperand && token.TSubType == efp.TokenSubTypeNumber {
opdStack.Push(token)
}
return nil
}
// parseReference parse reference and extract values by given reference
// characters and default sheet name.
func (f *File) parseReference(sheet, reference string) (arg formulaArg, err error) {
reference = strings.Replace(reference, "$", "", -1)
refs, cellRanges, cellRefs := list.New(), list.New(), list.New()
for _, ref := range strings.Split(reference, ":") {
tokens := strings.Split(ref, "!")
cr := cellRef{}
if len(tokens) == 2 { // have a worksheet name
cr.Sheet = tokens[0]
if cr.Col, cr.Row, err = CellNameToCoordinates(tokens[1]); err != nil {
return
}
if refs.Len() > 0 {
e := refs.Back()
cellRefs.PushBack(e.Value.(cellRef))
refs.Remove(e)
}
refs.PushBack(cr)
continue
}
if cr.Col, cr.Row, err = CellNameToCoordinates(tokens[0]); err != nil {
return
}
e := refs.Back()
if e == nil {
cr.Sheet = sheet
refs.PushBack(cr)
continue
}
cellRanges.PushBack(cellRange{
From: e.Value.(cellRef),
To: cr,
})
refs.Remove(e)
}
if refs.Len() > 0 {
e := refs.Back()
cellRefs.PushBack(e.Value.(cellRef))
refs.Remove(e)
}
arg, err = f.rangeResolver(cellRefs, cellRanges)
return
}
// prepareValueRange prepare value range.
func prepareValueRange(cr cellRange, valueRange []int) {
if cr.From.Row < valueRange[0] || valueRange[0] == 0 {
valueRange[0] = cr.From.Row
}
if cr.From.Col < valueRange[2] || valueRange[2] == 0 {
valueRange[2] = cr.From.Col
}
if cr.To.Row > valueRange[1] || valueRange[1] == 0 {
valueRange[1] = cr.To.Row
}
if cr.To.Col > valueRange[3] || valueRange[3] == 0 {
valueRange[3] = cr.To.Col
}
}
// prepareValueRef prepare value reference.
func prepareValueRef(cr cellRef, valueRange []int) {
if cr.Row < valueRange[0] || valueRange[0] == 0 {
valueRange[0] = cr.Row
}
if cr.Col < valueRange[2] || valueRange[2] == 0 {
valueRange[2] = cr.Col
}
if cr.Row > valueRange[1] || valueRange[1] == 0 {
valueRange[1] = cr.Row
}
if cr.Col > valueRange[3] || valueRange[3] == 0 {
valueRange[3] = cr.Col
}
}
// rangeResolver extract value as string from given reference and range list.
// This function will not ignore the empty cell. For example, A1:A2:A2:B3 will
// be reference A1:B3.
func (f *File) rangeResolver(cellRefs, cellRanges *list.List) (arg formulaArg, err error) {
// value range order: from row, to row, from column, to column
valueRange := []int{0, 0, 0, 0}
var sheet string
// prepare value range
for temp := cellRanges.Front(); temp != nil; temp = temp.Next() {
cr := temp.Value.(cellRange)
if cr.From.Sheet != cr.To.Sheet {
err = errors.New(formulaErrorVALUE)
}
rng := []int{cr.From.Col, cr.From.Row, cr.To.Col, cr.To.Row}
sortCoordinates(rng)
cr.From.Col, cr.From.Row, cr.To.Col, cr.To.Row = rng[0], rng[1], rng[2], rng[3]
prepareValueRange(cr, valueRange)
if cr.From.Sheet != "" {
sheet = cr.From.Sheet
}
}
for temp := cellRefs.Front(); temp != nil; temp = temp.Next() {
cr := temp.Value.(cellRef)
if cr.Sheet != "" {
sheet = cr.Sheet
}
prepareValueRef(cr, valueRange)
}
// extract value from ranges
if cellRanges.Len() > 0 {
arg.Type = ArgMatrix
for row := valueRange[0]; row <= valueRange[1]; row++ {
var matrixRow = []formulaArg{}
for col := valueRange[2]; col <= valueRange[3]; col++ {
var cell, value string
if cell, err = CoordinatesToCellName(col, row); err != nil {
return
}
if value, err = f.GetCellValue(sheet, cell); err != nil {
return
}
matrixRow = append(matrixRow, formulaArg{
String: value,
Type: ArgString,
})
}
arg.Matrix = append(arg.Matrix, matrixRow)
}
return
}
// extract value from references
for temp := cellRefs.Front(); temp != nil; temp = temp.Next() {
cr := temp.Value.(cellRef)
var cell string
if cell, err = CoordinatesToCellName(cr.Col, cr.Row); err != nil {
return
}
if arg.String, err = f.GetCellValue(cr.Sheet, cell); err != nil {
return
}
arg.Type = ArgString
}
return
}
// callFuncByName calls the no error or only error return function with
// reflect by given receiver, name and parameters.
func callFuncByName(receiver interface{}, name string, params []reflect.Value) (result string, err error) {
function := reflect.ValueOf(receiver).MethodByName(name)
if function.IsValid() {
rt := function.Call(params)
if len(rt) == 0 {
return
}
if !rt[1].IsNil() {
err = rt[1].Interface().(error)
return
}
result = rt[0].Interface().(string)
return
}
err = fmt.Errorf("not support %s function", name)
return
}
// formulaCriteriaParser parse formula criteria.
func formulaCriteriaParser(exp string) (fc *formulaCriteria) {
fc = &formulaCriteria{}
if exp == "" {
return
}
if match := regexp.MustCompile(`^([0-9]+)$`).FindStringSubmatch(exp); len(match) > 1 {
fc.Type, fc.Condition = criteriaEq, match[1]
return
}
if match := regexp.MustCompile(`^=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
fc.Type, fc.Condition = criteriaEq, match[1]
return
}
if match := regexp.MustCompile(`^<(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
fc.Type, fc.Condition = criteriaLe, match[1]
return
}
if match := regexp.MustCompile(`^>(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
fc.Type, fc.Condition = criteriaGe, match[1]
return
}
if match := regexp.MustCompile(`^<=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
fc.Type, fc.Condition = criteriaL, match[1]
return
}
if match := regexp.MustCompile(`^>=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
fc.Type, fc.Condition = criteriaG, match[1]
return
}
if strings.Contains(exp, "*") {
if strings.HasPrefix(exp, "*") {
fc.Type, fc.Condition = criteriaEnd, strings.TrimPrefix(exp, "*")
}
if strings.HasSuffix(exp, "*") {
fc.Type, fc.Condition = criteriaBeg, strings.TrimSuffix(exp, "*")
}
return
}
fc.Type, fc.Condition = criteriaEq, exp
return
}
// formulaCriteriaEval evaluate formula criteria expression.
func formulaCriteriaEval(val string, criteria *formulaCriteria) (result bool, err error) {
var value, expected float64
var prepareValue = func(val, cond string) (value float64, expected float64, err error) {
value, _ = strconv.ParseFloat(val, 64)
if expected, err = strconv.ParseFloat(criteria.Condition, 64); err != nil {
return
}
return
}
switch criteria.Type {
case criteriaEq:
return val == criteria.Condition, err
case criteriaLe:
if value, expected, err = prepareValue(val, criteria.Condition); err != nil {
return
}
return value <= expected, err
case criteriaGe:
if value, expected, err = prepareValue(val, criteria.Condition); err != nil {
return
}
return value >= expected, err
case criteriaL:
if value, expected, err = prepareValue(val, criteria.Condition); err != nil {
return
}
return value < expected, err
case criteriaG:
if value, expected, err = prepareValue(val, criteria.Condition); err != nil {
return
}
return value > expected, err
case criteriaBeg:
return strings.HasPrefix(val, criteria.Condition), err
case criteriaEnd:
return strings.HasSuffix(val, criteria.Condition), err
}
return
}
// Math and Trigonometric functions
// ABS function returns the absolute value of any supplied number. The syntax
// of the function is:
//
// ABS(number)
//
func (fn *formulaFuncs) ABS(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ABS requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Abs(val))
return
}
// ACOS function calculates the arccosine (i.e. the inverse cosine) of a given
// number, and returns an angle, in radians, between 0 and π. The syntax of
// the function is:
//
// ACOS(number)
//
func (fn *formulaFuncs) ACOS(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ACOS requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Acos(val))
return
}
// ACOSH function calculates the inverse hyperbolic cosine of a supplied number.
// of the function is:
//
// ACOSH(number)
//
func (fn *formulaFuncs) ACOSH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ACOSH requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Acosh(val))
return
}
// ACOT function calculates the arccotangent (i.e. the inverse cotangent) of a
// given number, and returns an angle, in radians, between 0 and π. The syntax
// of the function is:
//
// ACOT(number)
//
func (fn *formulaFuncs) ACOT(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ACOT requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Pi/2-math.Atan(val))
return
}
// ACOTH function calculates the hyperbolic arccotangent (coth) of a supplied
// value. The syntax of the function is:
//
// ACOTH(number)
//
func (fn *formulaFuncs) ACOTH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ACOTH requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Atanh(1/val))
return
}
// ARABIC function converts a Roman numeral into an Arabic numeral. The syntax
// of the function is:
//
// ARABIC(text)
//
func (fn *formulaFuncs) ARABIC(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ARABIC requires 1 numeric argument")
return
}
charMap := map[rune]float64{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
val, last, prefix := 0.0, 0.0, 1.0
for _, char := range argsList.Front().Value.(formulaArg).String {
digit := 0.0
if char == '-' {
prefix = -1
continue
}
digit, _ = charMap[char]
val += digit
switch {
case last == digit && (last == 5 || last == 50 || last == 500):
result = formulaErrorVALUE
return
case 2*last == digit:
result = formulaErrorVALUE
return
}
if last < digit {
val -= 2 * last
}
last = digit
}
result = fmt.Sprintf("%g", prefix*val)
return
}
// ASIN function calculates the arcsine (i.e. the inverse sine) of a given
// number, and returns an angle, in radians, between -π/2 and π/2. The syntax
// of the function is:
//
// ASIN(number)
//
func (fn *formulaFuncs) ASIN(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ASIN requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Asin(val))
return
}
// ASINH function calculates the inverse hyperbolic sine of a supplied number.
// The syntax of the function is:
//
// ASINH(number)
//
func (fn *formulaFuncs) ASINH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ASINH requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Asinh(val))
return
}
// ATAN function calculates the arctangent (i.e. the inverse tangent) of a
// given number, and returns an angle, in radians, between -π/2 and +π/2. The
// syntax of the function is:
//
// ATAN(number)
//
func (fn *formulaFuncs) ATAN(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ATAN requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Atan(val))
return
}
// ATANH function calculates the inverse hyperbolic tangent of a supplied
// number. The syntax of the function is:
//
// ATANH(number)
//
func (fn *formulaFuncs) ATANH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ATANH requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Atanh(val))
return
}
// ATAN2 function calculates the arctangent (i.e. the inverse tangent) of a
// given set of x and y coordinates, and returns an angle, in radians, between
// -π/2 and +π/2. The syntax of the function is:
//
// ATAN2(x_num,y_num)
//
func (fn *formulaFuncs) ATAN2(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("ATAN2 requires 2 numeric arguments")
return
}
var x, y float64
if x, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if y, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Atan2(x, y))
return
}
// BASE function converts a number into a supplied base (radix), and returns a
// text representation of the calculated value. The syntax of the function is:
//
// BASE(number,radix,[min_length])
//
func (fn *formulaFuncs) BASE(argsList *list.List) (result string, err error) {
if argsList.Len() < 2 {
err = errors.New("BASE requires at least 2 arguments")
return
}
if argsList.Len() > 3 {
err = errors.New("BASE allows at most 3 arguments")
return
}
var number float64
var radix, minLength int
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if radix, err = strconv.Atoi(argsList.Front().Next().Value.(formulaArg).String); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if radix < 2 || radix > 36 {
err = errors.New("radix must be an integer >= 2 and <= 36")
return
}
if argsList.Len() > 2 {
if minLength, err = strconv.Atoi(argsList.Back().Value.(formulaArg).String); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
}
result = strconv.FormatInt(int64(number), radix)
if len(result) < minLength {
result = strings.Repeat("0", minLength-len(result)) + result
}
result = strings.ToUpper(result)
return
}
// CEILING function rounds a supplied number away from zero, to the nearest
// multiple of a given number. The syntax of the function is:
//
// CEILING(number,significance)
//
func (fn *formulaFuncs) CEILING(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("CEILING requires at least 1 argument")
return
}
if argsList.Len() > 2 {
err = errors.New("CEILING allows at most 2 arguments")
return
}
number, significance, res := 0.0, 1.0, 0.0
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if number < 0 {
significance = -1
}
if argsList.Len() > 1 {
if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
}
if significance < 0 && number > 0 {
err = errors.New("negative sig to CEILING invalid")
return
}
if argsList.Len() == 1 {
result = fmt.Sprintf("%g", math.Ceil(number))
return
}
number, res = math.Modf(number / significance)
if res > 0 {
number++
}
result = fmt.Sprintf("%g", number*significance)
return
}
// CEILINGMATH function rounds a supplied number up to a supplied multiple of
// significance. The syntax of the function is:
//
// CEILING.MATH(number,[significance],[mode])
//
func (fn *formulaFuncs) CEILINGMATH(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("CEILING.MATH requires at least 1 argument")
return
}
if argsList.Len() > 3 {
err = errors.New("CEILING.MATH allows at most 3 arguments")
return
}
number, significance, mode := 0.0, 1.0, 1.0
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if number < 0 {
significance = -1
}
if argsList.Len() > 1 {
if significance, err = strconv.ParseFloat(argsList.Front().Next().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
}
if argsList.Len() == 1 {
result = fmt.Sprintf("%g", math.Ceil(number))
return
}
if argsList.Len() > 2 {
if mode, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
}
val, res := math.Modf(number / significance)
if res != 0 {
if number > 0 {
val++
} else if mode < 0 {
val--
}
}
result = fmt.Sprintf("%g", val*significance)
return
}
// CEILINGPRECISE function rounds a supplied number up (regardless of the
// number's sign), to the nearest multiple of a given number. The syntax of
// the function is:
//
// CEILING.PRECISE(number,[significance])
//
func (fn *formulaFuncs) CEILINGPRECISE(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("CEILING.PRECISE requires at least 1 argument")
return
}
if argsList.Len() > 2 {
err = errors.New("CEILING.PRECISE allows at most 2 arguments")
return
}
number, significance := 0.0, 1.0
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if number < 0 {
significance = -1
}
if argsList.Len() == 1 {
result = fmt.Sprintf("%g", math.Ceil(number))
return
}
if argsList.Len() > 1 {
if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
significance = math.Abs(significance)
if significance == 0 {
result = "0"
return
}
}
val, res := math.Modf(number / significance)
if res != 0 {
if number > 0 {
val++
}
}
result = fmt.Sprintf("%g", val*significance)
return
}
// COMBIN function calculates the number of combinations (in any order) of a
// given number objects from a set. The syntax of the function is:
//
// COMBIN(number,number_chosen)
//
func (fn *formulaFuncs) COMBIN(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("COMBIN requires 2 argument")
return
}
number, chosen, val := 0.0, 0.0, 1.0
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if chosen, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
number, chosen = math.Trunc(number), math.Trunc(chosen)
if chosen > number {
err = errors.New("COMBIN requires number >= number_chosen")
return
}
if chosen == number || chosen == 0 {
result = "1"
return
}
for c := float64(1); c <= chosen; c++ {
val *= (number + 1 - c) / c
}
result = fmt.Sprintf("%g", math.Ceil(val))
return
}
// COMBINA function calculates the number of combinations, with repetitions,
// of a given number objects from a set. The syntax of the function is:
//
// COMBINA(number,number_chosen)
//
func (fn *formulaFuncs) COMBINA(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("COMBINA requires 2 argument")
return
}
var number, chosen float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if chosen, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
number, chosen = math.Trunc(number), math.Trunc(chosen)
if number < chosen {
err = errors.New("COMBINA requires number > number_chosen")
return
}
if number == 0 {
result = "0"
return
}
args := list.New()
args.PushBack(formulaArg{
String: fmt.Sprintf("%g", number+chosen-1),
Type: ArgString,
})
args.PushBack(formulaArg{
String: fmt.Sprintf("%g", number-1),
Type: ArgString,
})
return fn.COMBIN(args)
}
// COS function calculates the cosine of a given angle. The syntax of the
// function is:
//
// COS(number)
//
func (fn *formulaFuncs) COS(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("COS requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Cos(val))
return
}
// COSH function calculates the hyperbolic cosine (cosh) of a supplied number.
// The syntax of the function is:
//
// COSH(number)
//
func (fn *formulaFuncs) COSH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("COSH requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Cosh(val))
return
}
// COT function calculates the cotangent of a given angle. The syntax of the
// function is:
//
// COT(number)
//
func (fn *formulaFuncs) COT(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("COT requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if val == 0 {
err = errors.New(formulaErrorDIV)
return
}
result = fmt.Sprintf("%g", math.Tan(val))
return
}
// COTH function calculates the hyperbolic cotangent (coth) of a supplied
// angle. The syntax of the function is:
//
// COTH(number)
//
func (fn *formulaFuncs) COTH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("COTH requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if val == 0 {
err = errors.New(formulaErrorDIV)
return
}
result = fmt.Sprintf("%g", math.Tanh(val))
return
}
// CSC function calculates the cosecant of a given angle. The syntax of the
// function is:
//
// CSC(number)
//
func (fn *formulaFuncs) CSC(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("CSC requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if val == 0 {
err = errors.New(formulaErrorDIV)
return
}
result = fmt.Sprintf("%g", 1/math.Sin(val))
return
}
// CSCH function calculates the hyperbolic cosecant (csch) of a supplied
// angle. The syntax of the function is:
//
// CSCH(number)
//
func (fn *formulaFuncs) CSCH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("CSCH requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if val == 0 {
err = errors.New(formulaErrorDIV)
return
}
result = fmt.Sprintf("%g", 1/math.Sinh(val))
return
}
// DECIMAL function converts a text representation of a number in a specified
// base, into a decimal value. The syntax of the function is:
//
// DECIMAL(text,radix)
//
func (fn *formulaFuncs) DECIMAL(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("DECIMAL requires 2 numeric arguments")
return
}
var text = argsList.Front().Value.(formulaArg).String
var radix int
if radix, err = strconv.Atoi(argsList.Back().Value.(formulaArg).String); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if len(text) > 2 && (strings.HasPrefix(text, "0x") || strings.HasPrefix(text, "0X")) {
text = text[2:]
}
val, err := strconv.ParseInt(text, radix, 64)
if err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", float64(val))
return
}
// DEGREES function converts radians into degrees. The syntax of the function
// is:
//
// DEGREES(angle)
//
func (fn *formulaFuncs) DEGREES(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("DEGREES requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if val == 0 {
err = errors.New(formulaErrorDIV)
return
}
result = fmt.Sprintf("%g", 180.0/math.Pi*val)
return
}
// EVEN function rounds a supplied number away from zero (i.e. rounds a
// positive number up and a negative number down), to the next even number.
// The syntax of the function is:
//
// EVEN(number)
//
func (fn *formulaFuncs) EVEN(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("EVEN requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
sign := math.Signbit(number)
m, frac := math.Modf(number / 2)
val := m * 2
if frac != 0 {
if !sign {
val += 2
} else {
val -= 2
}
}
result = fmt.Sprintf("%g", val)
return
}
// EXP function calculates the value of the mathematical constant e, raised to
// the power of a given number. The syntax of the function is:
//
// EXP(number)
//
func (fn *formulaFuncs) EXP(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("EXP requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = strings.ToUpper(fmt.Sprintf("%g", math.Exp(number)))
return
}
// fact returns the factorial of a supplied number.
func fact(number float64) float64 {
val := float64(1)
for i := float64(2); i <= number; i++ {
val *= i
}
return val
}
// FACT function returns the factorial of a supplied number. The syntax of the
// function is:
//
// FACT(number)
//
func (fn *formulaFuncs) FACT(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("FACT requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if number < 0 {
err = errors.New(formulaErrorNUM)
}
result = strings.ToUpper(fmt.Sprintf("%g", fact(number)))
return
}
// FACTDOUBLE function returns the double factorial of a supplied number. The
// syntax of the function is:
//
// FACTDOUBLE(number)
//
func (fn *formulaFuncs) FACTDOUBLE(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("FACTDOUBLE requires 1 numeric argument")
return
}
number, val := 0.0, 1.0
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if number < 0 {
err = errors.New(formulaErrorNUM)
return
}
for i := math.Trunc(number); i > 1; i -= 2 {
val *= i
}
result = strings.ToUpper(fmt.Sprintf("%g", val))
return
}
// FLOOR function rounds a supplied number towards zero to the nearest
// multiple of a specified significance. The syntax of the function is:
//
// FLOOR(number,significance)
//
func (fn *formulaFuncs) FLOOR(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("FLOOR requires 2 numeric arguments")
return
}
var number, significance float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if significance < 0 && number >= 0 {
err = errors.New(formulaErrorNUM)
return
}
val := number
val, res := math.Modf(val / significance)
if res != 0 {
if number < 0 && res < 0 {
val--
}
}
result = strings.ToUpper(fmt.Sprintf("%g", val*significance))
return
}
// FLOORMATH function rounds a supplied number down to a supplied multiple of
// significance. The syntax of the function is:
//
// FLOOR.MATH(number,[significance],[mode])
//
func (fn *formulaFuncs) FLOORMATH(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("FLOOR.MATH requires at least 1 argument")
return
}
if argsList.Len() > 3 {
err = errors.New("FLOOR.MATH allows at most 3 arguments")
return
}
number, significance, mode := 0.0, 1.0, 1.0
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if number < 0 {
significance = -1
}
if argsList.Len() > 1 {
if significance, err = strconv.ParseFloat(argsList.Front().Next().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
}
if argsList.Len() == 1 {
result = fmt.Sprintf("%g", math.Floor(number))
return
}
if argsList.Len() > 2 {
if mode, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
}
val, res := math.Modf(number / significance)
if res != 0 && number < 0 && mode > 0 {
val--
}
result = fmt.Sprintf("%g", val*significance)
return
}
// FLOORPRECISE function rounds a supplied number down to a supplied multiple
// of significance. The syntax of the function is:
//
// FLOOR.PRECISE(number,[significance])
//
func (fn *formulaFuncs) FLOORPRECISE(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("FLOOR.PRECISE requires at least 1 argument")
return
}
if argsList.Len() > 2 {
err = errors.New("FLOOR.PRECISE allows at most 2 arguments")
return
}
var number, significance float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if number < 0 {
significance = -1
}
if argsList.Len() == 1 {
result = fmt.Sprintf("%g", math.Floor(number))
return
}
if argsList.Len() > 1 {
if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
significance = math.Abs(significance)
if significance == 0 {
result = "0"
return
}
}
val, res := math.Modf(number / significance)
if res != 0 {
if number < 0 {
val--
}
}
result = fmt.Sprintf("%g", val*significance)
return
}
// gcd returns the greatest common divisor of two supplied integers.
func gcd(x, y float64) float64 {
x, y = math.Trunc(x), math.Trunc(y)
if x == 0 {
return y
}
if y == 0 {
return x
}
for x != y {
if x > y {
x = x - y
} else {
y = y - x
}
}
return x
}
// GCD function returns the greatest common divisor of two or more supplied
// integers. The syntax of the function is:
//
// GCD(number1,[number2],...)
//
func (fn *formulaFuncs) GCD(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("GCD requires at least 1 argument")
return
}
var (
val float64
nums = []float64{}
)
for arg := argsList.Front(); arg != nil; arg = arg.Next() {
token := arg.Value.(formulaArg).String
if token == "" {
continue
}
if val, err = strconv.ParseFloat(token, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
nums = append(nums, val)
}
if nums[0] < 0 {
err = errors.New("GCD only accepts positive arguments")
return
}
if len(nums) == 1 {
result = fmt.Sprintf("%g", nums[0])
return
}
cd := nums[0]
for i := 1; i < len(nums); i++ {
if nums[i] < 0 {
err = errors.New("GCD only accepts positive arguments")
return
}
cd = gcd(cd, nums[i])
}
result = fmt.Sprintf("%g", cd)
return
}
// INT function truncates a supplied number down to the closest integer. The
// syntax of the function is:
//
// INT(number)
//
func (fn *formulaFuncs) INT(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("INT requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
val, frac := math.Modf(number)
if frac < 0 {
val--
}
result = fmt.Sprintf("%g", val)
return
}
// ISOCEILING function rounds a supplied number up (regardless of the number's
// sign), to the nearest multiple of a supplied significance. The syntax of
// the function is:
//
// ISO.CEILING(number,[significance])
//
func (fn *formulaFuncs) ISOCEILING(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("ISO.CEILING requires at least 1 argument")
return
}
if argsList.Len() > 2 {
err = errors.New("ISO.CEILING allows at most 2 arguments")
return
}
var number, significance float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if number < 0 {
significance = -1
}
if argsList.Len() == 1 {
result = fmt.Sprintf("%g", math.Ceil(number))
return
}
if argsList.Len() > 1 {
if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
significance = math.Abs(significance)
if significance == 0 {
result = "0"
return
}
}
val, res := math.Modf(number / significance)
if res != 0 {
if number > 0 {
val++
}
}
result = fmt.Sprintf("%g", val*significance)
return
}
// lcm returns the least common multiple of two supplied integers.
func lcm(a, b float64) float64 {
a = math.Trunc(a)
b = math.Trunc(b)
if a == 0 && b == 0 {
return 0
}
return a * b / gcd(a, b)
}
// LCM function returns the least common multiple of two or more supplied
// integers. The syntax of the function is:
//
// LCM(number1,[number2],...)
//
func (fn *formulaFuncs) LCM(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("LCM requires at least 1 argument")
return
}
var (
val float64
nums = []float64{}
)
for arg := argsList.Front(); arg != nil; arg = arg.Next() {
token := arg.Value.(formulaArg).String
if token == "" {
continue
}
if val, err = strconv.ParseFloat(token, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
nums = append(nums, val)
}
if nums[0] < 0 {
err = errors.New("LCM only accepts positive arguments")
return
}
if len(nums) == 1 {
result = fmt.Sprintf("%g", nums[0])
return
}
cm := nums[0]
for i := 1; i < len(nums); i++ {
if nums[i] < 0 {
err = errors.New("LCM only accepts positive arguments")
return
}
cm = lcm(cm, nums[i])
}
result = fmt.Sprintf("%g", cm)
return
}
// LN function calculates the natural logarithm of a given number. The syntax
// of the function is:
//
// LN(number)
//
func (fn *formulaFuncs) LN(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("LN requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Log(number))
return
}
// LOG function calculates the logarithm of a given number, to a supplied
// base. The syntax of the function is:
//
// LOG(number,[base])
//
func (fn *formulaFuncs) LOG(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("LOG requires at least 1 argument")
return
}
if argsList.Len() > 2 {
err = errors.New("LOG allows at most 2 arguments")
return
}
number, base := 0.0, 10.0
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if argsList.Len() > 1 {
if base, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
}
if number == 0 {
err = errors.New(formulaErrorNUM)
return
}
if base == 0 {
err = errors.New(formulaErrorNUM)
return
}
if base == 1 {
err = errors.New(formulaErrorDIV)
return
}
result = fmt.Sprintf("%g", math.Log(number)/math.Log(base))
return
}
// LOG10 function calculates the base 10 logarithm of a given number. The
// syntax of the function is:
//
// LOG10(number)
//
func (fn *formulaFuncs) LOG10(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("LOG10 requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Log10(number))
return
}
func minor(sqMtx [][]float64, idx int) [][]float64 {
ret := [][]float64{}
for i := range sqMtx {
if i == 0 {
continue
}
row := []float64{}
for j := range sqMtx {
if j == idx {
continue
}
row = append(row, sqMtx[i][j])
}
ret = append(ret, row)
}
return ret
}
// det determinant of the 2x2 matrix.
func det(sqMtx [][]float64) float64 {
if len(sqMtx) == 2 {
m00 := sqMtx[0][0]
m01 := sqMtx[0][1]
m10 := sqMtx[1][0]
m11 := sqMtx[1][1]
return m00*m11 - m10*m01
}
var res, sgn float64 = 0, 1
for j := range sqMtx {
res += sgn * sqMtx[0][j] * det(minor(sqMtx, j))
sgn *= -1
}
return res
}
// MDETERM calculates the determinant of a square matrix. The
// syntax of the function is:
//
// MDETERM(array)
//
func (fn *formulaFuncs) MDETERM(argsList *list.List) (result string, err error) {
var num float64
var numMtx = [][]float64{}
var strMtx = argsList.Front().Value.(formulaArg).Matrix
if argsList.Len() < 1 {
return
}
var rows = len(strMtx)
for _, row := range argsList.Front().Value.(formulaArg).Matrix {
if len(row) != rows {
err = errors.New(formulaErrorVALUE)
return
}
numRow := []float64{}
for _, ele := range row {
if num, err = strconv.ParseFloat(ele.String, 64); err != nil {
return
}
numRow = append(numRow, num)
}
numMtx = append(numMtx, numRow)
}
result = fmt.Sprintf("%g", det(numMtx))
return
}
// MOD function returns the remainder of a division between two supplied
// numbers. The syntax of the function is:
//
// MOD(number,divisor)
//
func (fn *formulaFuncs) MOD(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("MOD requires 2 numeric arguments")
return
}
var number, divisor float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if divisor, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if divisor == 0 {
err = errors.New(formulaErrorDIV)
return
}
trunc, rem := math.Modf(number / divisor)
if rem < 0 {
trunc--
}
result = fmt.Sprintf("%g", number-divisor*trunc)
return
}
// MROUND function rounds a supplied number up or down to the nearest multiple
// of a given number. The syntax of the function is:
//
// MOD(number,multiple)
//
func (fn *formulaFuncs) MROUND(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("MROUND requires 2 numeric arguments")
return
}
var number, multiple float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if multiple, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if multiple == 0 {
err = errors.New(formulaErrorNUM)
return
}
if multiple < 0 && number > 0 ||
multiple > 0 && number < 0 {
err = errors.New(formulaErrorNUM)
return
}
number, res := math.Modf(number / multiple)
if math.Trunc(res+0.5) > 0 {
number++
}
result = fmt.Sprintf("%g", number*multiple)
return
}
// MULTINOMIAL function calculates the ratio of the factorial of a sum of
// supplied values to the product of factorials of those values. The syntax of
// the function is:
//
// MULTINOMIAL(number1,[number2],...)
//
func (fn *formulaFuncs) MULTINOMIAL(argsList *list.List) (result string, err error) {
val, num, denom := 0.0, 0.0, 1.0
for arg := argsList.Front(); arg != nil; arg = arg.Next() {
token := arg.Value.(formulaArg)
if token.String == "" {
continue
}
if val, err = strconv.ParseFloat(token.String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
num += val
denom *= fact(val)
}
result = fmt.Sprintf("%g", fact(num)/denom)
return
}
// MUNIT function returns the unit matrix for a specified dimension. The
// syntax of the function is:
//
// MUNIT(dimension)
//
func (fn *formulaFuncs) MUNIT(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("MUNIT requires 1 numeric argument")
return
}
var dimension int
if dimension, err = strconv.Atoi(argsList.Front().Value.(formulaArg).String); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
matrix := make([][]float64, 0, dimension)
for i := 0; i < dimension; i++ {
row := make([]float64, dimension)
for j := 0; j < dimension; j++ {
if i == j {
row[j] = float64(1.0)
} else {
row[j] = float64(0.0)
}
}
matrix = append(matrix, row)
}
return
}
// ODD function ounds a supplied number away from zero (i.e. rounds a positive
// number up and a negative number down), to the next odd number. The syntax
// of the function is:
//
// ODD(number)
//
func (fn *formulaFuncs) ODD(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ODD requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if number == 0 {
result = "1"
return
}
sign := math.Signbit(number)
m, frac := math.Modf((number - 1) / 2)
val := m*2 + 1
if frac != 0 {
if !sign {
val += 2
} else {
val -= 2
}
}
result = fmt.Sprintf("%g", val)
return
}
// PI function returns the value of the mathematical constant π (pi), accurate
// to 15 digits (14 decimal places). The syntax of the function is:
//
// PI()
//
func (fn *formulaFuncs) PI(argsList *list.List) (result string, err error) {
if argsList.Len() != 0 {
err = errors.New("PI accepts no arguments")
return
}
result = fmt.Sprintf("%g", math.Pi)
return
}
// POWER function calculates a given number, raised to a supplied power.
// The syntax of the function is:
//
// POWER(number,power)
//
func (fn *formulaFuncs) POWER(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("POWER requires 2 numeric arguments")
return
}
var x, y float64
if x, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if y, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if x == 0 && y == 0 {
err = errors.New(formulaErrorNUM)
return
}
if x == 0 && y < 0 {
err = errors.New(formulaErrorDIV)
return
}
result = fmt.Sprintf("%g", math.Pow(x, y))
return
}
// PRODUCT function returns the product (multiplication) of a supplied set of
// numerical values. The syntax of the function is:
//
// PRODUCT(number1,[number2],...)
//
func (fn *formulaFuncs) PRODUCT(argsList *list.List) (result string, err error) {
val, product := 0.0, 1.0
for arg := argsList.Front(); arg != nil; arg = arg.Next() {
token := arg.Value.(formulaArg)
switch token.Type {
case ArgUnknown:
continue
case ArgString:
if token.String == "" {
continue
}
if val, err = strconv.ParseFloat(token.String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
product = product * val
case ArgMatrix:
for _, row := range token.Matrix {
for _, value := range row {
if value.String == "" {
continue
}
if val, err = strconv.ParseFloat(value.String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
product = product * val
}
}
}
}
result = fmt.Sprintf("%g", product)
return
}
// QUOTIENT function returns the integer portion of a division between two
// supplied numbers. The syntax of the function is:
//
// QUOTIENT(numerator,denominator)
//
func (fn *formulaFuncs) QUOTIENT(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("QUOTIENT requires 2 numeric arguments")
return
}
var x, y float64
if x, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if y, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if y == 0 {
err = errors.New(formulaErrorDIV)
return
}
result = fmt.Sprintf("%g", math.Trunc(x/y))
return
}
// RADIANS function converts radians into degrees. The syntax of the function is:
//
// RADIANS(angle)
//
func (fn *formulaFuncs) RADIANS(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("RADIANS requires 1 numeric argument")
return
}
var angle float64
if angle, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Pi/180.0*angle)
return
}
// RAND function generates a random real number between 0 and 1. The syntax of
// the function is:
//
// RAND()
//
func (fn *formulaFuncs) RAND(argsList *list.List) (result string, err error) {
if argsList.Len() != 0 {
err = errors.New("RAND accepts no arguments")
return
}
result = fmt.Sprintf("%g", rand.New(rand.NewSource(time.Now().UnixNano())).Float64())
return
}
// RANDBETWEEN function generates a random integer between two supplied
// integers. The syntax of the function is:
//
// RANDBETWEEN(bottom,top)
//
func (fn *formulaFuncs) RANDBETWEEN(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("RANDBETWEEN requires 2 numeric arguments")
return
}
var bottom, top int64
if bottom, err = strconv.ParseInt(argsList.Front().Value.(formulaArg).String, 10, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if top, err = strconv.ParseInt(argsList.Back().Value.(formulaArg).String, 10, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if top < bottom {
err = errors.New(formulaErrorNUM)
return
}
result = fmt.Sprintf("%g", float64(rand.New(rand.NewSource(time.Now().UnixNano())).Int63n(top-bottom+1)+bottom))
return
}
// romanNumerals defined a numeral system that originated in ancient Rome and
// remained the usual way of writing numbers throughout Europe well into the
// Late Middle Ages.
type romanNumerals struct {
n float64
s string
}
var romanTable = [][]romanNumerals{{{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}},
{{1000, "M"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {450, "LD"}, {400, "CD"}, {100, "C"}, {95, "VC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}},
{{1000, "M"}, {990, "XM"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {490, "XD"}, {450, "LD"}, {400, "CD"}, {100, "C"}, {99, "IC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}},
{{1000, "M"}, {995, "VM"}, {990, "XM"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {495, "VD"}, {490, "XD"}, {450, "LD"}, {400, "CD"}, {100, "C"}, {99, "IC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}},
{{1000, "M"}, {999, "IM"}, {995, "VM"}, {990, "XM"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {499, "ID"}, {495, "VD"}, {490, "XD"}, {450, "LD"}, {400, "CD"}, {100, "C"}, {99, "IC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}}}
// ROMAN function converts an arabic number to Roman. I.e. for a supplied
// integer, the function returns a text string depicting the roman numeral
// form of the number. The syntax of the function is:
//
// ROMAN(number,[form])
//
func (fn *formulaFuncs) ROMAN(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("ROMAN requires at least 1 argument")
return
}
if argsList.Len() > 2 {
err = errors.New("ROMAN allows at most 2 arguments")
return
}
var number float64
var form int
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if argsList.Len() > 1 {
if form, err = strconv.Atoi(argsList.Back().Value.(formulaArg).String); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if form < 0 {
form = 0
} else if form > 4 {
form = 4
}
}
decimalTable := romanTable[0]
switch form {
case 1:
decimalTable = romanTable[1]
case 2:
decimalTable = romanTable[2]
case 3:
decimalTable = romanTable[3]
case 4:
decimalTable = romanTable[4]
}
val := math.Trunc(number)
buf := bytes.Buffer{}
for _, r := range decimalTable {
for val >= r.n {
buf.WriteString(r.s)
val -= r.n
}
}
result = buf.String()
return
}
type roundMode byte
const (
closest roundMode = iota
down
up
)
// round rounds a supplied number up or down.
func (fn *formulaFuncs) round(number, digits float64, mode roundMode) float64 {
var significance float64
if digits > 0 {
significance = math.Pow(1/10.0, digits)
} else {
significance = math.Pow(10.0, -digits)
}
val, res := math.Modf(number / significance)
switch mode {
case closest:
const eps = 0.499999999
if res >= eps {
val++
} else if res <= -eps {
val--
}
case down:
case up:
if res > 0 {
val++
} else if res < 0 {
val--
}
}
return val * significance
}
// ROUND function rounds a supplied number up or down, to a specified number
// of decimal places. The syntax of the function is:
//
// ROUND(number,num_digits)
//
func (fn *formulaFuncs) ROUND(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("ROUND requires 2 numeric arguments")
return
}
var number, digits float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if digits, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", fn.round(number, digits, closest))
return
}
// ROUNDDOWN function rounds a supplied number down towards zero, to a
// specified number of decimal places. The syntax of the function is:
//
// ROUNDDOWN(number,num_digits)
//
func (fn *formulaFuncs) ROUNDDOWN(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("ROUNDDOWN requires 2 numeric arguments")
return
}
var number, digits float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if digits, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", fn.round(number, digits, down))
return
}
// ROUNDUP function rounds a supplied number up, away from zero, to a
// specified number of decimal places. The syntax of the function is:
//
// ROUNDUP(number,num_digits)
//
func (fn *formulaFuncs) ROUNDUP(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("ROUNDUP requires 2 numeric arguments")
return
}
var number, digits float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if digits, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", fn.round(number, digits, up))
return
}
// SEC function calculates the secant of a given angle. The syntax of the
// function is:
//
// SEC(number)
//
func (fn *formulaFuncs) SEC(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("SEC requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Cos(number))
return
}
// SECH function calculates the hyperbolic secant (sech) of a supplied angle.
// The syntax of the function is:
//
// SECH(number)
//
func (fn *formulaFuncs) SECH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("SECH requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", 1/math.Cosh(number))
return
}
// SIGN function returns the arithmetic sign (+1, -1 or 0) of a supplied
// number. I.e. if the number is positive, the Sign function returns +1, if
// the number is negative, the function returns -1 and if the number is 0
// (zero), the function returns 0. The syntax of the function is:
//
// SIGN(number)
//
func (fn *formulaFuncs) SIGN(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("SIGN requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if val < 0 {
result = "-1"
return
}
if val > 0 {
result = "1"
return
}
result = "0"
return
}
// SIN function calculates the sine of a given angle. The syntax of the
// function is:
//
// SIN(number)
//
func (fn *formulaFuncs) SIN(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("SIN requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Sin(number))
return
}
// SINH function calculates the hyperbolic sine (sinh) of a supplied number.
// The syntax of the function is:
//
// SINH(number)
//
func (fn *formulaFuncs) SINH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("SINH requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Sinh(number))
return
}
// SQRT function calculates the positive square root of a supplied number. The
// syntax of the function is:
//
// SQRT(number)
//
func (fn *formulaFuncs) SQRT(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("SQRT requires 1 numeric argument")
return
}
var res float64
var value = argsList.Front().Value.(formulaArg).String
if value == "" {
result = "0"
return
}
if res, err = strconv.ParseFloat(value, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if res < 0 {
err = errors.New(formulaErrorNUM)
return
}
result = fmt.Sprintf("%g", math.Sqrt(res))
return
}
// SQRTPI function returns the square root of a supplied number multiplied by
// the mathematical constant, π. The syntax of the function is:
//
// SQRTPI(number)
//
func (fn *formulaFuncs) SQRTPI(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("SQRTPI requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Sqrt(number*math.Pi))
return
}
// SUM function adds together a supplied set of numbers and returns the sum of
// these values. The syntax of the function is:
//
// SUM(number1,[number2],...)
//
func (fn *formulaFuncs) SUM(argsList *list.List) (result string, err error) {
var val, sum float64
for arg := argsList.Front(); arg != nil; arg = arg.Next() {
token := arg.Value.(formulaArg)
switch token.Type {
case ArgUnknown:
continue
case ArgString:
if token.String == "" {
continue
}
if val, err = strconv.ParseFloat(token.String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
sum += val
case ArgMatrix:
for _, row := range token.Matrix {
for _, value := range row {
if value.String == "" {
continue
}
if val, err = strconv.ParseFloat(value.String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
sum += val
}
}
}
}
result = fmt.Sprintf("%g", sum)
return
}
// SUMIF function finds the values in a supplied array, that satisfy a given
// criteria, and returns the sum of the corresponding values in a second
// supplied array. The syntax of the function is:
//
// SUMIF(range,criteria,[sum_range])
//
func (fn *formulaFuncs) SUMIF(argsList *list.List) (result string, err error) {
if argsList.Len() < 2 {
err = errors.New("SUMIF requires at least 2 argument")
return
}
var criteria = formulaCriteriaParser(argsList.Front().Next().Value.(formulaArg).String)
var rangeMtx = argsList.Front().Value.(formulaArg).Matrix
var sumRange [][]formulaArg
if argsList.Len() == 3 {
sumRange = argsList.Back().Value.(formulaArg).Matrix
}
var sum, val float64
for rowIdx, row := range rangeMtx {
for colIdx, col := range row {
var ok bool
fromVal := col.String
if col.String == "" {
continue
}
if ok, err = formulaCriteriaEval(fromVal, criteria); err != nil {
return
}
if ok {
if argsList.Len() == 3 {
if len(sumRange) <= rowIdx || len(sumRange[rowIdx]) <= colIdx {
continue
}
fromVal = sumRange[rowIdx][colIdx].String
}
if val, err = strconv.ParseFloat(fromVal, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
sum += val
}
}
}
result = fmt.Sprintf("%g", sum)
return
}
// SUMSQ function returns the sum of squares of a supplied set of values. The
// syntax of the function is:
//
// SUMSQ(number1,[number2],...)
//
func (fn *formulaFuncs) SUMSQ(argsList *list.List) (result string, err error) {
var val, sq float64
for arg := argsList.Front(); arg != nil; arg = arg.Next() {
token := arg.Value.(formulaArg)
switch token.Type {
case ArgString:
if token.String == "" {
continue
}
if val, err = strconv.ParseFloat(token.String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
sq += val * val
case ArgMatrix:
for _, row := range token.Matrix {
for _, value := range row {
if value.String == "" {
continue
}
if val, err = strconv.ParseFloat(value.String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
sq += val * val
}
}
}
}
result = fmt.Sprintf("%g", sq)
return
}
// TAN function calculates the tangent of a given angle. The syntax of the
// function is:
//
// TAN(number)
//
func (fn *formulaFuncs) TAN(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("TAN requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Tan(number))
return
}
// TANH function calculates the hyperbolic tangent (tanh) of a supplied
// number. The syntax of the function is:
//
// TANH(number)
//
func (fn *formulaFuncs) TANH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("TANH requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Tanh(number))
return
}
// TRUNC function truncates a supplied number to a specified number of decimal
// places. The syntax of the function is:
//
// TRUNC(number,[number_digits])
//
func (fn *formulaFuncs) TRUNC(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("TRUNC requires at least 1 argument")
return
}
var number, digits, adjust, rtrim float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if argsList.Len() > 1 {
if digits, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
digits = math.Floor(digits)
}
adjust = math.Pow(10, digits)
x := int((math.Abs(number) - math.Abs(float64(int(number)))) * adjust)
if x != 0 {
if rtrim, err = strconv.ParseFloat(strings.TrimRight(strconv.Itoa(x), "0"), 64); err != nil {
return
}
}
if (digits > 0) && (rtrim < adjust/10) {
result = fmt.Sprintf("%g", number)
return
}
result = fmt.Sprintf("%g", float64(int(number*adjust))/adjust)
return
}
// Statistical functions
// COUNTA function returns the number of non-blanks within a supplied set of
// cells or values. The syntax of the function is:
//
// COUNTA(value1,[value2],...)
//
func (fn *formulaFuncs) COUNTA(argsList *list.List) (result string, err error) {
var count int
for token := argsList.Front(); token != nil; token = token.Next() {
arg := token.Value.(formulaArg)
switch arg.Type {
case ArgString:
if arg.String != "" {
count++
}
case ArgMatrix:
for _, row := range arg.Matrix {
for _, value := range row {
if value.String != "" {
count++
}
}
}
}
}
result = fmt.Sprintf("%d", count)
return
}
// MEDIAN function returns the statistical median (the middle value) of a list
// of supplied numbers. The syntax of the function is:
//
// MEDIAN(number1,[number2],...)
//
func (fn *formulaFuncs) MEDIAN(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("MEDIAN requires at least 1 argument")
return
}
values := []float64{}
var median, digits float64
for token := argsList.Front(); token != nil; token = token.Next() {
arg := token.Value.(formulaArg)
switch arg.Type {
case ArgString:
if digits, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
values = append(values, digits)
case ArgMatrix:
for _, row := range arg.Matrix {
for _, value := range row {
if value.String == "" {
continue
}
if digits, err = strconv.ParseFloat(value.String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
values = append(values, digits)
}
}
}
}
sort.Float64s(values)
if len(values)%2 == 0 {
median = (values[len(values)/2-1] + values[len(values)/2]) / 2
} else {
median = values[len(values)/2]
}
result = fmt.Sprintf("%g", median)
return
}
// Information functions
// ISBLANK function tests if a specified cell is blank (empty) and if so,
// returns TRUE; Otherwise the function returns FALSE. The syntax of the
// function is:
//
// ISBLANK(value)
//
func (fn *formulaFuncs) ISBLANK(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ISBLANK requires 1 argument")
return
}
token := argsList.Front().Value.(formulaArg)
result = "FALSE"
switch token.Type {
case ArgUnknown:
result = "TRUE"
case ArgString:
if token.String == "" {
result = "TRUE"
}
}
return
}
// ISERR function tests if an initial supplied expression (or value) returns
// any Excel Error, except the #N/A error. If so, the function returns the
// logical value TRUE; If the supplied value is not an error or is the #N/A
// error, the ISERR function returns FALSE. The syntax of the function is:
//
// ISERR(value)
//
func (fn *formulaFuncs) ISERR(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ISERR requires 1 argument")
return
}
token := argsList.Front().Value.(formulaArg)
result = "FALSE"
if token.Type == ArgString {
for _, errType := range []string{formulaErrorDIV, formulaErrorNAME, formulaErrorNUM, formulaErrorVALUE, formulaErrorREF, formulaErrorNULL, formulaErrorSPILL, formulaErrorCALC, formulaErrorGETTINGDATA} {
if errType == token.String {
result = "TRUE"
}
}
}
return
}
// ISERROR function tests if an initial supplied expression (or value) returns
// an Excel Error, and if so, returns the logical value TRUE; Otherwise the
// function returns FALSE. The syntax of the function is:
//
// ISERROR(value)
//
func (fn *formulaFuncs) ISERROR(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ISERROR requires 1 argument")
return
}
token := argsList.Front().Value.(formulaArg)
result = "FALSE"
if token.Type == ArgString {
for _, errType := range []string{formulaErrorDIV, formulaErrorNAME, formulaErrorNA, formulaErrorNUM, formulaErrorVALUE, formulaErrorREF, formulaErrorNULL, formulaErrorSPILL, formulaErrorCALC, formulaErrorGETTINGDATA} {
if errType == token.String {
result = "TRUE"
}
}
}
return
}
// ISEVEN function tests if a supplied number (or numeric expression)
// evaluates to an even number, and if so, returns TRUE; Otherwise, the
// function returns FALSE. The syntax of the function is:
//
// ISEVEN(value)
//
func (fn *formulaFuncs) ISEVEN(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ISEVEN requires 1 argument")
return
}
token := argsList.Front().Value.(formulaArg)
result = "FALSE"
var numeric int
if token.Type == ArgString {
if numeric, err = strconv.Atoi(token.String); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if numeric == numeric/2*2 {
result = "TRUE"
return
}
}
return
}
// ISNA function tests if an initial supplied expression (or value) returns
// the Excel #N/A Error, and if so, returns TRUE; Otherwise the function
// returns FALSE. The syntax of the function is:
//
// ISNA(value)
//
func (fn *formulaFuncs) ISNA(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ISNA requires 1 argument")
return
}
token := argsList.Front().Value.(formulaArg)
result = "FALSE"
if token.Type == ArgString && token.String == formulaErrorNA {
result = "TRUE"
}
return
}
// ISNONTEXT function function tests if a supplied value is text. If not, the
// function returns TRUE; If the supplied value is text, the function returns
// FALSE. The syntax of the function is:
//
// ISNONTEXT(value)
//
func (fn *formulaFuncs) ISNONTEXT(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ISNONTEXT requires 1 argument")
return
}
token := argsList.Front().Value.(formulaArg)
result = "TRUE"
if token.Type == ArgString && token.String != "" {
result = "FALSE"
}
return
}
// ISNUMBER function function tests if a supplied value is a number. If so,
// the function returns TRUE; Otherwise it returns FALSE. The syntax of the
// function is:
//
// ISNUMBER(value)
//
func (fn *formulaFuncs) ISNUMBER(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ISNUMBER requires 1 argument")
return
}
token := argsList.Front().Value.(formulaArg)
result = "FALSE"
if token.Type == ArgString && token.String != "" {
if _, err = strconv.Atoi(token.String); err == nil {
result = "TRUE"
}
err = nil
}
return
}
// ISODD function tests if a supplied number (or numeric expression) evaluates
// to an odd number, and if so, returns TRUE; Otherwise, the function returns
// FALSE. The syntax of the function is:
//
// ISODD(value)
//
func (fn *formulaFuncs) ISODD(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ISODD requires 1 argument")
return
}
token := argsList.Front().Value.(formulaArg)
result = "FALSE"
var numeric int
if token.Type == ArgString {
if numeric, err = strconv.Atoi(token.String); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if numeric != numeric/2*2 {
result = "TRUE"
return
}
}
return
}
// NA function returns the Excel #N/A error. This error message has the
// meaning 'value not available' and is produced when an Excel Formula is
// unable to find a value that it needs. The syntax of the function is:
//
// NA()
//
func (fn *formulaFuncs) NA(argsList *list.List) (result string, err error) {
if argsList.Len() != 0 {
err = errors.New("NA accepts no arguments")
return
}
result = formulaErrorNA
return
}