calc.go 231 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902
  1. // Copyright 2016 - 2021 The excelize Authors. All rights reserved. Use of
  2. // this source code is governed by a BSD-style license that can be found in
  3. // the LICENSE file.
  4. //
  5. // Package excelize providing a set of functions that allow you to write to
  6. // and read from XLSX / XLSM / XLTM files. Supports reading and writing
  7. // spreadsheet documents generated by Microsoft Excel™ 2007 and later. Supports
  8. // complex components by high compatibility, and provided streaming API for
  9. // generating or reading data from a worksheet with huge amounts of data. This
  10. // library needs Go version 1.15 or later.
  11. package excelize
  12. import (
  13. "bytes"
  14. "container/list"
  15. "errors"
  16. "fmt"
  17. "math"
  18. "math/cmplx"
  19. "math/rand"
  20. "net/url"
  21. "reflect"
  22. "regexp"
  23. "sort"
  24. "strconv"
  25. "strings"
  26. "time"
  27. "unicode"
  28. "unsafe"
  29. "github.com/xuri/efp"
  30. "golang.org/x/text/language"
  31. "golang.org/x/text/message"
  32. )
  33. // Excel formula errors
  34. const (
  35. formulaErrorDIV = "#DIV/0!"
  36. formulaErrorNAME = "#NAME?"
  37. formulaErrorNA = "#N/A"
  38. formulaErrorNUM = "#NUM!"
  39. formulaErrorVALUE = "#VALUE!"
  40. formulaErrorREF = "#REF!"
  41. formulaErrorNULL = "#NULL"
  42. formulaErrorSPILL = "#SPILL!"
  43. formulaErrorCALC = "#CALC!"
  44. formulaErrorGETTINGDATA = "#GETTING_DATA"
  45. )
  46. // Numeric precision correct numeric values as legacy Excel application
  47. // https://en.wikipedia.org/wiki/Numeric_precision_in_Microsoft_Excel In the
  48. // top figure the fraction 1/9000 in Excel is displayed. Although this number
  49. // has a decimal representation that is an infinite string of ones, Excel
  50. // displays only the leading 15 figures. In the second line, the number one
  51. // is added to the fraction, and again Excel displays only 15 figures.
  52. const numericPrecision = 1000000000000000
  53. const maxFinancialIterations = 128
  54. const financialPercision = 1.0e-08
  55. // cellRef defines the structure of a cell reference.
  56. type cellRef struct {
  57. Col int
  58. Row int
  59. Sheet string
  60. }
  61. // cellRef defines the structure of a cell range.
  62. type cellRange struct {
  63. From cellRef
  64. To cellRef
  65. }
  66. // formula criteria condition enumeration.
  67. const (
  68. _ byte = iota
  69. criteriaEq
  70. criteriaLe
  71. criteriaGe
  72. criteriaL
  73. criteriaG
  74. criteriaBeg
  75. criteriaEnd
  76. criteriaErr
  77. )
  78. // formulaCriteria defined formula criteria parser result.
  79. type formulaCriteria struct {
  80. Type byte
  81. Condition string
  82. }
  83. // ArgType is the type if formula argument type.
  84. type ArgType byte
  85. // Formula argument types enumeration.
  86. const (
  87. ArgUnknown ArgType = iota
  88. ArgNumber
  89. ArgString
  90. ArgList
  91. ArgMatrix
  92. ArgError
  93. ArgEmpty
  94. )
  95. // formulaArg is the argument of a formula or function.
  96. type formulaArg struct {
  97. SheetName string
  98. Number float64
  99. String string
  100. List []formulaArg
  101. Matrix [][]formulaArg
  102. Boolean bool
  103. Error string
  104. Type ArgType
  105. cellRefs, cellRanges *list.List
  106. }
  107. // Value returns a string data type of the formula argument.
  108. func (fa formulaArg) Value() (value string) {
  109. switch fa.Type {
  110. case ArgNumber:
  111. if fa.Boolean {
  112. if fa.Number == 0 {
  113. return "FALSE"
  114. }
  115. return "TRUE"
  116. }
  117. return fmt.Sprintf("%g", fa.Number)
  118. case ArgString:
  119. return fa.String
  120. case ArgError:
  121. return fa.Error
  122. }
  123. return
  124. }
  125. // ToNumber returns a formula argument with number data type.
  126. func (fa formulaArg) ToNumber() formulaArg {
  127. var n float64
  128. var err error
  129. switch fa.Type {
  130. case ArgString:
  131. n, err = strconv.ParseFloat(fa.String, 64)
  132. if err != nil {
  133. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  134. }
  135. case ArgNumber:
  136. n = fa.Number
  137. }
  138. return newNumberFormulaArg(n)
  139. }
  140. // ToBool returns a formula argument with boolean data type.
  141. func (fa formulaArg) ToBool() formulaArg {
  142. var b bool
  143. var err error
  144. switch fa.Type {
  145. case ArgString:
  146. b, err = strconv.ParseBool(fa.String)
  147. if err != nil {
  148. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  149. }
  150. case ArgNumber:
  151. if fa.Boolean && fa.Number == 1 {
  152. b = true
  153. }
  154. }
  155. return newBoolFormulaArg(b)
  156. }
  157. // ToList returns a formula argument with array data type.
  158. func (fa formulaArg) ToList() []formulaArg {
  159. switch fa.Type {
  160. case ArgMatrix:
  161. list := []formulaArg{}
  162. for _, row := range fa.Matrix {
  163. list = append(list, row...)
  164. }
  165. return list
  166. case ArgList:
  167. return fa.List
  168. case ArgNumber, ArgString, ArgError, ArgUnknown:
  169. return []formulaArg{fa}
  170. }
  171. return nil
  172. }
  173. // formulaFuncs is the type of the formula functions.
  174. type formulaFuncs struct {
  175. f *File
  176. sheet, cell string
  177. }
  178. // tokenPriority defined basic arithmetic operator priority.
  179. var tokenPriority = map[string]int{
  180. "^": 5,
  181. "*": 4,
  182. "/": 4,
  183. "+": 3,
  184. "-": 3,
  185. "=": 2,
  186. "<>": 2,
  187. "<": 2,
  188. "<=": 2,
  189. ">": 2,
  190. ">=": 2,
  191. "&": 1,
  192. }
  193. // CalcCellValue provides a function to get calculated cell value. This
  194. // feature is currently in working processing. Array formula, table formula
  195. // and some other formulas are not supported currently.
  196. //
  197. // Supported formula functions:
  198. //
  199. // ABS
  200. // ACOS
  201. // ACOSH
  202. // ACOT
  203. // ACOTH
  204. // AND
  205. // ARABIC
  206. // ASIN
  207. // ASINH
  208. // ATAN
  209. // ATAN2
  210. // ATANH
  211. // AVERAGE
  212. // AVERAGEA
  213. // BASE
  214. // BESSELI
  215. // BESSELJ
  216. // BIN2DEC
  217. // BIN2HEX
  218. // BIN2OCT
  219. // BITAND
  220. // BITLSHIFT
  221. // BITOR
  222. // BITRSHIFT
  223. // BITXOR
  224. // CEILING
  225. // CEILING.MATH
  226. // CEILING.PRECISE
  227. // CHAR
  228. // CHOOSE
  229. // CLEAN
  230. // CODE
  231. // COLUMN
  232. // COLUMNS
  233. // COMBIN
  234. // COMBINA
  235. // COMPLEX
  236. // CONCAT
  237. // CONCATENATE
  238. // COS
  239. // COSH
  240. // COT
  241. // COTH
  242. // COUNT
  243. // COUNTA
  244. // COUNTBLANK
  245. // CSC
  246. // CSCH
  247. // CUMIPMT
  248. // CUMPRINC
  249. // DATE
  250. // DATEDIF
  251. // DB
  252. // DDB
  253. // DEC2BIN
  254. // DEC2HEX
  255. // DEC2OCT
  256. // DECIMAL
  257. // DEGREES
  258. // DOLLARDE
  259. // DOLLARFR
  260. // EFFECT
  261. // ENCODEURL
  262. // EVEN
  263. // EXACT
  264. // EXP
  265. // FACT
  266. // FACTDOUBLE
  267. // FALSE
  268. // FIND
  269. // FINDB
  270. // FISHER
  271. // FISHERINV
  272. // FIXED
  273. // FLOOR
  274. // FLOOR.MATH
  275. // FLOOR.PRECISE
  276. // FV
  277. // FVSCHEDULE
  278. // GAMMA
  279. // GAMMALN
  280. // GCD
  281. // HARMEAN
  282. // HEX2BIN
  283. // HEX2DEC
  284. // HEX2OCT
  285. // HLOOKUP
  286. // IF
  287. // IFERROR
  288. // IMABS
  289. // IMAGINARY
  290. // IMARGUMENT
  291. // IMCONJUGATE
  292. // IMCOS
  293. // IMCOSH
  294. // IMCOT
  295. // IMCSC
  296. // IMCSCH
  297. // IMDIV
  298. // IMEXP
  299. // IMLN
  300. // IMLOG10
  301. // IMLOG2
  302. // IMPOWER
  303. // IMPRODUCT
  304. // IMREAL
  305. // IMSEC
  306. // IMSECH
  307. // IMSIN
  308. // IMSINH
  309. // IMSQRT
  310. // IMSUB
  311. // IMSUM
  312. // IMTAN
  313. // INT
  314. // IPMT
  315. // IRR
  316. // ISBLANK
  317. // ISERR
  318. // ISERROR
  319. // ISEVEN
  320. // ISNA
  321. // ISNONTEXT
  322. // ISNUMBER
  323. // ISODD
  324. // ISTEXT
  325. // ISO.CEILING
  326. // ISPMT
  327. // KURT
  328. // LARGE
  329. // LCM
  330. // LEFT
  331. // LEFTB
  332. // LEN
  333. // LENB
  334. // LN
  335. // LOG
  336. // LOG10
  337. // LOOKUP
  338. // LOWER
  339. // MAX
  340. // MDETERM
  341. // MEDIAN
  342. // MID
  343. // MIDB
  344. // MIN
  345. // MINA
  346. // MIRR
  347. // MOD
  348. // MROUND
  349. // MULTINOMIAL
  350. // MUNIT
  351. // N
  352. // NA
  353. // NOMINAL
  354. // NORM.DIST
  355. // NORMDIST
  356. // NORM.INV
  357. // NORMINV
  358. // NORM.S.DIST
  359. // NORMSDIST
  360. // NORM.S.INV
  361. // NORMSINV
  362. // NOT
  363. // NOW
  364. // NPER
  365. // NPV
  366. // OCT2BIN
  367. // OCT2DEC
  368. // OCT2HEX
  369. // ODD
  370. // OR
  371. // PDURATION
  372. // PERCENTILE.INC
  373. // PERCENTILE
  374. // PERMUT
  375. // PERMUTATIONA
  376. // PI
  377. // PMT
  378. // POISSON.DIST
  379. // POISSON
  380. // POWER
  381. // PPMT
  382. // PRODUCT
  383. // PROPER
  384. // QUARTILE
  385. // QUARTILE.INC
  386. // QUOTIENT
  387. // RADIANS
  388. // RAND
  389. // RANDBETWEEN
  390. // REPLACE
  391. // REPLACEB
  392. // REPT
  393. // RIGHT
  394. // RIGHTB
  395. // ROMAN
  396. // ROUND
  397. // ROUNDDOWN
  398. // ROUNDUP
  399. // ROW
  400. // ROWS
  401. // SEC
  402. // SECH
  403. // SHEET
  404. // SIGN
  405. // SIN
  406. // SINH
  407. // SKEW
  408. // SMALL
  409. // SQRT
  410. // SQRTPI
  411. // STDEV
  412. // STDEV.S
  413. // STDEVA
  414. // SUBSTITUTE
  415. // SUM
  416. // SUMIF
  417. // SUMSQ
  418. // T
  419. // TAN
  420. // TANH
  421. // TODAY
  422. // TRIM
  423. // TRUE
  424. // TRUNC
  425. // UNICHAR
  426. // UNICODE
  427. // UPPER
  428. // VAR.P
  429. // VARP
  430. // VLOOKUP
  431. //
  432. func (f *File) CalcCellValue(sheet, cell string) (result string, err error) {
  433. var (
  434. formula string
  435. token efp.Token
  436. )
  437. if formula, err = f.GetCellFormula(sheet, cell); err != nil {
  438. return
  439. }
  440. ps := efp.ExcelParser()
  441. tokens := ps.Parse(formula)
  442. if tokens == nil {
  443. return
  444. }
  445. if token, err = f.evalInfixExp(sheet, cell, tokens); err != nil {
  446. return
  447. }
  448. result = token.TValue
  449. isNum, precision := isNumeric(result)
  450. if isNum && precision > 15 {
  451. num, _ := roundPrecision(result)
  452. result = strings.ToUpper(num)
  453. }
  454. return
  455. }
  456. // getPriority calculate arithmetic operator priority.
  457. func getPriority(token efp.Token) (pri int) {
  458. pri = tokenPriority[token.TValue]
  459. if token.TValue == "-" && token.TType == efp.TokenTypeOperatorPrefix {
  460. pri = 6
  461. }
  462. if isBeginParenthesesToken(token) { // (
  463. pri = 0
  464. }
  465. return
  466. }
  467. // newNumberFormulaArg constructs a number formula argument.
  468. func newNumberFormulaArg(n float64) formulaArg {
  469. if math.IsNaN(n) {
  470. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  471. }
  472. return formulaArg{Type: ArgNumber, Number: n}
  473. }
  474. // newStringFormulaArg constructs a string formula argument.
  475. func newStringFormulaArg(s string) formulaArg {
  476. return formulaArg{Type: ArgString, String: s}
  477. }
  478. // newMatrixFormulaArg constructs a matrix formula argument.
  479. func newMatrixFormulaArg(m [][]formulaArg) formulaArg {
  480. return formulaArg{Type: ArgMatrix, Matrix: m}
  481. }
  482. // newListFormulaArg create a list formula argument.
  483. func newListFormulaArg(l []formulaArg) formulaArg {
  484. return formulaArg{Type: ArgList, List: l}
  485. }
  486. // newBoolFormulaArg constructs a boolean formula argument.
  487. func newBoolFormulaArg(b bool) formulaArg {
  488. var n float64
  489. if b {
  490. n = 1
  491. }
  492. return formulaArg{Type: ArgNumber, Number: n, Boolean: true}
  493. }
  494. // newErrorFormulaArg create an error formula argument of a given type with a
  495. // specified error message.
  496. func newErrorFormulaArg(formulaError, msg string) formulaArg {
  497. return formulaArg{Type: ArgError, String: formulaError, Error: msg}
  498. }
  499. // newEmptyFormulaArg create an empty formula argument.
  500. func newEmptyFormulaArg() formulaArg {
  501. return formulaArg{Type: ArgEmpty}
  502. }
  503. // evalInfixExp evaluate syntax analysis by given infix expression after
  504. // lexical analysis. Evaluate an infix expression containing formulas by
  505. // stacks:
  506. //
  507. // opd - Operand
  508. // opt - Operator
  509. // opf - Operation formula
  510. // opfd - Operand of the operation formula
  511. // opft - Operator of the operation formula
  512. // args - Arguments list of the operation formula
  513. //
  514. // TODO: handle subtypes: Nothing, Text, Logical, Error, Concatenation, Intersection, Union
  515. //
  516. func (f *File) evalInfixExp(sheet, cell string, tokens []efp.Token) (efp.Token, error) {
  517. var err error
  518. opdStack, optStack, opfStack, opfdStack, opftStack, argsStack := NewStack(), NewStack(), NewStack(), NewStack(), NewStack(), NewStack()
  519. for i := 0; i < len(tokens); i++ {
  520. token := tokens[i]
  521. // out of function stack
  522. if opfStack.Len() == 0 {
  523. if err = f.parseToken(sheet, token, opdStack, optStack); err != nil {
  524. return efp.Token{}, err
  525. }
  526. }
  527. // function start
  528. if isFunctionStartToken(token) {
  529. opfStack.Push(token)
  530. argsStack.Push(list.New().Init())
  531. continue
  532. }
  533. // in function stack, walk 2 token at once
  534. if opfStack.Len() > 0 {
  535. var nextToken efp.Token
  536. if i+1 < len(tokens) {
  537. nextToken = tokens[i+1]
  538. }
  539. // current token is args or range, skip next token, order required: parse reference first
  540. if token.TSubType == efp.TokenSubTypeRange {
  541. if !opftStack.Empty() {
  542. // parse reference: must reference at here
  543. result, err := f.parseReference(sheet, token.TValue)
  544. if err != nil {
  545. return efp.Token{TValue: formulaErrorNAME}, err
  546. }
  547. if result.Type != ArgString {
  548. return efp.Token{}, errors.New(formulaErrorVALUE)
  549. }
  550. opfdStack.Push(efp.Token{
  551. TType: efp.TokenTypeOperand,
  552. TSubType: efp.TokenSubTypeNumber,
  553. TValue: result.String,
  554. })
  555. continue
  556. }
  557. if nextToken.TType == efp.TokenTypeArgument || nextToken.TType == efp.TokenTypeFunction {
  558. // parse reference: reference or range at here
  559. result, err := f.parseReference(sheet, token.TValue)
  560. if err != nil {
  561. return efp.Token{TValue: formulaErrorNAME}, err
  562. }
  563. if result.Type == ArgUnknown {
  564. return efp.Token{}, errors.New(formulaErrorVALUE)
  565. }
  566. argsStack.Peek().(*list.List).PushBack(result)
  567. continue
  568. }
  569. }
  570. // check current token is opft
  571. if err = f.parseToken(sheet, token, opfdStack, opftStack); err != nil {
  572. return efp.Token{}, err
  573. }
  574. // current token is arg
  575. if token.TType == efp.TokenTypeArgument {
  576. for !opftStack.Empty() {
  577. // calculate trigger
  578. topOpt := opftStack.Peek().(efp.Token)
  579. if err := calculate(opfdStack, topOpt); err != nil {
  580. argsStack.Peek().(*list.List).PushFront(newErrorFormulaArg(formulaErrorVALUE, err.Error()))
  581. }
  582. opftStack.Pop()
  583. }
  584. if !opfdStack.Empty() {
  585. argsStack.Peek().(*list.List).PushBack(newStringFormulaArg(opfdStack.Pop().(efp.Token).TValue))
  586. }
  587. continue
  588. }
  589. // current token is logical
  590. if token.TType == efp.OperatorsInfix && token.TSubType == efp.TokenSubTypeLogical {
  591. }
  592. if token.TType == efp.TokenTypeOperand && token.TSubType == efp.TokenSubTypeLogical {
  593. argsStack.Peek().(*list.List).PushBack(newStringFormulaArg(token.TValue))
  594. }
  595. // current token is text
  596. if token.TType == efp.TokenTypeOperand && token.TSubType == efp.TokenSubTypeText {
  597. argsStack.Peek().(*list.List).PushBack(newStringFormulaArg(token.TValue))
  598. }
  599. if err = f.evalInfixExpFunc(sheet, cell, token, nextToken, opfStack, opdStack, opftStack, opfdStack, argsStack); err != nil {
  600. return efp.Token{}, err
  601. }
  602. }
  603. }
  604. for optStack.Len() != 0 {
  605. topOpt := optStack.Peek().(efp.Token)
  606. if err = calculate(opdStack, topOpt); err != nil {
  607. return efp.Token{}, err
  608. }
  609. optStack.Pop()
  610. }
  611. if opdStack.Len() == 0 {
  612. return efp.Token{}, errors.New("formula not valid")
  613. }
  614. return opdStack.Peek().(efp.Token), err
  615. }
  616. // evalInfixExpFunc evaluate formula function in the infix expression.
  617. func (f *File) evalInfixExpFunc(sheet, cell string, token, nextToken efp.Token, opfStack, opdStack, opftStack, opfdStack, argsStack *Stack) error {
  618. if !isFunctionStopToken(token) {
  619. return nil
  620. }
  621. // current token is function stop
  622. for !opftStack.Empty() {
  623. // calculate trigger
  624. topOpt := opftStack.Peek().(efp.Token)
  625. if err := calculate(opfdStack, topOpt); err != nil {
  626. return err
  627. }
  628. opftStack.Pop()
  629. }
  630. // push opfd to args
  631. if opfdStack.Len() > 0 {
  632. argsStack.Peek().(*list.List).PushBack(newStringFormulaArg(opfdStack.Pop().(efp.Token).TValue))
  633. }
  634. // call formula function to evaluate
  635. arg := callFuncByName(&formulaFuncs{f: f, sheet: sheet, cell: cell}, strings.NewReplacer(
  636. "_xlfn.", "", ".", "dot").Replace(opfStack.Peek().(efp.Token).TValue),
  637. []reflect.Value{reflect.ValueOf(argsStack.Peek().(*list.List))})
  638. if arg.Type == ArgError && opfStack.Len() == 1 {
  639. return errors.New(arg.Value())
  640. }
  641. argsStack.Pop()
  642. opfStack.Pop()
  643. if opfStack.Len() > 0 { // still in function stack
  644. if nextToken.TType == efp.TokenTypeOperatorInfix {
  645. // mathematics calculate in formula function
  646. opfdStack.Push(efp.Token{TValue: arg.Value(), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  647. } else {
  648. argsStack.Peek().(*list.List).PushBack(arg)
  649. }
  650. } else {
  651. opdStack.Push(efp.Token{TValue: arg.Value(), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  652. }
  653. return nil
  654. }
  655. // calcPow evaluate exponentiation arithmetic operations.
  656. func calcPow(rOpd, lOpd string, opdStack *Stack) error {
  657. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  658. if err != nil {
  659. return err
  660. }
  661. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  662. if err != nil {
  663. return err
  664. }
  665. result := math.Pow(lOpdVal, rOpdVal)
  666. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  667. return nil
  668. }
  669. // calcEq evaluate equal arithmetic operations.
  670. func calcEq(rOpd, lOpd string, opdStack *Stack) error {
  671. opdStack.Push(efp.Token{TValue: strings.ToUpper(strconv.FormatBool(rOpd == lOpd)), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  672. return nil
  673. }
  674. // calcNEq evaluate not equal arithmetic operations.
  675. func calcNEq(rOpd, lOpd string, opdStack *Stack) error {
  676. opdStack.Push(efp.Token{TValue: strings.ToUpper(strconv.FormatBool(rOpd != lOpd)), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  677. return nil
  678. }
  679. // calcL evaluate less than arithmetic operations.
  680. func calcL(rOpd, lOpd string, opdStack *Stack) error {
  681. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  682. if err != nil {
  683. return err
  684. }
  685. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  686. if err != nil {
  687. return err
  688. }
  689. opdStack.Push(efp.Token{TValue: strings.ToUpper(strconv.FormatBool(rOpdVal > lOpdVal)), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  690. return nil
  691. }
  692. // calcLe evaluate less than or equal arithmetic operations.
  693. func calcLe(rOpd, lOpd string, opdStack *Stack) error {
  694. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  695. if err != nil {
  696. return err
  697. }
  698. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  699. if err != nil {
  700. return err
  701. }
  702. opdStack.Push(efp.Token{TValue: strings.ToUpper(strconv.FormatBool(rOpdVal >= lOpdVal)), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  703. return nil
  704. }
  705. // calcG evaluate greater than or equal arithmetic operations.
  706. func calcG(rOpd, lOpd string, opdStack *Stack) error {
  707. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  708. if err != nil {
  709. return err
  710. }
  711. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  712. if err != nil {
  713. return err
  714. }
  715. opdStack.Push(efp.Token{TValue: strings.ToUpper(strconv.FormatBool(rOpdVal < lOpdVal)), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  716. return nil
  717. }
  718. // calcGe evaluate greater than or equal arithmetic operations.
  719. func calcGe(rOpd, lOpd string, opdStack *Stack) error {
  720. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  721. if err != nil {
  722. return err
  723. }
  724. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  725. if err != nil {
  726. return err
  727. }
  728. opdStack.Push(efp.Token{TValue: strings.ToUpper(strconv.FormatBool(rOpdVal <= lOpdVal)), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  729. return nil
  730. }
  731. // calcSplice evaluate splice '&' operations.
  732. func calcSplice(rOpd, lOpd string, opdStack *Stack) error {
  733. opdStack.Push(efp.Token{TValue: lOpd + rOpd, TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  734. return nil
  735. }
  736. // calcAdd evaluate addition arithmetic operations.
  737. func calcAdd(rOpd, lOpd string, opdStack *Stack) error {
  738. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  739. if err != nil {
  740. return err
  741. }
  742. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  743. if err != nil {
  744. return err
  745. }
  746. result := lOpdVal + rOpdVal
  747. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  748. return nil
  749. }
  750. // calcSubtract evaluate subtraction arithmetic operations.
  751. func calcSubtract(rOpd, lOpd string, opdStack *Stack) error {
  752. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  753. if err != nil {
  754. return err
  755. }
  756. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  757. if err != nil {
  758. return err
  759. }
  760. result := lOpdVal - rOpdVal
  761. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  762. return nil
  763. }
  764. // calcMultiply evaluate multiplication arithmetic operations.
  765. func calcMultiply(rOpd, lOpd string, opdStack *Stack) error {
  766. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  767. if err != nil {
  768. return err
  769. }
  770. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  771. if err != nil {
  772. return err
  773. }
  774. result := lOpdVal * rOpdVal
  775. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  776. return nil
  777. }
  778. // calcDiv evaluate division arithmetic operations.
  779. func calcDiv(rOpd, lOpd string, opdStack *Stack) error {
  780. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  781. if err != nil {
  782. return err
  783. }
  784. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  785. if err != nil {
  786. return err
  787. }
  788. result := lOpdVal / rOpdVal
  789. if rOpdVal == 0 {
  790. return errors.New(formulaErrorDIV)
  791. }
  792. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  793. return nil
  794. }
  795. // calculate evaluate basic arithmetic operations.
  796. func calculate(opdStack *Stack, opt efp.Token) error {
  797. if opt.TValue == "-" && opt.TType == efp.TokenTypeOperatorPrefix {
  798. if opdStack.Len() < 1 {
  799. return errors.New("formula not valid")
  800. }
  801. opd := opdStack.Pop().(efp.Token)
  802. opdVal, err := strconv.ParseFloat(opd.TValue, 64)
  803. if err != nil {
  804. return err
  805. }
  806. result := 0 - opdVal
  807. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  808. }
  809. tokenCalcFunc := map[string]func(rOpd, lOpd string, opdStack *Stack) error{
  810. "^": calcPow,
  811. "*": calcMultiply,
  812. "/": calcDiv,
  813. "+": calcAdd,
  814. "=": calcEq,
  815. "<>": calcNEq,
  816. "<": calcL,
  817. "<=": calcLe,
  818. ">": calcG,
  819. ">=": calcGe,
  820. "&": calcSplice,
  821. }
  822. if opt.TValue == "-" && opt.TType == efp.TokenTypeOperatorInfix {
  823. if opdStack.Len() < 2 {
  824. return errors.New("formula not valid")
  825. }
  826. rOpd := opdStack.Pop().(efp.Token)
  827. lOpd := opdStack.Pop().(efp.Token)
  828. if err := calcSubtract(rOpd.TValue, lOpd.TValue, opdStack); err != nil {
  829. return err
  830. }
  831. }
  832. fn, ok := tokenCalcFunc[opt.TValue]
  833. if ok {
  834. if opdStack.Len() < 2 {
  835. return errors.New("formula not valid")
  836. }
  837. rOpd := opdStack.Pop().(efp.Token)
  838. lOpd := opdStack.Pop().(efp.Token)
  839. if err := fn(rOpd.TValue, lOpd.TValue, opdStack); err != nil {
  840. return err
  841. }
  842. }
  843. return nil
  844. }
  845. // parseOperatorPrefixToken parse operator prefix token.
  846. func (f *File) parseOperatorPrefixToken(optStack, opdStack *Stack, token efp.Token) (err error) {
  847. if optStack.Len() == 0 {
  848. optStack.Push(token)
  849. } else {
  850. tokenPriority := getPriority(token)
  851. topOpt := optStack.Peek().(efp.Token)
  852. topOptPriority := getPriority(topOpt)
  853. if tokenPriority > topOptPriority {
  854. optStack.Push(token)
  855. } else {
  856. for tokenPriority <= topOptPriority {
  857. optStack.Pop()
  858. if err = calculate(opdStack, topOpt); err != nil {
  859. return
  860. }
  861. if optStack.Len() > 0 {
  862. topOpt = optStack.Peek().(efp.Token)
  863. topOptPriority = getPriority(topOpt)
  864. continue
  865. }
  866. break
  867. }
  868. optStack.Push(token)
  869. }
  870. }
  871. return
  872. }
  873. // isFunctionStartToken determine if the token is function stop.
  874. func isFunctionStartToken(token efp.Token) bool {
  875. return token.TType == efp.TokenTypeFunction && token.TSubType == efp.TokenSubTypeStart
  876. }
  877. // isFunctionStopToken determine if the token is function stop.
  878. func isFunctionStopToken(token efp.Token) bool {
  879. return token.TType == efp.TokenTypeFunction && token.TSubType == efp.TokenSubTypeStop
  880. }
  881. // isBeginParenthesesToken determine if the token is begin parentheses: (.
  882. func isBeginParenthesesToken(token efp.Token) bool {
  883. return token.TType == efp.TokenTypeSubexpression && token.TSubType == efp.TokenSubTypeStart
  884. }
  885. // isEndParenthesesToken determine if the token is end parentheses: ).
  886. func isEndParenthesesToken(token efp.Token) bool {
  887. return token.TType == efp.TokenTypeSubexpression && token.TSubType == efp.TokenSubTypeStop
  888. }
  889. // isOperatorPrefixToken determine if the token is parse operator prefix
  890. // token.
  891. func isOperatorPrefixToken(token efp.Token) bool {
  892. _, ok := tokenPriority[token.TValue]
  893. if (token.TValue == "-" && token.TType == efp.TokenTypeOperatorPrefix) || (ok && token.TType == efp.TokenTypeOperatorInfix) {
  894. return true
  895. }
  896. return false
  897. }
  898. // getDefinedNameRefTo convert defined name to reference range.
  899. func (f *File) getDefinedNameRefTo(definedNameName string, currentSheet string) (refTo string) {
  900. for _, definedName := range f.GetDefinedName() {
  901. if definedName.Name == definedNameName {
  902. refTo = definedName.RefersTo
  903. // worksheet scope takes precedence over scope workbook when both definedNames exist
  904. if definedName.Scope == currentSheet {
  905. break
  906. }
  907. }
  908. }
  909. return refTo
  910. }
  911. // parseToken parse basic arithmetic operator priority and evaluate based on
  912. // operators and operands.
  913. func (f *File) parseToken(sheet string, token efp.Token, opdStack, optStack *Stack) error {
  914. // parse reference: must reference at here
  915. if token.TSubType == efp.TokenSubTypeRange {
  916. refTo := f.getDefinedNameRefTo(token.TValue, sheet)
  917. if refTo != "" {
  918. token.TValue = refTo
  919. }
  920. result, err := f.parseReference(sheet, token.TValue)
  921. if err != nil {
  922. return errors.New(formulaErrorNAME)
  923. }
  924. if result.Type != ArgString {
  925. return errors.New(formulaErrorVALUE)
  926. }
  927. token.TValue = result.String
  928. token.TType = efp.TokenTypeOperand
  929. token.TSubType = efp.TokenSubTypeNumber
  930. }
  931. if isOperatorPrefixToken(token) {
  932. if err := f.parseOperatorPrefixToken(optStack, opdStack, token); err != nil {
  933. return err
  934. }
  935. }
  936. if isBeginParenthesesToken(token) { // (
  937. optStack.Push(token)
  938. }
  939. if isEndParenthesesToken(token) { // )
  940. for !isBeginParenthesesToken(optStack.Peek().(efp.Token)) { // != (
  941. topOpt := optStack.Peek().(efp.Token)
  942. if err := calculate(opdStack, topOpt); err != nil {
  943. return err
  944. }
  945. optStack.Pop()
  946. }
  947. optStack.Pop()
  948. }
  949. // opd
  950. if token.TType == efp.TokenTypeOperand && token.TSubType == efp.TokenSubTypeNumber {
  951. opdStack.Push(token)
  952. }
  953. return nil
  954. }
  955. // parseReference parse reference and extract values by given reference
  956. // characters and default sheet name.
  957. func (f *File) parseReference(sheet, reference string) (arg formulaArg, err error) {
  958. reference = strings.Replace(reference, "$", "", -1)
  959. refs, cellRanges, cellRefs := list.New(), list.New(), list.New()
  960. for _, ref := range strings.Split(reference, ":") {
  961. tokens := strings.Split(ref, "!")
  962. cr := cellRef{}
  963. if len(tokens) == 2 { // have a worksheet name
  964. cr.Sheet = tokens[0]
  965. // cast to cell coordinates
  966. if cr.Col, cr.Row, err = CellNameToCoordinates(tokens[1]); err != nil {
  967. // cast to column
  968. if cr.Col, err = ColumnNameToNumber(tokens[1]); err != nil {
  969. // cast to row
  970. if cr.Row, err = strconv.Atoi(tokens[1]); err != nil {
  971. err = newInvalidColumnNameError(tokens[1])
  972. return
  973. }
  974. cr.Col = TotalColumns
  975. }
  976. }
  977. if refs.Len() > 0 {
  978. e := refs.Back()
  979. cellRefs.PushBack(e.Value.(cellRef))
  980. refs.Remove(e)
  981. }
  982. refs.PushBack(cr)
  983. continue
  984. }
  985. // cast to cell coordinates
  986. if cr.Col, cr.Row, err = CellNameToCoordinates(tokens[0]); err != nil {
  987. // cast to column
  988. if cr.Col, err = ColumnNameToNumber(tokens[0]); err != nil {
  989. // cast to row
  990. if cr.Row, err = strconv.Atoi(tokens[0]); err != nil {
  991. err = newInvalidColumnNameError(tokens[0])
  992. return
  993. }
  994. cr.Col = TotalColumns
  995. }
  996. cellRanges.PushBack(cellRange{
  997. From: cellRef{Sheet: sheet, Col: cr.Col, Row: 1},
  998. To: cellRef{Sheet: sheet, Col: cr.Col, Row: TotalRows},
  999. })
  1000. cellRefs.Init()
  1001. arg, err = f.rangeResolver(cellRefs, cellRanges)
  1002. return
  1003. }
  1004. e := refs.Back()
  1005. if e == nil {
  1006. cr.Sheet = sheet
  1007. refs.PushBack(cr)
  1008. continue
  1009. }
  1010. cellRanges.PushBack(cellRange{
  1011. From: e.Value.(cellRef),
  1012. To: cr,
  1013. })
  1014. refs.Remove(e)
  1015. }
  1016. if refs.Len() > 0 {
  1017. e := refs.Back()
  1018. cellRefs.PushBack(e.Value.(cellRef))
  1019. refs.Remove(e)
  1020. }
  1021. arg, err = f.rangeResolver(cellRefs, cellRanges)
  1022. return
  1023. }
  1024. // prepareValueRange prepare value range.
  1025. func prepareValueRange(cr cellRange, valueRange []int) {
  1026. if cr.From.Row < valueRange[0] || valueRange[0] == 0 {
  1027. valueRange[0] = cr.From.Row
  1028. }
  1029. if cr.From.Col < valueRange[2] || valueRange[2] == 0 {
  1030. valueRange[2] = cr.From.Col
  1031. }
  1032. if cr.To.Row > valueRange[1] || valueRange[1] == 0 {
  1033. valueRange[1] = cr.To.Row
  1034. }
  1035. if cr.To.Col > valueRange[3] || valueRange[3] == 0 {
  1036. valueRange[3] = cr.To.Col
  1037. }
  1038. }
  1039. // prepareValueRef prepare value reference.
  1040. func prepareValueRef(cr cellRef, valueRange []int) {
  1041. if cr.Row < valueRange[0] || valueRange[0] == 0 {
  1042. valueRange[0] = cr.Row
  1043. }
  1044. if cr.Col < valueRange[2] || valueRange[2] == 0 {
  1045. valueRange[2] = cr.Col
  1046. }
  1047. if cr.Row > valueRange[1] || valueRange[1] == 0 {
  1048. valueRange[1] = cr.Row
  1049. }
  1050. if cr.Col > valueRange[3] || valueRange[3] == 0 {
  1051. valueRange[3] = cr.Col
  1052. }
  1053. }
  1054. // rangeResolver extract value as string from given reference and range list.
  1055. // This function will not ignore the empty cell. For example, A1:A2:A2:B3 will
  1056. // be reference A1:B3.
  1057. func (f *File) rangeResolver(cellRefs, cellRanges *list.List) (arg formulaArg, err error) {
  1058. arg.cellRefs, arg.cellRanges = cellRefs, cellRanges
  1059. // value range order: from row, to row, from column, to column
  1060. valueRange := []int{0, 0, 0, 0}
  1061. var sheet string
  1062. // prepare value range
  1063. for temp := cellRanges.Front(); temp != nil; temp = temp.Next() {
  1064. cr := temp.Value.(cellRange)
  1065. if cr.From.Sheet != cr.To.Sheet {
  1066. err = errors.New(formulaErrorVALUE)
  1067. }
  1068. rng := []int{cr.From.Col, cr.From.Row, cr.To.Col, cr.To.Row}
  1069. _ = sortCoordinates(rng)
  1070. cr.From.Col, cr.From.Row, cr.To.Col, cr.To.Row = rng[0], rng[1], rng[2], rng[3]
  1071. prepareValueRange(cr, valueRange)
  1072. if cr.From.Sheet != "" {
  1073. sheet = cr.From.Sheet
  1074. }
  1075. }
  1076. for temp := cellRefs.Front(); temp != nil; temp = temp.Next() {
  1077. cr := temp.Value.(cellRef)
  1078. if cr.Sheet != "" {
  1079. sheet = cr.Sheet
  1080. }
  1081. prepareValueRef(cr, valueRange)
  1082. }
  1083. // extract value from ranges
  1084. if cellRanges.Len() > 0 {
  1085. arg.Type = ArgMatrix
  1086. for row := valueRange[0]; row <= valueRange[1]; row++ {
  1087. var matrixRow = []formulaArg{}
  1088. for col := valueRange[2]; col <= valueRange[3]; col++ {
  1089. var cell, value string
  1090. if cell, err = CoordinatesToCellName(col, row); err != nil {
  1091. return
  1092. }
  1093. if value, err = f.GetCellValue(sheet, cell); err != nil {
  1094. return
  1095. }
  1096. matrixRow = append(matrixRow, formulaArg{
  1097. String: value,
  1098. Type: ArgString,
  1099. })
  1100. }
  1101. arg.Matrix = append(arg.Matrix, matrixRow)
  1102. }
  1103. return
  1104. }
  1105. // extract value from references
  1106. for temp := cellRefs.Front(); temp != nil; temp = temp.Next() {
  1107. cr := temp.Value.(cellRef)
  1108. var cell string
  1109. if cell, err = CoordinatesToCellName(cr.Col, cr.Row); err != nil {
  1110. return
  1111. }
  1112. if arg.String, err = f.GetCellValue(cr.Sheet, cell); err != nil {
  1113. return
  1114. }
  1115. arg.Type = ArgString
  1116. }
  1117. return
  1118. }
  1119. // callFuncByName calls the no error or only error return function with
  1120. // reflect by given receiver, name and parameters.
  1121. func callFuncByName(receiver interface{}, name string, params []reflect.Value) (arg formulaArg) {
  1122. function := reflect.ValueOf(receiver).MethodByName(name)
  1123. if function.IsValid() {
  1124. rt := function.Call(params)
  1125. if len(rt) == 0 {
  1126. return
  1127. }
  1128. arg = rt[0].Interface().(formulaArg)
  1129. return
  1130. }
  1131. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("not support %s function", name))
  1132. }
  1133. // formulaCriteriaParser parse formula criteria.
  1134. func formulaCriteriaParser(exp string) (fc *formulaCriteria) {
  1135. fc = &formulaCriteria{}
  1136. if exp == "" {
  1137. return
  1138. }
  1139. if match := regexp.MustCompile(`^([0-9]+)$`).FindStringSubmatch(exp); len(match) > 1 {
  1140. fc.Type, fc.Condition = criteriaEq, match[1]
  1141. return
  1142. }
  1143. if match := regexp.MustCompile(`^=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
  1144. fc.Type, fc.Condition = criteriaEq, match[1]
  1145. return
  1146. }
  1147. if match := regexp.MustCompile(`^<=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
  1148. fc.Type, fc.Condition = criteriaLe, match[1]
  1149. return
  1150. }
  1151. if match := regexp.MustCompile(`^>=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
  1152. fc.Type, fc.Condition = criteriaGe, match[1]
  1153. return
  1154. }
  1155. if match := regexp.MustCompile(`^<(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
  1156. fc.Type, fc.Condition = criteriaL, match[1]
  1157. return
  1158. }
  1159. if match := regexp.MustCompile(`^>(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
  1160. fc.Type, fc.Condition = criteriaG, match[1]
  1161. return
  1162. }
  1163. if strings.Contains(exp, "*") {
  1164. if strings.HasPrefix(exp, "*") {
  1165. fc.Type, fc.Condition = criteriaEnd, strings.TrimPrefix(exp, "*")
  1166. }
  1167. if strings.HasSuffix(exp, "*") {
  1168. fc.Type, fc.Condition = criteriaBeg, strings.TrimSuffix(exp, "*")
  1169. }
  1170. return
  1171. }
  1172. fc.Type, fc.Condition = criteriaEq, exp
  1173. return
  1174. }
  1175. // formulaCriteriaEval evaluate formula criteria expression.
  1176. func formulaCriteriaEval(val string, criteria *formulaCriteria) (result bool, err error) {
  1177. var value, expected float64
  1178. var e error
  1179. var prepareValue = func(val, cond string) (value float64, expected float64, err error) {
  1180. if value, err = strconv.ParseFloat(val, 64); err != nil {
  1181. return
  1182. }
  1183. if expected, err = strconv.ParseFloat(criteria.Condition, 64); err != nil {
  1184. return
  1185. }
  1186. return
  1187. }
  1188. switch criteria.Type {
  1189. case criteriaEq:
  1190. return val == criteria.Condition, err
  1191. case criteriaLe:
  1192. value, expected, e = prepareValue(val, criteria.Condition)
  1193. return value <= expected && e == nil, err
  1194. case criteriaGe:
  1195. value, expected, e = prepareValue(val, criteria.Condition)
  1196. return value >= expected && e == nil, err
  1197. case criteriaL:
  1198. value, expected, e = prepareValue(val, criteria.Condition)
  1199. return value < expected && e == nil, err
  1200. case criteriaG:
  1201. value, expected, e = prepareValue(val, criteria.Condition)
  1202. return value > expected && e == nil, err
  1203. case criteriaBeg:
  1204. return strings.HasPrefix(val, criteria.Condition), err
  1205. case criteriaEnd:
  1206. return strings.HasSuffix(val, criteria.Condition), err
  1207. }
  1208. return
  1209. }
  1210. // Engineering Functions
  1211. // BESSELI function the modified Bessel function, which is equivalent to the
  1212. // Bessel function evaluated for purely imaginary arguments. The syntax of
  1213. // the Besseli function is:
  1214. //
  1215. // BESSELI(x,n)
  1216. //
  1217. func (fn *formulaFuncs) BESSELI(argsList *list.List) formulaArg {
  1218. if argsList.Len() != 2 {
  1219. return newErrorFormulaArg(formulaErrorVALUE, "BESSELI requires 2 numeric arguments")
  1220. }
  1221. return fn.bassel(argsList, true)
  1222. }
  1223. // BESSELJ function returns the Bessel function, Jn(x), for a specified order
  1224. // and value of x. The syntax of the function is:
  1225. //
  1226. // BESSELJ(x,n)
  1227. //
  1228. func (fn *formulaFuncs) BESSELJ(argsList *list.List) formulaArg {
  1229. if argsList.Len() != 2 {
  1230. return newErrorFormulaArg(formulaErrorVALUE, "BESSELJ requires 2 numeric arguments")
  1231. }
  1232. return fn.bassel(argsList, false)
  1233. }
  1234. // bassel is an implementation of the formula function BESSELI and BESSELJ.
  1235. func (fn *formulaFuncs) bassel(argsList *list.List, modfied bool) formulaArg {
  1236. x, n := argsList.Front().Value.(formulaArg).ToNumber(), argsList.Back().Value.(formulaArg).ToNumber()
  1237. if x.Type != ArgNumber {
  1238. return x
  1239. }
  1240. if n.Type != ArgNumber {
  1241. return n
  1242. }
  1243. max, x1 := 100, x.Number*0.5
  1244. x2 := x1 * x1
  1245. x1 = math.Pow(x1, n.Number)
  1246. n1, n2, n3, n4, add := fact(n.Number), 1.0, 0.0, n.Number, false
  1247. result := x1 / n1
  1248. t := result * 0.9
  1249. for result != t && max != 0 {
  1250. x1 *= x2
  1251. n3++
  1252. n1 *= n3
  1253. n4++
  1254. n2 *= n4
  1255. t = result
  1256. if modfied || add {
  1257. result += (x1 / n1 / n2)
  1258. } else {
  1259. result -= (x1 / n1 / n2)
  1260. }
  1261. max--
  1262. add = !add
  1263. }
  1264. return newNumberFormulaArg(result)
  1265. }
  1266. // BIN2DEC function converts a Binary (a base-2 number) into a decimal number.
  1267. // The syntax of the function is:
  1268. //
  1269. // BIN2DEC(number)
  1270. //
  1271. func (fn *formulaFuncs) BIN2DEC(argsList *list.List) formulaArg {
  1272. if argsList.Len() != 1 {
  1273. return newErrorFormulaArg(formulaErrorVALUE, "BIN2DEC requires 1 numeric argument")
  1274. }
  1275. token := argsList.Front().Value.(formulaArg)
  1276. number := token.ToNumber()
  1277. if number.Type != ArgNumber {
  1278. return newErrorFormulaArg(formulaErrorVALUE, number.Error)
  1279. }
  1280. return fn.bin2dec(token.Value())
  1281. }
  1282. // BIN2HEX function converts a Binary (Base 2) number into a Hexadecimal
  1283. // (Base 16) number. The syntax of the function is:
  1284. //
  1285. // BIN2HEX(number,[places])
  1286. //
  1287. func (fn *formulaFuncs) BIN2HEX(argsList *list.List) formulaArg {
  1288. if argsList.Len() < 1 {
  1289. return newErrorFormulaArg(formulaErrorVALUE, "BIN2HEX requires at least 1 argument")
  1290. }
  1291. if argsList.Len() > 2 {
  1292. return newErrorFormulaArg(formulaErrorVALUE, "BIN2HEX allows at most 2 arguments")
  1293. }
  1294. token := argsList.Front().Value.(formulaArg)
  1295. number := token.ToNumber()
  1296. if number.Type != ArgNumber {
  1297. return newErrorFormulaArg(formulaErrorVALUE, number.Error)
  1298. }
  1299. decimal, newList := fn.bin2dec(token.Value()), list.New()
  1300. if decimal.Type != ArgNumber {
  1301. return decimal
  1302. }
  1303. newList.PushBack(decimal)
  1304. if argsList.Len() == 2 {
  1305. newList.PushBack(argsList.Back().Value.(formulaArg))
  1306. }
  1307. return fn.dec2x("BIN2HEX", newList)
  1308. }
  1309. // BIN2OCT function converts a Binary (Base 2) number into an Octal (Base 8)
  1310. // number. The syntax of the function is:
  1311. //
  1312. // BIN2OCT(number,[places])
  1313. //
  1314. func (fn *formulaFuncs) BIN2OCT(argsList *list.List) formulaArg {
  1315. if argsList.Len() < 1 {
  1316. return newErrorFormulaArg(formulaErrorVALUE, "BIN2OCT requires at least 1 argument")
  1317. }
  1318. if argsList.Len() > 2 {
  1319. return newErrorFormulaArg(formulaErrorVALUE, "BIN2OCT allows at most 2 arguments")
  1320. }
  1321. token := argsList.Front().Value.(formulaArg)
  1322. number := token.ToNumber()
  1323. if number.Type != ArgNumber {
  1324. return newErrorFormulaArg(formulaErrorVALUE, number.Error)
  1325. }
  1326. decimal, newList := fn.bin2dec(token.Value()), list.New()
  1327. if decimal.Type != ArgNumber {
  1328. return decimal
  1329. }
  1330. newList.PushBack(decimal)
  1331. if argsList.Len() == 2 {
  1332. newList.PushBack(argsList.Back().Value.(formulaArg))
  1333. }
  1334. return fn.dec2x("BIN2OCT", newList)
  1335. }
  1336. // bin2dec is an implementation of the formula function BIN2DEC.
  1337. func (fn *formulaFuncs) bin2dec(number string) formulaArg {
  1338. decimal, length := 0.0, len(number)
  1339. for i := length; i > 0; i-- {
  1340. s := string(number[length-i])
  1341. if i == 10 && s == "1" {
  1342. decimal += math.Pow(-2.0, float64(i-1))
  1343. continue
  1344. }
  1345. if s == "1" {
  1346. decimal += math.Pow(2.0, float64(i-1))
  1347. continue
  1348. }
  1349. if s != "0" {
  1350. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1351. }
  1352. }
  1353. return newNumberFormulaArg(decimal)
  1354. }
  1355. // BITAND function returns the bitwise 'AND' for two supplied integers. The
  1356. // syntax of the function is:
  1357. //
  1358. // BITAND(number1,number2)
  1359. //
  1360. func (fn *formulaFuncs) BITAND(argsList *list.List) formulaArg {
  1361. return fn.bitwise("BITAND", argsList)
  1362. }
  1363. // BITLSHIFT function returns a supplied integer, shifted left by a specified
  1364. // number of bits. The syntax of the function is:
  1365. //
  1366. // BITLSHIFT(number1,shift_amount)
  1367. //
  1368. func (fn *formulaFuncs) BITLSHIFT(argsList *list.List) formulaArg {
  1369. return fn.bitwise("BITLSHIFT", argsList)
  1370. }
  1371. // BITOR function returns the bitwise 'OR' for two supplied integers. The
  1372. // syntax of the function is:
  1373. //
  1374. // BITOR(number1,number2)
  1375. //
  1376. func (fn *formulaFuncs) BITOR(argsList *list.List) formulaArg {
  1377. return fn.bitwise("BITOR", argsList)
  1378. }
  1379. // BITRSHIFT function returns a supplied integer, shifted right by a specified
  1380. // number of bits. The syntax of the function is:
  1381. //
  1382. // BITRSHIFT(number1,shift_amount)
  1383. //
  1384. func (fn *formulaFuncs) BITRSHIFT(argsList *list.List) formulaArg {
  1385. return fn.bitwise("BITRSHIFT", argsList)
  1386. }
  1387. // BITXOR function returns the bitwise 'XOR' (exclusive 'OR') for two supplied
  1388. // integers. The syntax of the function is:
  1389. //
  1390. // BITXOR(number1,number2)
  1391. //
  1392. func (fn *formulaFuncs) BITXOR(argsList *list.List) formulaArg {
  1393. return fn.bitwise("BITXOR", argsList)
  1394. }
  1395. // bitwise is an implementation of the formula function BITAND, BITLSHIFT,
  1396. // BITOR, BITRSHIFT and BITXOR.
  1397. func (fn *formulaFuncs) bitwise(name string, argsList *list.List) formulaArg {
  1398. if argsList.Len() != 2 {
  1399. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires 2 numeric arguments", name))
  1400. }
  1401. num1, num2 := argsList.Front().Value.(formulaArg).ToNumber(), argsList.Back().Value.(formulaArg).ToNumber()
  1402. if num1.Type != ArgNumber || num2.Type != ArgNumber {
  1403. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1404. }
  1405. max := math.Pow(2, 48) - 1
  1406. if num1.Number < 0 || num1.Number > max || num2.Number < 0 || num2.Number > max {
  1407. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1408. }
  1409. bitwiseFuncMap := map[string]func(a, b int) int{
  1410. "BITAND": func(a, b int) int { return a & b },
  1411. "BITLSHIFT": func(a, b int) int { return a << uint(b) },
  1412. "BITOR": func(a, b int) int { return a | b },
  1413. "BITRSHIFT": func(a, b int) int { return a >> uint(b) },
  1414. "BITXOR": func(a, b int) int { return a ^ b },
  1415. }
  1416. bitwiseFunc := bitwiseFuncMap[name]
  1417. return newNumberFormulaArg(float64(bitwiseFunc(int(num1.Number), int(num2.Number))))
  1418. }
  1419. // COMPLEX function takes two arguments, representing the real and the
  1420. // imaginary coefficients of a complex number, and from these, creates a
  1421. // complex number. The syntax of the function is:
  1422. //
  1423. // COMPLEX(real_num,i_num,[suffix])
  1424. //
  1425. func (fn *formulaFuncs) COMPLEX(argsList *list.List) formulaArg {
  1426. if argsList.Len() < 2 {
  1427. return newErrorFormulaArg(formulaErrorVALUE, "COMPLEX requires at least 2 arguments")
  1428. }
  1429. if argsList.Len() > 3 {
  1430. return newErrorFormulaArg(formulaErrorVALUE, "COMPLEX allows at most 3 arguments")
  1431. }
  1432. real, i, suffix := argsList.Front().Value.(formulaArg).ToNumber(), argsList.Front().Next().Value.(formulaArg).ToNumber(), "i"
  1433. if real.Type != ArgNumber {
  1434. return real
  1435. }
  1436. if i.Type != ArgNumber {
  1437. return i
  1438. }
  1439. if argsList.Len() == 3 {
  1440. if suffix = strings.ToLower(argsList.Back().Value.(formulaArg).Value()); suffix != "i" && suffix != "j" {
  1441. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  1442. }
  1443. }
  1444. return newStringFormulaArg(cmplx2str(fmt.Sprint(complex(real.Number, i.Number)), suffix))
  1445. }
  1446. // cmplx2str replace complex number string characters.
  1447. func cmplx2str(c, suffix string) string {
  1448. if c == "(0+0i)" || c == "(-0+0i)" || c == "(0-0i)" || c == "(-0-0i)" {
  1449. return "0"
  1450. }
  1451. c = strings.TrimPrefix(c, "(")
  1452. c = strings.TrimPrefix(c, "+0+")
  1453. c = strings.TrimPrefix(c, "-0+")
  1454. c = strings.TrimSuffix(c, ")")
  1455. c = strings.TrimPrefix(c, "0+")
  1456. if strings.HasPrefix(c, "0-") {
  1457. c = "-" + strings.TrimPrefix(c, "0-")
  1458. }
  1459. c = strings.TrimPrefix(c, "0+")
  1460. c = strings.TrimSuffix(c, "+0i")
  1461. c = strings.TrimSuffix(c, "-0i")
  1462. c = strings.NewReplacer("+1i", "+i", "-1i", "-i").Replace(c)
  1463. c = strings.Replace(c, "i", suffix, -1)
  1464. return c
  1465. }
  1466. // str2cmplx convert complex number string characters.
  1467. func str2cmplx(c string) string {
  1468. c = strings.Replace(c, "j", "i", -1)
  1469. if c == "i" {
  1470. c = "1i"
  1471. }
  1472. c = strings.NewReplacer("+i", "+1i", "-i", "-1i").Replace(c)
  1473. return c
  1474. }
  1475. // DEC2BIN function converts a decimal number into a Binary (Base 2) number.
  1476. // The syntax of the function is:
  1477. //
  1478. // DEC2BIN(number,[places])
  1479. //
  1480. func (fn *formulaFuncs) DEC2BIN(argsList *list.List) formulaArg {
  1481. return fn.dec2x("DEC2BIN", argsList)
  1482. }
  1483. // DEC2HEX function converts a decimal number into a Hexadecimal (Base 16)
  1484. // number. The syntax of the function is:
  1485. //
  1486. // DEC2HEX(number,[places])
  1487. //
  1488. func (fn *formulaFuncs) DEC2HEX(argsList *list.List) formulaArg {
  1489. return fn.dec2x("DEC2HEX", argsList)
  1490. }
  1491. // DEC2OCT function converts a decimal number into an Octal (Base 8) number.
  1492. // The syntax of the function is:
  1493. //
  1494. // DEC2OCT(number,[places])
  1495. //
  1496. func (fn *formulaFuncs) DEC2OCT(argsList *list.List) formulaArg {
  1497. return fn.dec2x("DEC2OCT", argsList)
  1498. }
  1499. // dec2x is an implementation of the formula function DEC2BIN, DEC2HEX and
  1500. // DEC2OCT.
  1501. func (fn *formulaFuncs) dec2x(name string, argsList *list.List) formulaArg {
  1502. if argsList.Len() < 1 {
  1503. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires at least 1 argument", name))
  1504. }
  1505. if argsList.Len() > 2 {
  1506. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s allows at most 2 arguments", name))
  1507. }
  1508. decimal := argsList.Front().Value.(formulaArg).ToNumber()
  1509. if decimal.Type != ArgNumber {
  1510. return newErrorFormulaArg(formulaErrorVALUE, decimal.Error)
  1511. }
  1512. maxLimitMap := map[string]float64{
  1513. "DEC2BIN": 511,
  1514. "HEX2BIN": 511,
  1515. "OCT2BIN": 511,
  1516. "BIN2HEX": 549755813887,
  1517. "DEC2HEX": 549755813887,
  1518. "OCT2HEX": 549755813887,
  1519. "BIN2OCT": 536870911,
  1520. "DEC2OCT": 536870911,
  1521. "HEX2OCT": 536870911,
  1522. }
  1523. minLimitMap := map[string]float64{
  1524. "DEC2BIN": -512,
  1525. "HEX2BIN": -512,
  1526. "OCT2BIN": -512,
  1527. "BIN2HEX": -549755813888,
  1528. "DEC2HEX": -549755813888,
  1529. "OCT2HEX": -549755813888,
  1530. "BIN2OCT": -536870912,
  1531. "DEC2OCT": -536870912,
  1532. "HEX2OCT": -536870912,
  1533. }
  1534. baseMap := map[string]int{
  1535. "DEC2BIN": 2,
  1536. "HEX2BIN": 2,
  1537. "OCT2BIN": 2,
  1538. "BIN2HEX": 16,
  1539. "DEC2HEX": 16,
  1540. "OCT2HEX": 16,
  1541. "BIN2OCT": 8,
  1542. "DEC2OCT": 8,
  1543. "HEX2OCT": 8,
  1544. }
  1545. maxLimit, minLimit := maxLimitMap[name], minLimitMap[name]
  1546. base := baseMap[name]
  1547. if decimal.Number < minLimit || decimal.Number > maxLimit {
  1548. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1549. }
  1550. n := int64(decimal.Number)
  1551. binary := strconv.FormatUint(*(*uint64)(unsafe.Pointer(&n)), base)
  1552. if argsList.Len() == 2 {
  1553. places := argsList.Back().Value.(formulaArg).ToNumber()
  1554. if places.Type != ArgNumber {
  1555. return newErrorFormulaArg(formulaErrorVALUE, places.Error)
  1556. }
  1557. binaryPlaces := len(binary)
  1558. if places.Number < 0 || places.Number > 10 || binaryPlaces > int(places.Number) {
  1559. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1560. }
  1561. return newStringFormulaArg(strings.ToUpper(fmt.Sprintf("%s%s", strings.Repeat("0", int(places.Number)-binaryPlaces), binary)))
  1562. }
  1563. if decimal.Number < 0 && len(binary) > 10 {
  1564. return newStringFormulaArg(strings.ToUpper(binary[len(binary)-10:]))
  1565. }
  1566. return newStringFormulaArg(strings.ToUpper(binary))
  1567. }
  1568. // HEX2BIN function converts a Hexadecimal (Base 16) number into a Binary
  1569. // (Base 2) number. The syntax of the function is:
  1570. //
  1571. // HEX2BIN(number,[places])
  1572. //
  1573. func (fn *formulaFuncs) HEX2BIN(argsList *list.List) formulaArg {
  1574. if argsList.Len() < 1 {
  1575. return newErrorFormulaArg(formulaErrorVALUE, "HEX2BIN requires at least 1 argument")
  1576. }
  1577. if argsList.Len() > 2 {
  1578. return newErrorFormulaArg(formulaErrorVALUE, "HEX2BIN allows at most 2 arguments")
  1579. }
  1580. decimal, newList := fn.hex2dec(argsList.Front().Value.(formulaArg).Value()), list.New()
  1581. if decimal.Type != ArgNumber {
  1582. return decimal
  1583. }
  1584. newList.PushBack(decimal)
  1585. if argsList.Len() == 2 {
  1586. newList.PushBack(argsList.Back().Value.(formulaArg))
  1587. }
  1588. return fn.dec2x("HEX2BIN", newList)
  1589. }
  1590. // HEX2DEC function converts a hexadecimal (a base-16 number) into a decimal
  1591. // number. The syntax of the function is:
  1592. //
  1593. // HEX2DEC(number)
  1594. //
  1595. func (fn *formulaFuncs) HEX2DEC(argsList *list.List) formulaArg {
  1596. if argsList.Len() != 1 {
  1597. return newErrorFormulaArg(formulaErrorVALUE, "HEX2DEC requires 1 numeric argument")
  1598. }
  1599. return fn.hex2dec(argsList.Front().Value.(formulaArg).Value())
  1600. }
  1601. // HEX2OCT function converts a Hexadecimal (Base 16) number into an Octal
  1602. // (Base 8) number. The syntax of the function is:
  1603. //
  1604. // HEX2OCT(number,[places])
  1605. //
  1606. func (fn *formulaFuncs) HEX2OCT(argsList *list.List) formulaArg {
  1607. if argsList.Len() < 1 {
  1608. return newErrorFormulaArg(formulaErrorVALUE, "HEX2OCT requires at least 1 argument")
  1609. }
  1610. if argsList.Len() > 2 {
  1611. return newErrorFormulaArg(formulaErrorVALUE, "HEX2OCT allows at most 2 arguments")
  1612. }
  1613. decimal, newList := fn.hex2dec(argsList.Front().Value.(formulaArg).Value()), list.New()
  1614. if decimal.Type != ArgNumber {
  1615. return decimal
  1616. }
  1617. newList.PushBack(decimal)
  1618. if argsList.Len() == 2 {
  1619. newList.PushBack(argsList.Back().Value.(formulaArg))
  1620. }
  1621. return fn.dec2x("HEX2OCT", newList)
  1622. }
  1623. // hex2dec is an implementation of the formula function HEX2DEC.
  1624. func (fn *formulaFuncs) hex2dec(number string) formulaArg {
  1625. decimal, length := 0.0, len(number)
  1626. for i := length; i > 0; i-- {
  1627. num, err := strconv.ParseInt(string(number[length-i]), 16, 64)
  1628. if err != nil {
  1629. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1630. }
  1631. if i == 10 && string(number[length-i]) == "F" {
  1632. decimal += math.Pow(-16.0, float64(i-1))
  1633. continue
  1634. }
  1635. decimal += float64(num) * math.Pow(16.0, float64(i-1))
  1636. }
  1637. return newNumberFormulaArg(decimal)
  1638. }
  1639. // IMABS function returns the absolute value (the modulus) of a complex
  1640. // number. The syntax of the function is:
  1641. //
  1642. // IMABS(inumber)
  1643. //
  1644. func (fn *formulaFuncs) IMABS(argsList *list.List) formulaArg {
  1645. if argsList.Len() != 1 {
  1646. return newErrorFormulaArg(formulaErrorVALUE, "IMABS requires 1 argument")
  1647. }
  1648. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1649. if err != nil {
  1650. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1651. }
  1652. return newNumberFormulaArg(cmplx.Abs(inumber))
  1653. }
  1654. // IMAGINARY function returns the imaginary coefficient of a supplied complex
  1655. // number. The syntax of the function is:
  1656. //
  1657. // IMAGINARY(inumber)
  1658. //
  1659. func (fn *formulaFuncs) IMAGINARY(argsList *list.List) formulaArg {
  1660. if argsList.Len() != 1 {
  1661. return newErrorFormulaArg(formulaErrorVALUE, "IMAGINARY requires 1 argument")
  1662. }
  1663. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1664. if err != nil {
  1665. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1666. }
  1667. return newNumberFormulaArg(imag(inumber))
  1668. }
  1669. // IMARGUMENT function returns the phase (also called the argument) of a
  1670. // supplied complex number. The syntax of the function is:
  1671. //
  1672. // IMARGUMENT(inumber)
  1673. //
  1674. func (fn *formulaFuncs) IMARGUMENT(argsList *list.List) formulaArg {
  1675. if argsList.Len() != 1 {
  1676. return newErrorFormulaArg(formulaErrorVALUE, "IMARGUMENT requires 1 argument")
  1677. }
  1678. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1679. if err != nil {
  1680. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1681. }
  1682. return newNumberFormulaArg(cmplx.Phase(inumber))
  1683. }
  1684. // IMCONJUGATE function returns the complex conjugate of a supplied complex
  1685. // number. The syntax of the function is:
  1686. //
  1687. // IMCONJUGATE(inumber)
  1688. //
  1689. func (fn *formulaFuncs) IMCONJUGATE(argsList *list.List) formulaArg {
  1690. if argsList.Len() != 1 {
  1691. return newErrorFormulaArg(formulaErrorVALUE, "IMCONJUGATE requires 1 argument")
  1692. }
  1693. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1694. if err != nil {
  1695. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1696. }
  1697. return newStringFormulaArg(cmplx2str(fmt.Sprint(cmplx.Conj(inumber)), "i"))
  1698. }
  1699. // IMCOS function returns the cosine of a supplied complex number. The syntax
  1700. // of the function is:
  1701. //
  1702. // IMCOS(inumber)
  1703. //
  1704. func (fn *formulaFuncs) IMCOS(argsList *list.List) formulaArg {
  1705. if argsList.Len() != 1 {
  1706. return newErrorFormulaArg(formulaErrorVALUE, "IMCOS requires 1 argument")
  1707. }
  1708. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1709. if err != nil {
  1710. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1711. }
  1712. return newStringFormulaArg(cmplx2str(fmt.Sprint(cmplx.Cos(inumber)), "i"))
  1713. }
  1714. // IMCOSH function returns the hyperbolic cosine of a supplied complex number. The syntax
  1715. // of the function is:
  1716. //
  1717. // IMCOSH(inumber)
  1718. //
  1719. func (fn *formulaFuncs) IMCOSH(argsList *list.List) formulaArg {
  1720. if argsList.Len() != 1 {
  1721. return newErrorFormulaArg(formulaErrorVALUE, "IMCOSH requires 1 argument")
  1722. }
  1723. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1724. if err != nil {
  1725. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1726. }
  1727. return newStringFormulaArg(cmplx2str(fmt.Sprint(cmplx.Cosh(inumber)), "i"))
  1728. }
  1729. // IMCOT function returns the cotangent of a supplied complex number. The syntax
  1730. // of the function is:
  1731. //
  1732. // IMCOT(inumber)
  1733. //
  1734. func (fn *formulaFuncs) IMCOT(argsList *list.List) formulaArg {
  1735. if argsList.Len() != 1 {
  1736. return newErrorFormulaArg(formulaErrorVALUE, "IMCOT requires 1 argument")
  1737. }
  1738. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1739. if err != nil {
  1740. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1741. }
  1742. return newStringFormulaArg(cmplx2str(fmt.Sprint(cmplx.Cot(inumber)), "i"))
  1743. }
  1744. // IMCSC function returns the cosecant of a supplied complex number. The syntax
  1745. // of the function is:
  1746. //
  1747. // IMCSC(inumber)
  1748. //
  1749. func (fn *formulaFuncs) IMCSC(argsList *list.List) formulaArg {
  1750. if argsList.Len() != 1 {
  1751. return newErrorFormulaArg(formulaErrorVALUE, "IMCSC requires 1 argument")
  1752. }
  1753. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1754. if err != nil {
  1755. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1756. }
  1757. num := 1 / cmplx.Sin(inumber)
  1758. if cmplx.IsInf(num) {
  1759. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1760. }
  1761. return newStringFormulaArg(cmplx2str(fmt.Sprint(num), "i"))
  1762. }
  1763. // IMCSCH function returns the hyperbolic cosecant of a supplied complex
  1764. // number. The syntax of the function is:
  1765. //
  1766. // IMCSCH(inumber)
  1767. //
  1768. func (fn *formulaFuncs) IMCSCH(argsList *list.List) formulaArg {
  1769. if argsList.Len() != 1 {
  1770. return newErrorFormulaArg(formulaErrorVALUE, "IMCSCH requires 1 argument")
  1771. }
  1772. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1773. if err != nil {
  1774. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1775. }
  1776. num := 1 / cmplx.Sinh(inumber)
  1777. if cmplx.IsInf(num) {
  1778. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1779. }
  1780. return newStringFormulaArg(cmplx2str(fmt.Sprint(num), "i"))
  1781. }
  1782. // IMDIV function calculates the quotient of two complex numbers (i.e. divides
  1783. // one complex number by another). The syntax of the function is:
  1784. //
  1785. // IMDIV(inumber1,inumber2)
  1786. //
  1787. func (fn *formulaFuncs) IMDIV(argsList *list.List) formulaArg {
  1788. if argsList.Len() != 2 {
  1789. return newErrorFormulaArg(formulaErrorVALUE, "IMDIV requires 2 arguments")
  1790. }
  1791. inumber1, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1792. if err != nil {
  1793. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1794. }
  1795. inumber2, err := strconv.ParseComplex(str2cmplx(argsList.Back().Value.(formulaArg).Value()), 128)
  1796. if err != nil {
  1797. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1798. }
  1799. num := inumber1 / inumber2
  1800. if cmplx.IsInf(num) {
  1801. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1802. }
  1803. return newStringFormulaArg(cmplx2str(fmt.Sprint(num), "i"))
  1804. }
  1805. // IMEXP function returns the exponential of a supplied complex number. The
  1806. // syntax of the function is:
  1807. //
  1808. // IMEXP(inumber)
  1809. //
  1810. func (fn *formulaFuncs) IMEXP(argsList *list.List) formulaArg {
  1811. if argsList.Len() != 1 {
  1812. return newErrorFormulaArg(formulaErrorVALUE, "IMEXP requires 1 argument")
  1813. }
  1814. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1815. if err != nil {
  1816. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1817. }
  1818. return newStringFormulaArg(cmplx2str(fmt.Sprint(cmplx.Exp(inumber)), "i"))
  1819. }
  1820. // IMLN function returns the natural logarithm of a supplied complex number.
  1821. // The syntax of the function is:
  1822. //
  1823. // IMLN(inumber)
  1824. //
  1825. func (fn *formulaFuncs) IMLN(argsList *list.List) formulaArg {
  1826. if argsList.Len() != 1 {
  1827. return newErrorFormulaArg(formulaErrorVALUE, "IMLN requires 1 argument")
  1828. }
  1829. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1830. if err != nil {
  1831. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1832. }
  1833. num := cmplx.Log(inumber)
  1834. if cmplx.IsInf(num) {
  1835. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1836. }
  1837. return newStringFormulaArg(cmplx2str(fmt.Sprint(num), "i"))
  1838. }
  1839. // IMLOG10 function returns the common (base 10) logarithm of a supplied
  1840. // complex number. The syntax of the function is:
  1841. //
  1842. // IMLOG10(inumber)
  1843. //
  1844. func (fn *formulaFuncs) IMLOG10(argsList *list.List) formulaArg {
  1845. if argsList.Len() != 1 {
  1846. return newErrorFormulaArg(formulaErrorVALUE, "IMLOG10 requires 1 argument")
  1847. }
  1848. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1849. if err != nil {
  1850. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1851. }
  1852. num := cmplx.Log10(inumber)
  1853. if cmplx.IsInf(num) {
  1854. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1855. }
  1856. return newStringFormulaArg(cmplx2str(fmt.Sprint(num), "i"))
  1857. }
  1858. // IMLOG2 function calculates the base 2 logarithm of a supplied complex
  1859. // number. The syntax of the function is:
  1860. //
  1861. // IMLOG2(inumber)
  1862. //
  1863. func (fn *formulaFuncs) IMLOG2(argsList *list.List) formulaArg {
  1864. if argsList.Len() != 1 {
  1865. return newErrorFormulaArg(formulaErrorVALUE, "IMLOG2 requires 1 argument")
  1866. }
  1867. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1868. if err != nil {
  1869. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1870. }
  1871. num := cmplx.Log(inumber)
  1872. if cmplx.IsInf(num) {
  1873. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1874. }
  1875. return newStringFormulaArg(cmplx2str(fmt.Sprint(num/cmplx.Log(2)), "i"))
  1876. }
  1877. // IMPOWER function returns a supplied complex number, raised to a given
  1878. // power. The syntax of the function is:
  1879. //
  1880. // IMPOWER(inumber,number)
  1881. //
  1882. func (fn *formulaFuncs) IMPOWER(argsList *list.List) formulaArg {
  1883. if argsList.Len() != 2 {
  1884. return newErrorFormulaArg(formulaErrorVALUE, "IMPOWER requires 2 arguments")
  1885. }
  1886. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1887. if err != nil {
  1888. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1889. }
  1890. number, err := strconv.ParseComplex(str2cmplx(argsList.Back().Value.(formulaArg).Value()), 128)
  1891. if err != nil {
  1892. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1893. }
  1894. if inumber == 0 && number == 0 {
  1895. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1896. }
  1897. num := cmplx.Pow(inumber, number)
  1898. if cmplx.IsInf(num) {
  1899. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1900. }
  1901. return newStringFormulaArg(cmplx2str(fmt.Sprint(num), "i"))
  1902. }
  1903. // IMPRODUCT function calculates the product of two or more complex numbers.
  1904. // The syntax of the function is:
  1905. //
  1906. // IMPRODUCT(number1,[number2],...)
  1907. //
  1908. func (fn *formulaFuncs) IMPRODUCT(argsList *list.List) formulaArg {
  1909. product := complex128(1)
  1910. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  1911. token := arg.Value.(formulaArg)
  1912. switch token.Type {
  1913. case ArgString:
  1914. if token.Value() == "" {
  1915. continue
  1916. }
  1917. val, err := strconv.ParseComplex(str2cmplx(token.Value()), 128)
  1918. if err != nil {
  1919. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1920. }
  1921. product = product * val
  1922. case ArgNumber:
  1923. product = product * complex(token.Number, 0)
  1924. case ArgMatrix:
  1925. for _, row := range token.Matrix {
  1926. for _, value := range row {
  1927. if value.Value() == "" {
  1928. continue
  1929. }
  1930. val, err := strconv.ParseComplex(str2cmplx(value.Value()), 128)
  1931. if err != nil {
  1932. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1933. }
  1934. product = product * val
  1935. }
  1936. }
  1937. }
  1938. }
  1939. return newStringFormulaArg(cmplx2str(fmt.Sprint(product), "i"))
  1940. }
  1941. // IMREAL function returns the real coefficient of a supplied complex number.
  1942. // The syntax of the function is:
  1943. //
  1944. // IMREAL(inumber)
  1945. //
  1946. func (fn *formulaFuncs) IMREAL(argsList *list.List) formulaArg {
  1947. if argsList.Len() != 1 {
  1948. return newErrorFormulaArg(formulaErrorVALUE, "IMREAL requires 1 argument")
  1949. }
  1950. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1951. if err != nil {
  1952. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1953. }
  1954. return newStringFormulaArg(cmplx2str(fmt.Sprint(real(inumber)), "i"))
  1955. }
  1956. // IMSEC function returns the secant of a supplied complex number. The syntax
  1957. // of the function is:
  1958. //
  1959. // IMSEC(inumber)
  1960. //
  1961. func (fn *formulaFuncs) IMSEC(argsList *list.List) formulaArg {
  1962. if argsList.Len() != 1 {
  1963. return newErrorFormulaArg(formulaErrorVALUE, "IMSEC requires 1 argument")
  1964. }
  1965. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1966. if err != nil {
  1967. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1968. }
  1969. return newStringFormulaArg(cmplx2str(fmt.Sprint(1/cmplx.Cos(inumber)), "i"))
  1970. }
  1971. // IMSECH function returns the hyperbolic secant of a supplied complex number.
  1972. // The syntax of the function is:
  1973. //
  1974. // IMSECH(inumber)
  1975. //
  1976. func (fn *formulaFuncs) IMSECH(argsList *list.List) formulaArg {
  1977. if argsList.Len() != 1 {
  1978. return newErrorFormulaArg(formulaErrorVALUE, "IMSECH requires 1 argument")
  1979. }
  1980. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1981. if err != nil {
  1982. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1983. }
  1984. return newStringFormulaArg(cmplx2str(fmt.Sprint(1/cmplx.Cosh(inumber)), "i"))
  1985. }
  1986. // IMSIN function returns the Sine of a supplied complex number. The syntax of
  1987. // the function is:
  1988. //
  1989. // IMSIN(inumber)
  1990. //
  1991. func (fn *formulaFuncs) IMSIN(argsList *list.List) formulaArg {
  1992. if argsList.Len() != 1 {
  1993. return newErrorFormulaArg(formulaErrorVALUE, "IMSIN requires 1 argument")
  1994. }
  1995. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1996. if err != nil {
  1997. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1998. }
  1999. return newStringFormulaArg(cmplx2str(fmt.Sprint(cmplx.Sin(inumber)), "i"))
  2000. }
  2001. // IMSINH function returns the hyperbolic sine of a supplied complex number.
  2002. // The syntax of the function is:
  2003. //
  2004. // IMSINH(inumber)
  2005. //
  2006. func (fn *formulaFuncs) IMSINH(argsList *list.List) formulaArg {
  2007. if argsList.Len() != 1 {
  2008. return newErrorFormulaArg(formulaErrorVALUE, "IMSINH requires 1 argument")
  2009. }
  2010. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  2011. if err != nil {
  2012. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2013. }
  2014. return newStringFormulaArg(cmplx2str(fmt.Sprint(cmplx.Sinh(inumber)), "i"))
  2015. }
  2016. // IMSQRT function returns the square root of a supplied complex number. The
  2017. // syntax of the function is:
  2018. //
  2019. // IMSQRT(inumber)
  2020. //
  2021. func (fn *formulaFuncs) IMSQRT(argsList *list.List) formulaArg {
  2022. if argsList.Len() != 1 {
  2023. return newErrorFormulaArg(formulaErrorVALUE, "IMSQRT requires 1 argument")
  2024. }
  2025. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  2026. if err != nil {
  2027. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2028. }
  2029. return newStringFormulaArg(cmplx2str(fmt.Sprint(cmplx.Sqrt(inumber)), "i"))
  2030. }
  2031. // IMSUB function calculates the difference between two complex numbers
  2032. // (i.e. subtracts one complex number from another). The syntax of the
  2033. // function is:
  2034. //
  2035. // IMSUB(inumber1,inumber2)
  2036. //
  2037. func (fn *formulaFuncs) IMSUB(argsList *list.List) formulaArg {
  2038. if argsList.Len() != 2 {
  2039. return newErrorFormulaArg(formulaErrorVALUE, "IMSUB requires 2 arguments")
  2040. }
  2041. i1, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  2042. if err != nil {
  2043. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2044. }
  2045. i2, err := strconv.ParseComplex(str2cmplx(argsList.Back().Value.(formulaArg).Value()), 128)
  2046. if err != nil {
  2047. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2048. }
  2049. return newStringFormulaArg(cmplx2str(fmt.Sprint(i1-i2), "i"))
  2050. }
  2051. // IMSUM function calculates the sum of two or more complex numbers. The
  2052. // syntax of the function is:
  2053. //
  2054. // IMSUM(inumber1,inumber2,...)
  2055. //
  2056. func (fn *formulaFuncs) IMSUM(argsList *list.List) formulaArg {
  2057. if argsList.Len() < 1 {
  2058. return newErrorFormulaArg(formulaErrorVALUE, "IMSUM requires at least 1 argument")
  2059. }
  2060. var result complex128
  2061. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  2062. token := arg.Value.(formulaArg)
  2063. num, err := strconv.ParseComplex(str2cmplx(token.Value()), 128)
  2064. if err != nil {
  2065. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2066. }
  2067. result += num
  2068. }
  2069. return newStringFormulaArg(cmplx2str(fmt.Sprint(result), "i"))
  2070. }
  2071. // IMTAN function returns the tangent of a supplied complex number. The syntax
  2072. // of the function is:
  2073. //
  2074. // IMTAN(inumber)
  2075. //
  2076. func (fn *formulaFuncs) IMTAN(argsList *list.List) formulaArg {
  2077. if argsList.Len() != 1 {
  2078. return newErrorFormulaArg(formulaErrorVALUE, "IMTAN requires 1 argument")
  2079. }
  2080. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  2081. if err != nil {
  2082. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2083. }
  2084. return newStringFormulaArg(cmplx2str(fmt.Sprint(cmplx.Tan(inumber)), "i"))
  2085. }
  2086. // OCT2BIN function converts an Octal (Base 8) number into a Binary (Base 2)
  2087. // number. The syntax of the function is:
  2088. //
  2089. // OCT2BIN(number,[places])
  2090. //
  2091. func (fn *formulaFuncs) OCT2BIN(argsList *list.List) formulaArg {
  2092. if argsList.Len() < 1 {
  2093. return newErrorFormulaArg(formulaErrorVALUE, "OCT2BIN requires at least 1 argument")
  2094. }
  2095. if argsList.Len() > 2 {
  2096. return newErrorFormulaArg(formulaErrorVALUE, "OCT2BIN allows at most 2 arguments")
  2097. }
  2098. token := argsList.Front().Value.(formulaArg)
  2099. number := token.ToNumber()
  2100. if number.Type != ArgNumber {
  2101. return newErrorFormulaArg(formulaErrorVALUE, number.Error)
  2102. }
  2103. decimal, newList := fn.oct2dec(token.Value()), list.New()
  2104. newList.PushBack(decimal)
  2105. if argsList.Len() == 2 {
  2106. newList.PushBack(argsList.Back().Value.(formulaArg))
  2107. }
  2108. return fn.dec2x("OCT2BIN", newList)
  2109. }
  2110. // OCT2DEC function converts an Octal (a base-8 number) into a decimal number.
  2111. // The syntax of the function is:
  2112. //
  2113. // OCT2DEC(number)
  2114. //
  2115. func (fn *formulaFuncs) OCT2DEC(argsList *list.List) formulaArg {
  2116. if argsList.Len() != 1 {
  2117. return newErrorFormulaArg(formulaErrorVALUE, "OCT2DEC requires 1 numeric argument")
  2118. }
  2119. token := argsList.Front().Value.(formulaArg)
  2120. number := token.ToNumber()
  2121. if number.Type != ArgNumber {
  2122. return newErrorFormulaArg(formulaErrorVALUE, number.Error)
  2123. }
  2124. return fn.oct2dec(token.Value())
  2125. }
  2126. // OCT2HEX function converts an Octal (Base 8) number into a Hexadecimal
  2127. // (Base 16) number. The syntax of the function is:
  2128. //
  2129. // OCT2HEX(number,[places])
  2130. //
  2131. func (fn *formulaFuncs) OCT2HEX(argsList *list.List) formulaArg {
  2132. if argsList.Len() < 1 {
  2133. return newErrorFormulaArg(formulaErrorVALUE, "OCT2HEX requires at least 1 argument")
  2134. }
  2135. if argsList.Len() > 2 {
  2136. return newErrorFormulaArg(formulaErrorVALUE, "OCT2HEX allows at most 2 arguments")
  2137. }
  2138. token := argsList.Front().Value.(formulaArg)
  2139. number := token.ToNumber()
  2140. if number.Type != ArgNumber {
  2141. return newErrorFormulaArg(formulaErrorVALUE, number.Error)
  2142. }
  2143. decimal, newList := fn.oct2dec(token.Value()), list.New()
  2144. newList.PushBack(decimal)
  2145. if argsList.Len() == 2 {
  2146. newList.PushBack(argsList.Back().Value.(formulaArg))
  2147. }
  2148. return fn.dec2x("OCT2HEX", newList)
  2149. }
  2150. // oct2dec is an implementation of the formula function OCT2DEC.
  2151. func (fn *formulaFuncs) oct2dec(number string) formulaArg {
  2152. decimal, length := 0.0, len(number)
  2153. for i := length; i > 0; i-- {
  2154. num, _ := strconv.Atoi(string(number[length-i]))
  2155. if i == 10 && string(number[length-i]) == "7" {
  2156. decimal += math.Pow(-8.0, float64(i-1))
  2157. continue
  2158. }
  2159. decimal += float64(num) * math.Pow(8.0, float64(i-1))
  2160. }
  2161. return newNumberFormulaArg(decimal)
  2162. }
  2163. // Math and Trigonometric Functions
  2164. // ABS function returns the absolute value of any supplied number. The syntax
  2165. // of the function is:
  2166. //
  2167. // ABS(number)
  2168. //
  2169. func (fn *formulaFuncs) ABS(argsList *list.List) formulaArg {
  2170. if argsList.Len() != 1 {
  2171. return newErrorFormulaArg(formulaErrorVALUE, "ABS requires 1 numeric argument")
  2172. }
  2173. arg := argsList.Front().Value.(formulaArg).ToNumber()
  2174. if arg.Type == ArgError {
  2175. return arg
  2176. }
  2177. return newNumberFormulaArg(math.Abs(arg.Number))
  2178. }
  2179. // ACOS function calculates the arccosine (i.e. the inverse cosine) of a given
  2180. // number, and returns an angle, in radians, between 0 and π. The syntax of
  2181. // the function is:
  2182. //
  2183. // ACOS(number)
  2184. //
  2185. func (fn *formulaFuncs) ACOS(argsList *list.List) formulaArg {
  2186. if argsList.Len() != 1 {
  2187. return newErrorFormulaArg(formulaErrorVALUE, "ACOS requires 1 numeric argument")
  2188. }
  2189. arg := argsList.Front().Value.(formulaArg).ToNumber()
  2190. if arg.Type == ArgError {
  2191. return arg
  2192. }
  2193. return newNumberFormulaArg(math.Acos(arg.Number))
  2194. }
  2195. // ACOSH function calculates the inverse hyperbolic cosine of a supplied number.
  2196. // of the function is:
  2197. //
  2198. // ACOSH(number)
  2199. //
  2200. func (fn *formulaFuncs) ACOSH(argsList *list.List) formulaArg {
  2201. if argsList.Len() != 1 {
  2202. return newErrorFormulaArg(formulaErrorVALUE, "ACOSH requires 1 numeric argument")
  2203. }
  2204. arg := argsList.Front().Value.(formulaArg).ToNumber()
  2205. if arg.Type == ArgError {
  2206. return arg
  2207. }
  2208. return newNumberFormulaArg(math.Acosh(arg.Number))
  2209. }
  2210. // ACOT function calculates the arccotangent (i.e. the inverse cotangent) of a
  2211. // given number, and returns an angle, in radians, between 0 and π. The syntax
  2212. // of the function is:
  2213. //
  2214. // ACOT(number)
  2215. //
  2216. func (fn *formulaFuncs) ACOT(argsList *list.List) formulaArg {
  2217. if argsList.Len() != 1 {
  2218. return newErrorFormulaArg(formulaErrorVALUE, "ACOT requires 1 numeric argument")
  2219. }
  2220. arg := argsList.Front().Value.(formulaArg).ToNumber()
  2221. if arg.Type == ArgError {
  2222. return arg
  2223. }
  2224. return newNumberFormulaArg(math.Pi/2 - math.Atan(arg.Number))
  2225. }
  2226. // ACOTH function calculates the hyperbolic arccotangent (coth) of a supplied
  2227. // value. The syntax of the function is:
  2228. //
  2229. // ACOTH(number)
  2230. //
  2231. func (fn *formulaFuncs) ACOTH(argsList *list.List) formulaArg {
  2232. if argsList.Len() != 1 {
  2233. return newErrorFormulaArg(formulaErrorVALUE, "ACOTH requires 1 numeric argument")
  2234. }
  2235. arg := argsList.Front().Value.(formulaArg).ToNumber()
  2236. if arg.Type == ArgError {
  2237. return arg
  2238. }
  2239. return newNumberFormulaArg(math.Atanh(1 / arg.Number))
  2240. }
  2241. // ARABIC function converts a Roman numeral into an Arabic numeral. The syntax
  2242. // of the function is:
  2243. //
  2244. // ARABIC(text)
  2245. //
  2246. func (fn *formulaFuncs) ARABIC(argsList *list.List) formulaArg {
  2247. if argsList.Len() != 1 {
  2248. return newErrorFormulaArg(formulaErrorVALUE, "ARABIC requires 1 numeric argument")
  2249. }
  2250. text := argsList.Front().Value.(formulaArg).Value()
  2251. if len(text) > 255 {
  2252. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  2253. }
  2254. text = strings.ToUpper(text)
  2255. number, actualStart, index, isNegative := 0, 0, len(text)-1, false
  2256. startIndex, subtractNumber, currentPartValue, currentCharValue, prevCharValue := 0, 0, 0, 0, -1
  2257. for index >= 0 && text[index] == ' ' {
  2258. index--
  2259. }
  2260. for actualStart <= index && text[actualStart] == ' ' {
  2261. actualStart++
  2262. }
  2263. if actualStart <= index && text[actualStart] == '-' {
  2264. isNegative = true
  2265. actualStart++
  2266. }
  2267. charMap := map[rune]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
  2268. for index >= actualStart {
  2269. startIndex = index
  2270. startChar := text[startIndex]
  2271. index--
  2272. for index >= actualStart && (text[index]|' ') == startChar {
  2273. index--
  2274. }
  2275. currentCharValue = charMap[rune(startChar)]
  2276. currentPartValue = (startIndex - index) * currentCharValue
  2277. if currentCharValue >= prevCharValue {
  2278. number += currentPartValue - subtractNumber
  2279. prevCharValue = currentCharValue
  2280. subtractNumber = 0
  2281. continue
  2282. }
  2283. subtractNumber += currentPartValue
  2284. }
  2285. if subtractNumber != 0 {
  2286. number -= subtractNumber
  2287. }
  2288. if isNegative {
  2289. number = -number
  2290. }
  2291. return newNumberFormulaArg(float64(number))
  2292. }
  2293. // ASIN function calculates the arcsine (i.e. the inverse sine) of a given
  2294. // number, and returns an angle, in radians, between -π/2 and π/2. The syntax
  2295. // of the function is:
  2296. //
  2297. // ASIN(number)
  2298. //
  2299. func (fn *formulaFuncs) ASIN(argsList *list.List) formulaArg {
  2300. if argsList.Len() != 1 {
  2301. return newErrorFormulaArg(formulaErrorVALUE, "ASIN requires 1 numeric argument")
  2302. }
  2303. arg := argsList.Front().Value.(formulaArg).ToNumber()
  2304. if arg.Type == ArgError {
  2305. return arg
  2306. }
  2307. return newNumberFormulaArg(math.Asin(arg.Number))
  2308. }
  2309. // ASINH function calculates the inverse hyperbolic sine of a supplied number.
  2310. // The syntax of the function is:
  2311. //
  2312. // ASINH(number)
  2313. //
  2314. func (fn *formulaFuncs) ASINH(argsList *list.List) formulaArg {
  2315. if argsList.Len() != 1 {
  2316. return newErrorFormulaArg(formulaErrorVALUE, "ASINH requires 1 numeric argument")
  2317. }
  2318. arg := argsList.Front().Value.(formulaArg).ToNumber()
  2319. if arg.Type == ArgError {
  2320. return arg
  2321. }
  2322. return newNumberFormulaArg(math.Asinh(arg.Number))
  2323. }
  2324. // ATAN function calculates the arctangent (i.e. the inverse tangent) of a
  2325. // given number, and returns an angle, in radians, between -π/2 and +π/2. The
  2326. // syntax of the function is:
  2327. //
  2328. // ATAN(number)
  2329. //
  2330. func (fn *formulaFuncs) ATAN(argsList *list.List) formulaArg {
  2331. if argsList.Len() != 1 {
  2332. return newErrorFormulaArg(formulaErrorVALUE, "ATAN requires 1 numeric argument")
  2333. }
  2334. arg := argsList.Front().Value.(formulaArg).ToNumber()
  2335. if arg.Type == ArgError {
  2336. return arg
  2337. }
  2338. return newNumberFormulaArg(math.Atan(arg.Number))
  2339. }
  2340. // ATANH function calculates the inverse hyperbolic tangent of a supplied
  2341. // number. The syntax of the function is:
  2342. //
  2343. // ATANH(number)
  2344. //
  2345. func (fn *formulaFuncs) ATANH(argsList *list.List) formulaArg {
  2346. if argsList.Len() != 1 {
  2347. return newErrorFormulaArg(formulaErrorVALUE, "ATANH requires 1 numeric argument")
  2348. }
  2349. arg := argsList.Front().Value.(formulaArg).ToNumber()
  2350. if arg.Type == ArgError {
  2351. return arg
  2352. }
  2353. return newNumberFormulaArg(math.Atanh(arg.Number))
  2354. }
  2355. // ATAN2 function calculates the arctangent (i.e. the inverse tangent) of a
  2356. // given set of x and y coordinates, and returns an angle, in radians, between
  2357. // -π/2 and +π/2. The syntax of the function is:
  2358. //
  2359. // ATAN2(x_num,y_num)
  2360. //
  2361. func (fn *formulaFuncs) ATAN2(argsList *list.List) formulaArg {
  2362. if argsList.Len() != 2 {
  2363. return newErrorFormulaArg(formulaErrorVALUE, "ATAN2 requires 2 numeric arguments")
  2364. }
  2365. x := argsList.Back().Value.(formulaArg).ToNumber()
  2366. if x.Type == ArgError {
  2367. return x
  2368. }
  2369. y := argsList.Front().Value.(formulaArg).ToNumber()
  2370. if y.Type == ArgError {
  2371. return y
  2372. }
  2373. return newNumberFormulaArg(math.Atan2(x.Number, y.Number))
  2374. }
  2375. // BASE function converts a number into a supplied base (radix), and returns a
  2376. // text representation of the calculated value. The syntax of the function is:
  2377. //
  2378. // BASE(number,radix,[min_length])
  2379. //
  2380. func (fn *formulaFuncs) BASE(argsList *list.List) formulaArg {
  2381. if argsList.Len() < 2 {
  2382. return newErrorFormulaArg(formulaErrorVALUE, "BASE requires at least 2 arguments")
  2383. }
  2384. if argsList.Len() > 3 {
  2385. return newErrorFormulaArg(formulaErrorVALUE, "BASE allows at most 3 arguments")
  2386. }
  2387. var minLength int
  2388. var err error
  2389. number := argsList.Front().Value.(formulaArg).ToNumber()
  2390. if number.Type == ArgError {
  2391. return number
  2392. }
  2393. radix := argsList.Front().Next().Value.(formulaArg).ToNumber()
  2394. if radix.Type == ArgError {
  2395. return radix
  2396. }
  2397. if int(radix.Number) < 2 || int(radix.Number) > 36 {
  2398. return newErrorFormulaArg(formulaErrorVALUE, "radix must be an integer >= 2 and <= 36")
  2399. }
  2400. if argsList.Len() > 2 {
  2401. if minLength, err = strconv.Atoi(argsList.Back().Value.(formulaArg).String); err != nil {
  2402. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  2403. }
  2404. }
  2405. result := strconv.FormatInt(int64(number.Number), int(radix.Number))
  2406. if len(result) < minLength {
  2407. result = strings.Repeat("0", minLength-len(result)) + result
  2408. }
  2409. return newStringFormulaArg(strings.ToUpper(result))
  2410. }
  2411. // CEILING function rounds a supplied number away from zero, to the nearest
  2412. // multiple of a given number. The syntax of the function is:
  2413. //
  2414. // CEILING(number,significance)
  2415. //
  2416. func (fn *formulaFuncs) CEILING(argsList *list.List) formulaArg {
  2417. if argsList.Len() == 0 {
  2418. return newErrorFormulaArg(formulaErrorVALUE, "CEILING requires at least 1 argument")
  2419. }
  2420. if argsList.Len() > 2 {
  2421. return newErrorFormulaArg(formulaErrorVALUE, "CEILING allows at most 2 arguments")
  2422. }
  2423. number, significance, res := 0.0, 1.0, 0.0
  2424. n := argsList.Front().Value.(formulaArg).ToNumber()
  2425. if n.Type == ArgError {
  2426. return n
  2427. }
  2428. number = n.Number
  2429. if number < 0 {
  2430. significance = -1
  2431. }
  2432. if argsList.Len() > 1 {
  2433. s := argsList.Back().Value.(formulaArg).ToNumber()
  2434. if s.Type == ArgError {
  2435. return s
  2436. }
  2437. significance = s.Number
  2438. }
  2439. if significance < 0 && number > 0 {
  2440. return newErrorFormulaArg(formulaErrorVALUE, "negative sig to CEILING invalid")
  2441. }
  2442. if argsList.Len() == 1 {
  2443. return newNumberFormulaArg(math.Ceil(number))
  2444. }
  2445. number, res = math.Modf(number / significance)
  2446. if res > 0 {
  2447. number++
  2448. }
  2449. return newNumberFormulaArg(number * significance)
  2450. }
  2451. // CEILINGdotMATH function rounds a supplied number up to a supplied multiple
  2452. // of significance. The syntax of the function is:
  2453. //
  2454. // CEILING.MATH(number,[significance],[mode])
  2455. //
  2456. func (fn *formulaFuncs) CEILINGdotMATH(argsList *list.List) formulaArg {
  2457. if argsList.Len() == 0 {
  2458. return newErrorFormulaArg(formulaErrorVALUE, "CEILING.MATH requires at least 1 argument")
  2459. }
  2460. if argsList.Len() > 3 {
  2461. return newErrorFormulaArg(formulaErrorVALUE, "CEILING.MATH allows at most 3 arguments")
  2462. }
  2463. number, significance, mode := 0.0, 1.0, 1.0
  2464. n := argsList.Front().Value.(formulaArg).ToNumber()
  2465. if n.Type == ArgError {
  2466. return n
  2467. }
  2468. number = n.Number
  2469. if number < 0 {
  2470. significance = -1
  2471. }
  2472. if argsList.Len() > 1 {
  2473. s := argsList.Front().Next().Value.(formulaArg).ToNumber()
  2474. if s.Type == ArgError {
  2475. return s
  2476. }
  2477. significance = s.Number
  2478. }
  2479. if argsList.Len() == 1 {
  2480. return newNumberFormulaArg(math.Ceil(number))
  2481. }
  2482. if argsList.Len() > 2 {
  2483. m := argsList.Back().Value.(formulaArg).ToNumber()
  2484. if m.Type == ArgError {
  2485. return m
  2486. }
  2487. mode = m.Number
  2488. }
  2489. val, res := math.Modf(number / significance)
  2490. if res != 0 {
  2491. if number > 0 {
  2492. val++
  2493. } else if mode < 0 {
  2494. val--
  2495. }
  2496. }
  2497. return newNumberFormulaArg(val * significance)
  2498. }
  2499. // CEILINGdotPRECISE function rounds a supplied number up (regardless of the
  2500. // number's sign), to the nearest multiple of a given number. The syntax of
  2501. // the function is:
  2502. //
  2503. // CEILING.PRECISE(number,[significance])
  2504. //
  2505. func (fn *formulaFuncs) CEILINGdotPRECISE(argsList *list.List) formulaArg {
  2506. if argsList.Len() == 0 {
  2507. return newErrorFormulaArg(formulaErrorVALUE, "CEILING.PRECISE requires at least 1 argument")
  2508. }
  2509. if argsList.Len() > 2 {
  2510. return newErrorFormulaArg(formulaErrorVALUE, "CEILING.PRECISE allows at most 2 arguments")
  2511. }
  2512. number, significance := 0.0, 1.0
  2513. n := argsList.Front().Value.(formulaArg).ToNumber()
  2514. if n.Type == ArgError {
  2515. return n
  2516. }
  2517. number = n.Number
  2518. if number < 0 {
  2519. significance = -1
  2520. }
  2521. if argsList.Len() == 1 {
  2522. return newNumberFormulaArg(math.Ceil(number))
  2523. }
  2524. if argsList.Len() > 1 {
  2525. s := argsList.Back().Value.(formulaArg).ToNumber()
  2526. if s.Type == ArgError {
  2527. return s
  2528. }
  2529. significance = s.Number
  2530. significance = math.Abs(significance)
  2531. if significance == 0 {
  2532. return newNumberFormulaArg(significance)
  2533. }
  2534. }
  2535. val, res := math.Modf(number / significance)
  2536. if res != 0 {
  2537. if number > 0 {
  2538. val++
  2539. }
  2540. }
  2541. return newNumberFormulaArg(val * significance)
  2542. }
  2543. // COMBIN function calculates the number of combinations (in any order) of a
  2544. // given number objects from a set. The syntax of the function is:
  2545. //
  2546. // COMBIN(number,number_chosen)
  2547. //
  2548. func (fn *formulaFuncs) COMBIN(argsList *list.List) formulaArg {
  2549. if argsList.Len() != 2 {
  2550. return newErrorFormulaArg(formulaErrorVALUE, "COMBIN requires 2 argument")
  2551. }
  2552. number, chosen, val := 0.0, 0.0, 1.0
  2553. n := argsList.Front().Value.(formulaArg).ToNumber()
  2554. if n.Type == ArgError {
  2555. return n
  2556. }
  2557. number = n.Number
  2558. c := argsList.Back().Value.(formulaArg).ToNumber()
  2559. if c.Type == ArgError {
  2560. return c
  2561. }
  2562. chosen = c.Number
  2563. number, chosen = math.Trunc(number), math.Trunc(chosen)
  2564. if chosen > number {
  2565. return newErrorFormulaArg(formulaErrorVALUE, "COMBIN requires number >= number_chosen")
  2566. }
  2567. if chosen == number || chosen == 0 {
  2568. return newNumberFormulaArg(1)
  2569. }
  2570. for c := float64(1); c <= chosen; c++ {
  2571. val *= (number + 1 - c) / c
  2572. }
  2573. return newNumberFormulaArg(math.Ceil(val))
  2574. }
  2575. // COMBINA function calculates the number of combinations, with repetitions,
  2576. // of a given number objects from a set. The syntax of the function is:
  2577. //
  2578. // COMBINA(number,number_chosen)
  2579. //
  2580. func (fn *formulaFuncs) COMBINA(argsList *list.List) formulaArg {
  2581. if argsList.Len() != 2 {
  2582. return newErrorFormulaArg(formulaErrorVALUE, "COMBINA requires 2 argument")
  2583. }
  2584. var number, chosen float64
  2585. n := argsList.Front().Value.(formulaArg).ToNumber()
  2586. if n.Type == ArgError {
  2587. return n
  2588. }
  2589. number = n.Number
  2590. c := argsList.Back().Value.(formulaArg).ToNumber()
  2591. if c.Type == ArgError {
  2592. return c
  2593. }
  2594. chosen = c.Number
  2595. number, chosen = math.Trunc(number), math.Trunc(chosen)
  2596. if number < chosen {
  2597. return newErrorFormulaArg(formulaErrorVALUE, "COMBINA requires number > number_chosen")
  2598. }
  2599. if number == 0 {
  2600. return newNumberFormulaArg(number)
  2601. }
  2602. args := list.New()
  2603. args.PushBack(formulaArg{
  2604. String: fmt.Sprintf("%g", number+chosen-1),
  2605. Type: ArgString,
  2606. })
  2607. args.PushBack(formulaArg{
  2608. String: fmt.Sprintf("%g", number-1),
  2609. Type: ArgString,
  2610. })
  2611. return fn.COMBIN(args)
  2612. }
  2613. // COS function calculates the cosine of a given angle. The syntax of the
  2614. // function is:
  2615. //
  2616. // COS(number)
  2617. //
  2618. func (fn *formulaFuncs) COS(argsList *list.List) formulaArg {
  2619. if argsList.Len() != 1 {
  2620. return newErrorFormulaArg(formulaErrorVALUE, "COS requires 1 numeric argument")
  2621. }
  2622. val := argsList.Front().Value.(formulaArg).ToNumber()
  2623. if val.Type == ArgError {
  2624. return val
  2625. }
  2626. return newNumberFormulaArg(math.Cos(val.Number))
  2627. }
  2628. // COSH function calculates the hyperbolic cosine (cosh) of a supplied number.
  2629. // The syntax of the function is:
  2630. //
  2631. // COSH(number)
  2632. //
  2633. func (fn *formulaFuncs) COSH(argsList *list.List) formulaArg {
  2634. if argsList.Len() != 1 {
  2635. return newErrorFormulaArg(formulaErrorVALUE, "COSH requires 1 numeric argument")
  2636. }
  2637. val := argsList.Front().Value.(formulaArg).ToNumber()
  2638. if val.Type == ArgError {
  2639. return val
  2640. }
  2641. return newNumberFormulaArg(math.Cosh(val.Number))
  2642. }
  2643. // COT function calculates the cotangent of a given angle. The syntax of the
  2644. // function is:
  2645. //
  2646. // COT(number)
  2647. //
  2648. func (fn *formulaFuncs) COT(argsList *list.List) formulaArg {
  2649. if argsList.Len() != 1 {
  2650. return newErrorFormulaArg(formulaErrorVALUE, "COT requires 1 numeric argument")
  2651. }
  2652. val := argsList.Front().Value.(formulaArg).ToNumber()
  2653. if val.Type == ArgError {
  2654. return val
  2655. }
  2656. if val.Number == 0 {
  2657. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  2658. }
  2659. return newNumberFormulaArg(1 / math.Tan(val.Number))
  2660. }
  2661. // COTH function calculates the hyperbolic cotangent (coth) of a supplied
  2662. // angle. The syntax of the function is:
  2663. //
  2664. // COTH(number)
  2665. //
  2666. func (fn *formulaFuncs) COTH(argsList *list.List) formulaArg {
  2667. if argsList.Len() != 1 {
  2668. return newErrorFormulaArg(formulaErrorVALUE, "COTH requires 1 numeric argument")
  2669. }
  2670. val := argsList.Front().Value.(formulaArg).ToNumber()
  2671. if val.Type == ArgError {
  2672. return val
  2673. }
  2674. if val.Number == 0 {
  2675. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  2676. }
  2677. return newNumberFormulaArg((math.Exp(val.Number) + math.Exp(-val.Number)) / (math.Exp(val.Number) - math.Exp(-val.Number)))
  2678. }
  2679. // CSC function calculates the cosecant of a given angle. The syntax of the
  2680. // function is:
  2681. //
  2682. // CSC(number)
  2683. //
  2684. func (fn *formulaFuncs) CSC(argsList *list.List) formulaArg {
  2685. if argsList.Len() != 1 {
  2686. return newErrorFormulaArg(formulaErrorVALUE, "CSC requires 1 numeric argument")
  2687. }
  2688. val := argsList.Front().Value.(formulaArg).ToNumber()
  2689. if val.Type == ArgError {
  2690. return val
  2691. }
  2692. if val.Number == 0 {
  2693. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  2694. }
  2695. return newNumberFormulaArg(1 / math.Sin(val.Number))
  2696. }
  2697. // CSCH function calculates the hyperbolic cosecant (csch) of a supplied
  2698. // angle. The syntax of the function is:
  2699. //
  2700. // CSCH(number)
  2701. //
  2702. func (fn *formulaFuncs) CSCH(argsList *list.List) formulaArg {
  2703. if argsList.Len() != 1 {
  2704. return newErrorFormulaArg(formulaErrorVALUE, "CSCH requires 1 numeric argument")
  2705. }
  2706. val := argsList.Front().Value.(formulaArg).ToNumber()
  2707. if val.Type == ArgError {
  2708. return val
  2709. }
  2710. if val.Number == 0 {
  2711. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  2712. }
  2713. return newNumberFormulaArg(1 / math.Sinh(val.Number))
  2714. }
  2715. // DECIMAL function converts a text representation of a number in a specified
  2716. // base, into a decimal value. The syntax of the function is:
  2717. //
  2718. // DECIMAL(text,radix)
  2719. //
  2720. func (fn *formulaFuncs) DECIMAL(argsList *list.List) formulaArg {
  2721. if argsList.Len() != 2 {
  2722. return newErrorFormulaArg(formulaErrorVALUE, "DECIMAL requires 2 numeric arguments")
  2723. }
  2724. var text = argsList.Front().Value.(formulaArg).String
  2725. var radix int
  2726. var err error
  2727. radix, err = strconv.Atoi(argsList.Back().Value.(formulaArg).String)
  2728. if err != nil {
  2729. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  2730. }
  2731. if len(text) > 2 && (strings.HasPrefix(text, "0x") || strings.HasPrefix(text, "0X")) {
  2732. text = text[2:]
  2733. }
  2734. val, err := strconv.ParseInt(text, radix, 64)
  2735. if err != nil {
  2736. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  2737. }
  2738. return newNumberFormulaArg(float64(val))
  2739. }
  2740. // DEGREES function converts radians into degrees. The syntax of the function
  2741. // is:
  2742. //
  2743. // DEGREES(angle)
  2744. //
  2745. func (fn *formulaFuncs) DEGREES(argsList *list.List) formulaArg {
  2746. if argsList.Len() != 1 {
  2747. return newErrorFormulaArg(formulaErrorVALUE, "DEGREES requires 1 numeric argument")
  2748. }
  2749. val := argsList.Front().Value.(formulaArg).ToNumber()
  2750. if val.Type == ArgError {
  2751. return val
  2752. }
  2753. if val.Number == 0 {
  2754. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  2755. }
  2756. return newNumberFormulaArg(180.0 / math.Pi * val.Number)
  2757. }
  2758. // EVEN function rounds a supplied number away from zero (i.e. rounds a
  2759. // positive number up and a negative number down), to the next even number.
  2760. // The syntax of the function is:
  2761. //
  2762. // EVEN(number)
  2763. //
  2764. func (fn *formulaFuncs) EVEN(argsList *list.List) formulaArg {
  2765. if argsList.Len() != 1 {
  2766. return newErrorFormulaArg(formulaErrorVALUE, "EVEN requires 1 numeric argument")
  2767. }
  2768. number := argsList.Front().Value.(formulaArg).ToNumber()
  2769. if number.Type == ArgError {
  2770. return number
  2771. }
  2772. sign := math.Signbit(number.Number)
  2773. m, frac := math.Modf(number.Number / 2)
  2774. val := m * 2
  2775. if frac != 0 {
  2776. if !sign {
  2777. val += 2
  2778. } else {
  2779. val -= 2
  2780. }
  2781. }
  2782. return newNumberFormulaArg(val)
  2783. }
  2784. // EXP function calculates the value of the mathematical constant e, raised to
  2785. // the power of a given number. The syntax of the function is:
  2786. //
  2787. // EXP(number)
  2788. //
  2789. func (fn *formulaFuncs) EXP(argsList *list.List) formulaArg {
  2790. if argsList.Len() != 1 {
  2791. return newErrorFormulaArg(formulaErrorVALUE, "EXP requires 1 numeric argument")
  2792. }
  2793. number := argsList.Front().Value.(formulaArg).ToNumber()
  2794. if number.Type == ArgError {
  2795. return number
  2796. }
  2797. return newStringFormulaArg(strings.ToUpper(fmt.Sprintf("%g", math.Exp(number.Number))))
  2798. }
  2799. // fact returns the factorial of a supplied number.
  2800. func fact(number float64) float64 {
  2801. val := float64(1)
  2802. for i := float64(2); i <= number; i++ {
  2803. val *= i
  2804. }
  2805. return val
  2806. }
  2807. // FACT function returns the factorial of a supplied number. The syntax of the
  2808. // function is:
  2809. //
  2810. // FACT(number)
  2811. //
  2812. func (fn *formulaFuncs) FACT(argsList *list.List) formulaArg {
  2813. if argsList.Len() != 1 {
  2814. return newErrorFormulaArg(formulaErrorVALUE, "FACT requires 1 numeric argument")
  2815. }
  2816. number := argsList.Front().Value.(formulaArg).ToNumber()
  2817. if number.Type == ArgError {
  2818. return number
  2819. }
  2820. if number.Number < 0 {
  2821. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  2822. }
  2823. return newNumberFormulaArg(fact(number.Number))
  2824. }
  2825. // FACTDOUBLE function returns the double factorial of a supplied number. The
  2826. // syntax of the function is:
  2827. //
  2828. // FACTDOUBLE(number)
  2829. //
  2830. func (fn *formulaFuncs) FACTDOUBLE(argsList *list.List) formulaArg {
  2831. if argsList.Len() != 1 {
  2832. return newErrorFormulaArg(formulaErrorVALUE, "FACTDOUBLE requires 1 numeric argument")
  2833. }
  2834. val := 1.0
  2835. number := argsList.Front().Value.(formulaArg).ToNumber()
  2836. if number.Type == ArgError {
  2837. return number
  2838. }
  2839. if number.Number < 0 {
  2840. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  2841. }
  2842. for i := math.Trunc(number.Number); i > 1; i -= 2 {
  2843. val *= i
  2844. }
  2845. return newStringFormulaArg(strings.ToUpper(fmt.Sprintf("%g", val)))
  2846. }
  2847. // FLOOR function rounds a supplied number towards zero to the nearest
  2848. // multiple of a specified significance. The syntax of the function is:
  2849. //
  2850. // FLOOR(number,significance)
  2851. //
  2852. func (fn *formulaFuncs) FLOOR(argsList *list.List) formulaArg {
  2853. if argsList.Len() != 2 {
  2854. return newErrorFormulaArg(formulaErrorVALUE, "FLOOR requires 2 numeric arguments")
  2855. }
  2856. number := argsList.Front().Value.(formulaArg).ToNumber()
  2857. if number.Type == ArgError {
  2858. return number
  2859. }
  2860. significance := argsList.Back().Value.(formulaArg).ToNumber()
  2861. if significance.Type == ArgError {
  2862. return significance
  2863. }
  2864. if significance.Number < 0 && number.Number >= 0 {
  2865. return newErrorFormulaArg(formulaErrorNUM, "invalid arguments to FLOOR")
  2866. }
  2867. val := number.Number
  2868. val, res := math.Modf(val / significance.Number)
  2869. if res != 0 {
  2870. if number.Number < 0 && res < 0 {
  2871. val--
  2872. }
  2873. }
  2874. return newStringFormulaArg(strings.ToUpper(fmt.Sprintf("%g", val*significance.Number)))
  2875. }
  2876. // FLOORdotMATH function rounds a supplied number down to a supplied multiple
  2877. // of significance. The syntax of the function is:
  2878. //
  2879. // FLOOR.MATH(number,[significance],[mode])
  2880. //
  2881. func (fn *formulaFuncs) FLOORdotMATH(argsList *list.List) formulaArg {
  2882. if argsList.Len() == 0 {
  2883. return newErrorFormulaArg(formulaErrorVALUE, "FLOOR.MATH requires at least 1 argument")
  2884. }
  2885. if argsList.Len() > 3 {
  2886. return newErrorFormulaArg(formulaErrorVALUE, "FLOOR.MATH allows at most 3 arguments")
  2887. }
  2888. significance, mode := 1.0, 1.0
  2889. number := argsList.Front().Value.(formulaArg).ToNumber()
  2890. if number.Type == ArgError {
  2891. return number
  2892. }
  2893. if number.Number < 0 {
  2894. significance = -1
  2895. }
  2896. if argsList.Len() > 1 {
  2897. s := argsList.Front().Next().Value.(formulaArg).ToNumber()
  2898. if s.Type == ArgError {
  2899. return s
  2900. }
  2901. significance = s.Number
  2902. }
  2903. if argsList.Len() == 1 {
  2904. return newNumberFormulaArg(math.Floor(number.Number))
  2905. }
  2906. if argsList.Len() > 2 {
  2907. m := argsList.Back().Value.(formulaArg).ToNumber()
  2908. if m.Type == ArgError {
  2909. return m
  2910. }
  2911. mode = m.Number
  2912. }
  2913. val, res := math.Modf(number.Number / significance)
  2914. if res != 0 && number.Number < 0 && mode > 0 {
  2915. val--
  2916. }
  2917. return newNumberFormulaArg(val * significance)
  2918. }
  2919. // FLOORdotPRECISE function rounds a supplied number down to a supplied
  2920. // multiple of significance. The syntax of the function is:
  2921. //
  2922. // FLOOR.PRECISE(number,[significance])
  2923. //
  2924. func (fn *formulaFuncs) FLOORdotPRECISE(argsList *list.List) formulaArg {
  2925. if argsList.Len() == 0 {
  2926. return newErrorFormulaArg(formulaErrorVALUE, "FLOOR.PRECISE requires at least 1 argument")
  2927. }
  2928. if argsList.Len() > 2 {
  2929. return newErrorFormulaArg(formulaErrorVALUE, "FLOOR.PRECISE allows at most 2 arguments")
  2930. }
  2931. var significance float64
  2932. number := argsList.Front().Value.(formulaArg).ToNumber()
  2933. if number.Type == ArgError {
  2934. return number
  2935. }
  2936. if number.Number < 0 {
  2937. significance = -1
  2938. }
  2939. if argsList.Len() == 1 {
  2940. return newNumberFormulaArg(math.Floor(number.Number))
  2941. }
  2942. if argsList.Len() > 1 {
  2943. s := argsList.Back().Value.(formulaArg).ToNumber()
  2944. if s.Type == ArgError {
  2945. return s
  2946. }
  2947. significance = s.Number
  2948. significance = math.Abs(significance)
  2949. if significance == 0 {
  2950. return newNumberFormulaArg(significance)
  2951. }
  2952. }
  2953. val, res := math.Modf(number.Number / significance)
  2954. if res != 0 {
  2955. if number.Number < 0 {
  2956. val--
  2957. }
  2958. }
  2959. return newNumberFormulaArg(val * significance)
  2960. }
  2961. // gcd returns the greatest common divisor of two supplied integers.
  2962. func gcd(x, y float64) float64 {
  2963. x, y = math.Trunc(x), math.Trunc(y)
  2964. if x == 0 {
  2965. return y
  2966. }
  2967. if y == 0 {
  2968. return x
  2969. }
  2970. for x != y {
  2971. if x > y {
  2972. x = x - y
  2973. } else {
  2974. y = y - x
  2975. }
  2976. }
  2977. return x
  2978. }
  2979. // GCD function returns the greatest common divisor of two or more supplied
  2980. // integers. The syntax of the function is:
  2981. //
  2982. // GCD(number1,[number2],...)
  2983. //
  2984. func (fn *formulaFuncs) GCD(argsList *list.List) formulaArg {
  2985. if argsList.Len() == 0 {
  2986. return newErrorFormulaArg(formulaErrorVALUE, "GCD requires at least 1 argument")
  2987. }
  2988. var (
  2989. val float64
  2990. nums = []float64{}
  2991. )
  2992. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  2993. token := arg.Value.(formulaArg)
  2994. switch token.Type {
  2995. case ArgString:
  2996. num := token.ToNumber()
  2997. if num.Type == ArgError {
  2998. return num
  2999. }
  3000. val = num.Number
  3001. case ArgNumber:
  3002. val = token.Number
  3003. }
  3004. nums = append(nums, val)
  3005. }
  3006. if nums[0] < 0 {
  3007. return newErrorFormulaArg(formulaErrorVALUE, "GCD only accepts positive arguments")
  3008. }
  3009. if len(nums) == 1 {
  3010. return newNumberFormulaArg(nums[0])
  3011. }
  3012. cd := nums[0]
  3013. for i := 1; i < len(nums); i++ {
  3014. if nums[i] < 0 {
  3015. return newErrorFormulaArg(formulaErrorVALUE, "GCD only accepts positive arguments")
  3016. }
  3017. cd = gcd(cd, nums[i])
  3018. }
  3019. return newNumberFormulaArg(cd)
  3020. }
  3021. // INT function truncates a supplied number down to the closest integer. The
  3022. // syntax of the function is:
  3023. //
  3024. // INT(number)
  3025. //
  3026. func (fn *formulaFuncs) INT(argsList *list.List) formulaArg {
  3027. if argsList.Len() != 1 {
  3028. return newErrorFormulaArg(formulaErrorVALUE, "INT requires 1 numeric argument")
  3029. }
  3030. number := argsList.Front().Value.(formulaArg).ToNumber()
  3031. if number.Type == ArgError {
  3032. return number
  3033. }
  3034. val, frac := math.Modf(number.Number)
  3035. if frac < 0 {
  3036. val--
  3037. }
  3038. return newNumberFormulaArg(val)
  3039. }
  3040. // ISOdotCEILING function rounds a supplied number up (regardless of the
  3041. // number's sign), to the nearest multiple of a supplied significance. The
  3042. // syntax of the function is:
  3043. //
  3044. // ISO.CEILING(number,[significance])
  3045. //
  3046. func (fn *formulaFuncs) ISOdotCEILING(argsList *list.List) formulaArg {
  3047. if argsList.Len() == 0 {
  3048. return newErrorFormulaArg(formulaErrorVALUE, "ISO.CEILING requires at least 1 argument")
  3049. }
  3050. if argsList.Len() > 2 {
  3051. return newErrorFormulaArg(formulaErrorVALUE, "ISO.CEILING allows at most 2 arguments")
  3052. }
  3053. var significance float64
  3054. number := argsList.Front().Value.(formulaArg).ToNumber()
  3055. if number.Type == ArgError {
  3056. return number
  3057. }
  3058. if number.Number < 0 {
  3059. significance = -1
  3060. }
  3061. if argsList.Len() == 1 {
  3062. return newNumberFormulaArg(math.Ceil(number.Number))
  3063. }
  3064. if argsList.Len() > 1 {
  3065. s := argsList.Back().Value.(formulaArg).ToNumber()
  3066. if s.Type == ArgError {
  3067. return s
  3068. }
  3069. significance = s.Number
  3070. significance = math.Abs(significance)
  3071. if significance == 0 {
  3072. return newNumberFormulaArg(significance)
  3073. }
  3074. }
  3075. val, res := math.Modf(number.Number / significance)
  3076. if res != 0 {
  3077. if number.Number > 0 {
  3078. val++
  3079. }
  3080. }
  3081. return newNumberFormulaArg(val * significance)
  3082. }
  3083. // lcm returns the least common multiple of two supplied integers.
  3084. func lcm(a, b float64) float64 {
  3085. a = math.Trunc(a)
  3086. b = math.Trunc(b)
  3087. if a == 0 && b == 0 {
  3088. return 0
  3089. }
  3090. return a * b / gcd(a, b)
  3091. }
  3092. // LCM function returns the least common multiple of two or more supplied
  3093. // integers. The syntax of the function is:
  3094. //
  3095. // LCM(number1,[number2],...)
  3096. //
  3097. func (fn *formulaFuncs) LCM(argsList *list.List) formulaArg {
  3098. if argsList.Len() == 0 {
  3099. return newErrorFormulaArg(formulaErrorVALUE, "LCM requires at least 1 argument")
  3100. }
  3101. var (
  3102. val float64
  3103. nums = []float64{}
  3104. err error
  3105. )
  3106. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  3107. token := arg.Value.(formulaArg)
  3108. switch token.Type {
  3109. case ArgString:
  3110. if token.String == "" {
  3111. continue
  3112. }
  3113. if val, err = strconv.ParseFloat(token.String, 64); err != nil {
  3114. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  3115. }
  3116. case ArgNumber:
  3117. val = token.Number
  3118. }
  3119. nums = append(nums, val)
  3120. }
  3121. if nums[0] < 0 {
  3122. return newErrorFormulaArg(formulaErrorVALUE, "LCM only accepts positive arguments")
  3123. }
  3124. if len(nums) == 1 {
  3125. return newNumberFormulaArg(nums[0])
  3126. }
  3127. cm := nums[0]
  3128. for i := 1; i < len(nums); i++ {
  3129. if nums[i] < 0 {
  3130. return newErrorFormulaArg(formulaErrorVALUE, "LCM only accepts positive arguments")
  3131. }
  3132. cm = lcm(cm, nums[i])
  3133. }
  3134. return newNumberFormulaArg(cm)
  3135. }
  3136. // LN function calculates the natural logarithm of a given number. The syntax
  3137. // of the function is:
  3138. //
  3139. // LN(number)
  3140. //
  3141. func (fn *formulaFuncs) LN(argsList *list.List) formulaArg {
  3142. if argsList.Len() != 1 {
  3143. return newErrorFormulaArg(formulaErrorVALUE, "LN requires 1 numeric argument")
  3144. }
  3145. number := argsList.Front().Value.(formulaArg).ToNumber()
  3146. if number.Type == ArgError {
  3147. return number
  3148. }
  3149. return newNumberFormulaArg(math.Log(number.Number))
  3150. }
  3151. // LOG function calculates the logarithm of a given number, to a supplied
  3152. // base. The syntax of the function is:
  3153. //
  3154. // LOG(number,[base])
  3155. //
  3156. func (fn *formulaFuncs) LOG(argsList *list.List) formulaArg {
  3157. if argsList.Len() == 0 {
  3158. return newErrorFormulaArg(formulaErrorVALUE, "LOG requires at least 1 argument")
  3159. }
  3160. if argsList.Len() > 2 {
  3161. return newErrorFormulaArg(formulaErrorVALUE, "LOG allows at most 2 arguments")
  3162. }
  3163. base := 10.0
  3164. number := argsList.Front().Value.(formulaArg).ToNumber()
  3165. if number.Type == ArgError {
  3166. return number
  3167. }
  3168. if argsList.Len() > 1 {
  3169. b := argsList.Back().Value.(formulaArg).ToNumber()
  3170. if b.Type == ArgError {
  3171. return b
  3172. }
  3173. base = b.Number
  3174. }
  3175. if number.Number == 0 {
  3176. return newErrorFormulaArg(formulaErrorNUM, formulaErrorDIV)
  3177. }
  3178. if base == 0 {
  3179. return newErrorFormulaArg(formulaErrorNUM, formulaErrorDIV)
  3180. }
  3181. if base == 1 {
  3182. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  3183. }
  3184. return newNumberFormulaArg(math.Log(number.Number) / math.Log(base))
  3185. }
  3186. // LOG10 function calculates the base 10 logarithm of a given number. The
  3187. // syntax of the function is:
  3188. //
  3189. // LOG10(number)
  3190. //
  3191. func (fn *formulaFuncs) LOG10(argsList *list.List) formulaArg {
  3192. if argsList.Len() != 1 {
  3193. return newErrorFormulaArg(formulaErrorVALUE, "LOG10 requires 1 numeric argument")
  3194. }
  3195. number := argsList.Front().Value.(formulaArg).ToNumber()
  3196. if number.Type == ArgError {
  3197. return number
  3198. }
  3199. return newNumberFormulaArg(math.Log10(number.Number))
  3200. }
  3201. // minor function implement a minor of a matrix A is the determinant of some
  3202. // smaller square matrix.
  3203. func minor(sqMtx [][]float64, idx int) [][]float64 {
  3204. ret := [][]float64{}
  3205. for i := range sqMtx {
  3206. if i == 0 {
  3207. continue
  3208. }
  3209. row := []float64{}
  3210. for j := range sqMtx {
  3211. if j == idx {
  3212. continue
  3213. }
  3214. row = append(row, sqMtx[i][j])
  3215. }
  3216. ret = append(ret, row)
  3217. }
  3218. return ret
  3219. }
  3220. // det determinant of the 2x2 matrix.
  3221. func det(sqMtx [][]float64) float64 {
  3222. if len(sqMtx) == 2 {
  3223. m00 := sqMtx[0][0]
  3224. m01 := sqMtx[0][1]
  3225. m10 := sqMtx[1][0]
  3226. m11 := sqMtx[1][1]
  3227. return m00*m11 - m10*m01
  3228. }
  3229. var res, sgn float64 = 0, 1
  3230. for j := range sqMtx {
  3231. res += sgn * sqMtx[0][j] * det(minor(sqMtx, j))
  3232. sgn *= -1
  3233. }
  3234. return res
  3235. }
  3236. // MDETERM calculates the determinant of a square matrix. The
  3237. // syntax of the function is:
  3238. //
  3239. // MDETERM(array)
  3240. //
  3241. func (fn *formulaFuncs) MDETERM(argsList *list.List) (result formulaArg) {
  3242. var (
  3243. num float64
  3244. numMtx = [][]float64{}
  3245. err error
  3246. strMtx [][]formulaArg
  3247. )
  3248. if argsList.Len() < 1 {
  3249. return newErrorFormulaArg(formulaErrorVALUE, "MDETERM requires at least 1 argument")
  3250. }
  3251. strMtx = argsList.Front().Value.(formulaArg).Matrix
  3252. var rows = len(strMtx)
  3253. for _, row := range argsList.Front().Value.(formulaArg).Matrix {
  3254. if len(row) != rows {
  3255. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  3256. }
  3257. numRow := []float64{}
  3258. for _, ele := range row {
  3259. if num, err = strconv.ParseFloat(ele.String, 64); err != nil {
  3260. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  3261. }
  3262. numRow = append(numRow, num)
  3263. }
  3264. numMtx = append(numMtx, numRow)
  3265. }
  3266. return newNumberFormulaArg(det(numMtx))
  3267. }
  3268. // MOD function returns the remainder of a division between two supplied
  3269. // numbers. The syntax of the function is:
  3270. //
  3271. // MOD(number,divisor)
  3272. //
  3273. func (fn *formulaFuncs) MOD(argsList *list.List) formulaArg {
  3274. if argsList.Len() != 2 {
  3275. return newErrorFormulaArg(formulaErrorVALUE, "MOD requires 2 numeric arguments")
  3276. }
  3277. number := argsList.Front().Value.(formulaArg).ToNumber()
  3278. if number.Type == ArgError {
  3279. return number
  3280. }
  3281. divisor := argsList.Back().Value.(formulaArg).ToNumber()
  3282. if divisor.Type == ArgError {
  3283. return divisor
  3284. }
  3285. if divisor.Number == 0 {
  3286. return newErrorFormulaArg(formulaErrorDIV, "MOD divide by zero")
  3287. }
  3288. trunc, rem := math.Modf(number.Number / divisor.Number)
  3289. if rem < 0 {
  3290. trunc--
  3291. }
  3292. return newNumberFormulaArg(number.Number - divisor.Number*trunc)
  3293. }
  3294. // MROUND function rounds a supplied number up or down to the nearest multiple
  3295. // of a given number. The syntax of the function is:
  3296. //
  3297. // MROUND(number,multiple)
  3298. //
  3299. func (fn *formulaFuncs) MROUND(argsList *list.List) formulaArg {
  3300. if argsList.Len() != 2 {
  3301. return newErrorFormulaArg(formulaErrorVALUE, "MROUND requires 2 numeric arguments")
  3302. }
  3303. n := argsList.Front().Value.(formulaArg).ToNumber()
  3304. if n.Type == ArgError {
  3305. return n
  3306. }
  3307. multiple := argsList.Back().Value.(formulaArg).ToNumber()
  3308. if multiple.Type == ArgError {
  3309. return multiple
  3310. }
  3311. if multiple.Number == 0 {
  3312. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  3313. }
  3314. if multiple.Number < 0 && n.Number > 0 ||
  3315. multiple.Number > 0 && n.Number < 0 {
  3316. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  3317. }
  3318. number, res := math.Modf(n.Number / multiple.Number)
  3319. if math.Trunc(res+0.5) > 0 {
  3320. number++
  3321. }
  3322. return newNumberFormulaArg(number * multiple.Number)
  3323. }
  3324. // MULTINOMIAL function calculates the ratio of the factorial of a sum of
  3325. // supplied values to the product of factorials of those values. The syntax of
  3326. // the function is:
  3327. //
  3328. // MULTINOMIAL(number1,[number2],...)
  3329. //
  3330. func (fn *formulaFuncs) MULTINOMIAL(argsList *list.List) formulaArg {
  3331. val, num, denom := 0.0, 0.0, 1.0
  3332. var err error
  3333. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  3334. token := arg.Value.(formulaArg)
  3335. switch token.Type {
  3336. case ArgString:
  3337. if token.String == "" {
  3338. continue
  3339. }
  3340. if val, err = strconv.ParseFloat(token.String, 64); err != nil {
  3341. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  3342. }
  3343. case ArgNumber:
  3344. val = token.Number
  3345. }
  3346. num += val
  3347. denom *= fact(val)
  3348. }
  3349. return newNumberFormulaArg(fact(num) / denom)
  3350. }
  3351. // MUNIT function returns the unit matrix for a specified dimension. The
  3352. // syntax of the function is:
  3353. //
  3354. // MUNIT(dimension)
  3355. //
  3356. func (fn *formulaFuncs) MUNIT(argsList *list.List) (result formulaArg) {
  3357. if argsList.Len() != 1 {
  3358. return newErrorFormulaArg(formulaErrorVALUE, "MUNIT requires 1 numeric argument")
  3359. }
  3360. dimension := argsList.Back().Value.(formulaArg).ToNumber()
  3361. if dimension.Type == ArgError || dimension.Number < 0 {
  3362. return newErrorFormulaArg(formulaErrorVALUE, dimension.Error)
  3363. }
  3364. matrix := make([][]formulaArg, 0, int(dimension.Number))
  3365. for i := 0; i < int(dimension.Number); i++ {
  3366. row := make([]formulaArg, int(dimension.Number))
  3367. for j := 0; j < int(dimension.Number); j++ {
  3368. if i == j {
  3369. row[j] = newNumberFormulaArg(1.0)
  3370. } else {
  3371. row[j] = newNumberFormulaArg(0.0)
  3372. }
  3373. }
  3374. matrix = append(matrix, row)
  3375. }
  3376. return newMatrixFormulaArg(matrix)
  3377. }
  3378. // ODD function ounds a supplied number away from zero (i.e. rounds a positive
  3379. // number up and a negative number down), to the next odd number. The syntax
  3380. // of the function is:
  3381. //
  3382. // ODD(number)
  3383. //
  3384. func (fn *formulaFuncs) ODD(argsList *list.List) formulaArg {
  3385. if argsList.Len() != 1 {
  3386. return newErrorFormulaArg(formulaErrorVALUE, "ODD requires 1 numeric argument")
  3387. }
  3388. number := argsList.Back().Value.(formulaArg).ToNumber()
  3389. if number.Type == ArgError {
  3390. return number
  3391. }
  3392. if number.Number == 0 {
  3393. return newNumberFormulaArg(1)
  3394. }
  3395. sign := math.Signbit(number.Number)
  3396. m, frac := math.Modf((number.Number - 1) / 2)
  3397. val := m*2 + 1
  3398. if frac != 0 {
  3399. if !sign {
  3400. val += 2
  3401. } else {
  3402. val -= 2
  3403. }
  3404. }
  3405. return newNumberFormulaArg(val)
  3406. }
  3407. // PI function returns the value of the mathematical constant π (pi), accurate
  3408. // to 15 digits (14 decimal places). The syntax of the function is:
  3409. //
  3410. // PI()
  3411. //
  3412. func (fn *formulaFuncs) PI(argsList *list.List) formulaArg {
  3413. if argsList.Len() != 0 {
  3414. return newErrorFormulaArg(formulaErrorVALUE, "PI accepts no arguments")
  3415. }
  3416. return newNumberFormulaArg(math.Pi)
  3417. }
  3418. // POWER function calculates a given number, raised to a supplied power.
  3419. // The syntax of the function is:
  3420. //
  3421. // POWER(number,power)
  3422. //
  3423. func (fn *formulaFuncs) POWER(argsList *list.List) formulaArg {
  3424. if argsList.Len() != 2 {
  3425. return newErrorFormulaArg(formulaErrorVALUE, "POWER requires 2 numeric arguments")
  3426. }
  3427. x := argsList.Front().Value.(formulaArg).ToNumber()
  3428. if x.Type == ArgError {
  3429. return x
  3430. }
  3431. y := argsList.Back().Value.(formulaArg).ToNumber()
  3432. if y.Type == ArgError {
  3433. return y
  3434. }
  3435. if x.Number == 0 && y.Number == 0 {
  3436. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  3437. }
  3438. if x.Number == 0 && y.Number < 0 {
  3439. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  3440. }
  3441. return newNumberFormulaArg(math.Pow(x.Number, y.Number))
  3442. }
  3443. // PRODUCT function returns the product (multiplication) of a supplied set of
  3444. // numerical values. The syntax of the function is:
  3445. //
  3446. // PRODUCT(number1,[number2],...)
  3447. //
  3448. func (fn *formulaFuncs) PRODUCT(argsList *list.List) formulaArg {
  3449. val, product := 0.0, 1.0
  3450. var err error
  3451. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  3452. token := arg.Value.(formulaArg)
  3453. switch token.Type {
  3454. case ArgUnknown:
  3455. continue
  3456. case ArgString:
  3457. if token.String == "" {
  3458. continue
  3459. }
  3460. if val, err = strconv.ParseFloat(token.String, 64); err != nil {
  3461. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  3462. }
  3463. product = product * val
  3464. case ArgNumber:
  3465. product = product * token.Number
  3466. case ArgMatrix:
  3467. for _, row := range token.Matrix {
  3468. for _, value := range row {
  3469. if value.String == "" {
  3470. continue
  3471. }
  3472. if val, err = strconv.ParseFloat(value.String, 64); err != nil {
  3473. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  3474. }
  3475. product = product * val
  3476. }
  3477. }
  3478. }
  3479. }
  3480. return newNumberFormulaArg(product)
  3481. }
  3482. // QUOTIENT function returns the integer portion of a division between two
  3483. // supplied numbers. The syntax of the function is:
  3484. //
  3485. // QUOTIENT(numerator,denominator)
  3486. //
  3487. func (fn *formulaFuncs) QUOTIENT(argsList *list.List) formulaArg {
  3488. if argsList.Len() != 2 {
  3489. return newErrorFormulaArg(formulaErrorVALUE, "QUOTIENT requires 2 numeric arguments")
  3490. }
  3491. x := argsList.Front().Value.(formulaArg).ToNumber()
  3492. if x.Type == ArgError {
  3493. return x
  3494. }
  3495. y := argsList.Back().Value.(formulaArg).ToNumber()
  3496. if y.Type == ArgError {
  3497. return y
  3498. }
  3499. if y.Number == 0 {
  3500. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  3501. }
  3502. return newNumberFormulaArg(math.Trunc(x.Number / y.Number))
  3503. }
  3504. // RADIANS function converts radians into degrees. The syntax of the function is:
  3505. //
  3506. // RADIANS(angle)
  3507. //
  3508. func (fn *formulaFuncs) RADIANS(argsList *list.List) formulaArg {
  3509. if argsList.Len() != 1 {
  3510. return newErrorFormulaArg(formulaErrorVALUE, "RADIANS requires 1 numeric argument")
  3511. }
  3512. angle := argsList.Front().Value.(formulaArg).ToNumber()
  3513. if angle.Type == ArgError {
  3514. return angle
  3515. }
  3516. return newNumberFormulaArg(math.Pi / 180.0 * angle.Number)
  3517. }
  3518. // RAND function generates a random real number between 0 and 1. The syntax of
  3519. // the function is:
  3520. //
  3521. // RAND()
  3522. //
  3523. func (fn *formulaFuncs) RAND(argsList *list.List) formulaArg {
  3524. if argsList.Len() != 0 {
  3525. return newErrorFormulaArg(formulaErrorVALUE, "RAND accepts no arguments")
  3526. }
  3527. return newNumberFormulaArg(rand.New(rand.NewSource(time.Now().UnixNano())).Float64())
  3528. }
  3529. // RANDBETWEEN function generates a random integer between two supplied
  3530. // integers. The syntax of the function is:
  3531. //
  3532. // RANDBETWEEN(bottom,top)
  3533. //
  3534. func (fn *formulaFuncs) RANDBETWEEN(argsList *list.List) formulaArg {
  3535. if argsList.Len() != 2 {
  3536. return newErrorFormulaArg(formulaErrorVALUE, "RANDBETWEEN requires 2 numeric arguments")
  3537. }
  3538. bottom := argsList.Front().Value.(formulaArg).ToNumber()
  3539. if bottom.Type == ArgError {
  3540. return bottom
  3541. }
  3542. top := argsList.Back().Value.(formulaArg).ToNumber()
  3543. if top.Type == ArgError {
  3544. return top
  3545. }
  3546. if top.Number < bottom.Number {
  3547. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  3548. }
  3549. num := rand.New(rand.NewSource(time.Now().UnixNano())).Int63n(int64(top.Number - bottom.Number + 1))
  3550. return newNumberFormulaArg(float64(num + int64(bottom.Number)))
  3551. }
  3552. // romanNumerals defined a numeral system that originated in ancient Rome and
  3553. // remained the usual way of writing numbers throughout Europe well into the
  3554. // Late Middle Ages.
  3555. type romanNumerals struct {
  3556. n float64
  3557. s string
  3558. }
  3559. var romanTable = [][]romanNumerals{
  3560. {
  3561. {1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"},
  3562. {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"},
  3563. },
  3564. {
  3565. {1000, "M"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {450, "LD"}, {400, "CD"},
  3566. {100, "C"}, {95, "VC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"},
  3567. {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"},
  3568. },
  3569. {
  3570. {1000, "M"}, {990, "XM"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {490, "XD"},
  3571. {450, "LD"}, {400, "CD"}, {100, "C"}, {99, "IC"}, {90, "XC"}, {50, "L"},
  3572. {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"},
  3573. },
  3574. {
  3575. {1000, "M"}, {995, "VM"}, {990, "XM"}, {950, "LM"}, {900, "CM"}, {500, "D"},
  3576. {495, "VD"}, {490, "XD"}, {450, "LD"}, {400, "CD"}, {100, "C"}, {99, "IC"},
  3577. {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"},
  3578. {5, "V"}, {4, "IV"}, {1, "I"},
  3579. },
  3580. {
  3581. {1000, "M"}, {999, "IM"}, {995, "VM"}, {990, "XM"}, {950, "LM"}, {900, "CM"},
  3582. {500, "D"}, {499, "ID"}, {495, "VD"}, {490, "XD"}, {450, "LD"}, {400, "CD"},
  3583. {100, "C"}, {99, "IC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"},
  3584. {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"},
  3585. },
  3586. }
  3587. // ROMAN function converts an arabic number to Roman. I.e. for a supplied
  3588. // integer, the function returns a text string depicting the roman numeral
  3589. // form of the number. The syntax of the function is:
  3590. //
  3591. // ROMAN(number,[form])
  3592. //
  3593. func (fn *formulaFuncs) ROMAN(argsList *list.List) formulaArg {
  3594. if argsList.Len() == 0 {
  3595. return newErrorFormulaArg(formulaErrorVALUE, "ROMAN requires at least 1 argument")
  3596. }
  3597. if argsList.Len() > 2 {
  3598. return newErrorFormulaArg(formulaErrorVALUE, "ROMAN allows at most 2 arguments")
  3599. }
  3600. var form int
  3601. number := argsList.Front().Value.(formulaArg).ToNumber()
  3602. if number.Type == ArgError {
  3603. return number
  3604. }
  3605. if argsList.Len() > 1 {
  3606. f := argsList.Back().Value.(formulaArg).ToNumber()
  3607. if f.Type == ArgError {
  3608. return f
  3609. }
  3610. form = int(f.Number)
  3611. if form < 0 {
  3612. form = 0
  3613. } else if form > 4 {
  3614. form = 4
  3615. }
  3616. }
  3617. decimalTable := romanTable[0]
  3618. switch form {
  3619. case 1:
  3620. decimalTable = romanTable[1]
  3621. case 2:
  3622. decimalTable = romanTable[2]
  3623. case 3:
  3624. decimalTable = romanTable[3]
  3625. case 4:
  3626. decimalTable = romanTable[4]
  3627. }
  3628. val := math.Trunc(number.Number)
  3629. buf := bytes.Buffer{}
  3630. for _, r := range decimalTable {
  3631. for val >= r.n {
  3632. buf.WriteString(r.s)
  3633. val -= r.n
  3634. }
  3635. }
  3636. return newStringFormulaArg(buf.String())
  3637. }
  3638. type roundMode byte
  3639. const (
  3640. closest roundMode = iota
  3641. down
  3642. up
  3643. )
  3644. // round rounds a supplied number up or down.
  3645. func (fn *formulaFuncs) round(number, digits float64, mode roundMode) float64 {
  3646. var significance float64
  3647. if digits > 0 {
  3648. significance = math.Pow(1/10.0, digits)
  3649. } else {
  3650. significance = math.Pow(10.0, -digits)
  3651. }
  3652. val, res := math.Modf(number / significance)
  3653. switch mode {
  3654. case closest:
  3655. const eps = 0.499999999
  3656. if res >= eps {
  3657. val++
  3658. } else if res <= -eps {
  3659. val--
  3660. }
  3661. case down:
  3662. case up:
  3663. if res > 0 {
  3664. val++
  3665. } else if res < 0 {
  3666. val--
  3667. }
  3668. }
  3669. return val * significance
  3670. }
  3671. // ROUND function rounds a supplied number up or down, to a specified number
  3672. // of decimal places. The syntax of the function is:
  3673. //
  3674. // ROUND(number,num_digits)
  3675. //
  3676. func (fn *formulaFuncs) ROUND(argsList *list.List) formulaArg {
  3677. if argsList.Len() != 2 {
  3678. return newErrorFormulaArg(formulaErrorVALUE, "ROUND requires 2 numeric arguments")
  3679. }
  3680. number := argsList.Front().Value.(formulaArg).ToNumber()
  3681. if number.Type == ArgError {
  3682. return number
  3683. }
  3684. digits := argsList.Back().Value.(formulaArg).ToNumber()
  3685. if digits.Type == ArgError {
  3686. return digits
  3687. }
  3688. return newNumberFormulaArg(fn.round(number.Number, digits.Number, closest))
  3689. }
  3690. // ROUNDDOWN function rounds a supplied number down towards zero, to a
  3691. // specified number of decimal places. The syntax of the function is:
  3692. //
  3693. // ROUNDDOWN(number,num_digits)
  3694. //
  3695. func (fn *formulaFuncs) ROUNDDOWN(argsList *list.List) formulaArg {
  3696. if argsList.Len() != 2 {
  3697. return newErrorFormulaArg(formulaErrorVALUE, "ROUNDDOWN requires 2 numeric arguments")
  3698. }
  3699. number := argsList.Front().Value.(formulaArg).ToNumber()
  3700. if number.Type == ArgError {
  3701. return number
  3702. }
  3703. digits := argsList.Back().Value.(formulaArg).ToNumber()
  3704. if digits.Type == ArgError {
  3705. return digits
  3706. }
  3707. return newNumberFormulaArg(fn.round(number.Number, digits.Number, down))
  3708. }
  3709. // ROUNDUP function rounds a supplied number up, away from zero, to a
  3710. // specified number of decimal places. The syntax of the function is:
  3711. //
  3712. // ROUNDUP(number,num_digits)
  3713. //
  3714. func (fn *formulaFuncs) ROUNDUP(argsList *list.List) formulaArg {
  3715. if argsList.Len() != 2 {
  3716. return newErrorFormulaArg(formulaErrorVALUE, "ROUNDUP requires 2 numeric arguments")
  3717. }
  3718. number := argsList.Front().Value.(formulaArg).ToNumber()
  3719. if number.Type == ArgError {
  3720. return number
  3721. }
  3722. digits := argsList.Back().Value.(formulaArg).ToNumber()
  3723. if digits.Type == ArgError {
  3724. return digits
  3725. }
  3726. return newNumberFormulaArg(fn.round(number.Number, digits.Number, up))
  3727. }
  3728. // SEC function calculates the secant of a given angle. The syntax of the
  3729. // function is:
  3730. //
  3731. // SEC(number)
  3732. //
  3733. func (fn *formulaFuncs) SEC(argsList *list.List) formulaArg {
  3734. if argsList.Len() != 1 {
  3735. return newErrorFormulaArg(formulaErrorVALUE, "SEC requires 1 numeric argument")
  3736. }
  3737. number := argsList.Front().Value.(formulaArg).ToNumber()
  3738. if number.Type == ArgError {
  3739. return number
  3740. }
  3741. return newNumberFormulaArg(math.Cos(number.Number))
  3742. }
  3743. // SECH function calculates the hyperbolic secant (sech) of a supplied angle.
  3744. // The syntax of the function is:
  3745. //
  3746. // SECH(number)
  3747. //
  3748. func (fn *formulaFuncs) SECH(argsList *list.List) formulaArg {
  3749. if argsList.Len() != 1 {
  3750. return newErrorFormulaArg(formulaErrorVALUE, "SECH requires 1 numeric argument")
  3751. }
  3752. number := argsList.Front().Value.(formulaArg).ToNumber()
  3753. if number.Type == ArgError {
  3754. return number
  3755. }
  3756. return newNumberFormulaArg(1 / math.Cosh(number.Number))
  3757. }
  3758. // SIGN function returns the arithmetic sign (+1, -1 or 0) of a supplied
  3759. // number. I.e. if the number is positive, the Sign function returns +1, if
  3760. // the number is negative, the function returns -1 and if the number is 0
  3761. // (zero), the function returns 0. The syntax of the function is:
  3762. //
  3763. // SIGN(number)
  3764. //
  3765. func (fn *formulaFuncs) SIGN(argsList *list.List) formulaArg {
  3766. if argsList.Len() != 1 {
  3767. return newErrorFormulaArg(formulaErrorVALUE, "SIGN requires 1 numeric argument")
  3768. }
  3769. val := argsList.Front().Value.(formulaArg).ToNumber()
  3770. if val.Type == ArgError {
  3771. return val
  3772. }
  3773. if val.Number < 0 {
  3774. return newNumberFormulaArg(-1)
  3775. }
  3776. if val.Number > 0 {
  3777. return newNumberFormulaArg(1)
  3778. }
  3779. return newNumberFormulaArg(0)
  3780. }
  3781. // SIN function calculates the sine of a given angle. The syntax of the
  3782. // function is:
  3783. //
  3784. // SIN(number)
  3785. //
  3786. func (fn *formulaFuncs) SIN(argsList *list.List) formulaArg {
  3787. if argsList.Len() != 1 {
  3788. return newErrorFormulaArg(formulaErrorVALUE, "SIN requires 1 numeric argument")
  3789. }
  3790. number := argsList.Front().Value.(formulaArg).ToNumber()
  3791. if number.Type == ArgError {
  3792. return number
  3793. }
  3794. return newNumberFormulaArg(math.Sin(number.Number))
  3795. }
  3796. // SINH function calculates the hyperbolic sine (sinh) of a supplied number.
  3797. // The syntax of the function is:
  3798. //
  3799. // SINH(number)
  3800. //
  3801. func (fn *formulaFuncs) SINH(argsList *list.List) formulaArg {
  3802. if argsList.Len() != 1 {
  3803. return newErrorFormulaArg(formulaErrorVALUE, "SINH requires 1 numeric argument")
  3804. }
  3805. number := argsList.Front().Value.(formulaArg).ToNumber()
  3806. if number.Type == ArgError {
  3807. return number
  3808. }
  3809. return newNumberFormulaArg(math.Sinh(number.Number))
  3810. }
  3811. // SQRT function calculates the positive square root of a supplied number. The
  3812. // syntax of the function is:
  3813. //
  3814. // SQRT(number)
  3815. //
  3816. func (fn *formulaFuncs) SQRT(argsList *list.List) formulaArg {
  3817. if argsList.Len() != 1 {
  3818. return newErrorFormulaArg(formulaErrorVALUE, "SQRT requires 1 numeric argument")
  3819. }
  3820. value := argsList.Front().Value.(formulaArg).ToNumber()
  3821. if value.Type == ArgError {
  3822. return value
  3823. }
  3824. if value.Number < 0 {
  3825. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  3826. }
  3827. return newNumberFormulaArg(math.Sqrt(value.Number))
  3828. }
  3829. // SQRTPI function returns the square root of a supplied number multiplied by
  3830. // the mathematical constant, π. The syntax of the function is:
  3831. //
  3832. // SQRTPI(number)
  3833. //
  3834. func (fn *formulaFuncs) SQRTPI(argsList *list.List) formulaArg {
  3835. if argsList.Len() != 1 {
  3836. return newErrorFormulaArg(formulaErrorVALUE, "SQRTPI requires 1 numeric argument")
  3837. }
  3838. number := argsList.Front().Value.(formulaArg).ToNumber()
  3839. if number.Type == ArgError {
  3840. return number
  3841. }
  3842. return newNumberFormulaArg(math.Sqrt(number.Number * math.Pi))
  3843. }
  3844. // STDEV function calculates the sample standard deviation of a supplied set
  3845. // of values. The syntax of the function is:
  3846. //
  3847. // STDEV(number1,[number2],...)
  3848. //
  3849. func (fn *formulaFuncs) STDEV(argsList *list.List) formulaArg {
  3850. if argsList.Len() < 1 {
  3851. return newErrorFormulaArg(formulaErrorVALUE, "STDEV requires at least 1 argument")
  3852. }
  3853. return fn.stdev(false, argsList)
  3854. }
  3855. // STDEVdotS function calculates the sample standard deviation of a supplied
  3856. // set of values. The syntax of the function is:
  3857. //
  3858. // STDEV.S(number1,[number2],...)
  3859. //
  3860. func (fn *formulaFuncs) STDEVdotS(argsList *list.List) formulaArg {
  3861. if argsList.Len() < 1 {
  3862. return newErrorFormulaArg(formulaErrorVALUE, "STDEV.S requires at least 1 argument")
  3863. }
  3864. return fn.stdev(false, argsList)
  3865. }
  3866. // STDEVA function estimates standard deviation based on a sample. The
  3867. // standard deviation is a measure of how widely values are dispersed from
  3868. // the average value (the mean). The syntax of the function is:
  3869. //
  3870. // STDEVA(number1,[number2],...)
  3871. //
  3872. func (fn *formulaFuncs) STDEVA(argsList *list.List) formulaArg {
  3873. if argsList.Len() < 1 {
  3874. return newErrorFormulaArg(formulaErrorVALUE, "STDEVA requires at least 1 argument")
  3875. }
  3876. return fn.stdev(true, argsList)
  3877. }
  3878. // stdev is an implementation of the formula function STDEV and STDEVA.
  3879. func (fn *formulaFuncs) stdev(stdeva bool, argsList *list.List) formulaArg {
  3880. pow := func(result, count float64, n, m formulaArg) (float64, float64) {
  3881. if result == -1 {
  3882. result = math.Pow((n.Number - m.Number), 2)
  3883. } else {
  3884. result += math.Pow((n.Number - m.Number), 2)
  3885. }
  3886. count++
  3887. return result, count
  3888. }
  3889. count, result := -1.0, -1.0
  3890. var mean formulaArg
  3891. if stdeva {
  3892. mean = fn.AVERAGEA(argsList)
  3893. } else {
  3894. mean = fn.AVERAGE(argsList)
  3895. }
  3896. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  3897. token := arg.Value.(formulaArg)
  3898. switch token.Type {
  3899. case ArgString, ArgNumber:
  3900. if !stdeva && (token.Value() == "TRUE" || token.Value() == "FALSE") {
  3901. continue
  3902. } else if stdeva && (token.Value() == "TRUE" || token.Value() == "FALSE") {
  3903. num := token.ToBool()
  3904. if num.Type == ArgNumber {
  3905. result, count = pow(result, count, num, mean)
  3906. continue
  3907. }
  3908. } else {
  3909. num := token.ToNumber()
  3910. if num.Type == ArgNumber {
  3911. result, count = pow(result, count, num, mean)
  3912. }
  3913. }
  3914. case ArgList, ArgMatrix:
  3915. for _, row := range token.ToList() {
  3916. if row.Type == ArgNumber || row.Type == ArgString {
  3917. if !stdeva && (row.Value() == "TRUE" || row.Value() == "FALSE") {
  3918. continue
  3919. } else if stdeva && (row.Value() == "TRUE" || row.Value() == "FALSE") {
  3920. num := row.ToBool()
  3921. if num.Type == ArgNumber {
  3922. result, count = pow(result, count, num, mean)
  3923. continue
  3924. }
  3925. } else {
  3926. num := row.ToNumber()
  3927. if num.Type == ArgNumber {
  3928. result, count = pow(result, count, num, mean)
  3929. }
  3930. }
  3931. }
  3932. }
  3933. }
  3934. }
  3935. if count > 0 && result >= 0 {
  3936. return newNumberFormulaArg(math.Sqrt(result / count))
  3937. }
  3938. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  3939. }
  3940. // POISSONdotDIST function calculates the Poisson Probability Mass Function or
  3941. // the Cumulative Poisson Probability Function for a supplied set of
  3942. // parameters. The syntax of the function is:
  3943. //
  3944. // POISSON.DIST(x,mean,cumulative)
  3945. //
  3946. func (fn *formulaFuncs) POISSONdotDIST(argsList *list.List) formulaArg {
  3947. if argsList.Len() != 3 {
  3948. return newErrorFormulaArg(formulaErrorVALUE, "POISSON.DIST requires 3 arguments")
  3949. }
  3950. return fn.POISSON(argsList)
  3951. }
  3952. // POISSON function calculates the Poisson Probability Mass Function or the
  3953. // Cumulative Poisson Probability Function for a supplied set of parameters.
  3954. // The syntax of the function is:
  3955. //
  3956. // POISSON(x,mean,cumulative)
  3957. //
  3958. func (fn *formulaFuncs) POISSON(argsList *list.List) formulaArg {
  3959. if argsList.Len() != 3 {
  3960. return newErrorFormulaArg(formulaErrorVALUE, "POISSON requires 3 arguments")
  3961. }
  3962. var x, mean, cumulative formulaArg
  3963. if x = argsList.Front().Value.(formulaArg).ToNumber(); x.Type != ArgNumber {
  3964. return x
  3965. }
  3966. if mean = argsList.Front().Next().Value.(formulaArg).ToNumber(); mean.Type != ArgNumber {
  3967. return mean
  3968. }
  3969. if cumulative = argsList.Back().Value.(formulaArg).ToBool(); cumulative.Type == ArgError {
  3970. return cumulative
  3971. }
  3972. if x.Number < 0 || mean.Number <= 0 {
  3973. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  3974. }
  3975. if cumulative.Number == 1 {
  3976. summer := 0.0
  3977. floor := math.Floor(x.Number)
  3978. for i := 0; i <= int(floor); i++ {
  3979. summer += math.Pow(mean.Number, float64(i)) / fact(float64(i))
  3980. }
  3981. return newNumberFormulaArg(math.Exp(0-mean.Number) * summer)
  3982. }
  3983. return newNumberFormulaArg(math.Exp(0-mean.Number) * math.Pow(mean.Number, x.Number) / fact(x.Number))
  3984. }
  3985. // SUM function adds together a supplied set of numbers and returns the sum of
  3986. // these values. The syntax of the function is:
  3987. //
  3988. // SUM(number1,[number2],...)
  3989. //
  3990. func (fn *formulaFuncs) SUM(argsList *list.List) formulaArg {
  3991. var sum float64
  3992. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  3993. token := arg.Value.(formulaArg)
  3994. switch token.Type {
  3995. case ArgUnknown:
  3996. continue
  3997. case ArgString:
  3998. if num := token.ToNumber(); num.Type == ArgNumber {
  3999. sum += num.Number
  4000. }
  4001. case ArgNumber:
  4002. sum += token.Number
  4003. case ArgMatrix:
  4004. for _, row := range token.Matrix {
  4005. for _, value := range row {
  4006. if num := value.ToNumber(); num.Type == ArgNumber {
  4007. sum += num.Number
  4008. }
  4009. }
  4010. }
  4011. }
  4012. }
  4013. return newNumberFormulaArg(sum)
  4014. }
  4015. // SUMIF function finds the values in a supplied array, that satisfy a given
  4016. // criteria, and returns the sum of the corresponding values in a second
  4017. // supplied array. The syntax of the function is:
  4018. //
  4019. // SUMIF(range,criteria,[sum_range])
  4020. //
  4021. func (fn *formulaFuncs) SUMIF(argsList *list.List) formulaArg {
  4022. if argsList.Len() < 2 {
  4023. return newErrorFormulaArg(formulaErrorVALUE, "SUMIF requires at least 2 argument")
  4024. }
  4025. var criteria = formulaCriteriaParser(argsList.Front().Next().Value.(formulaArg).String)
  4026. var rangeMtx = argsList.Front().Value.(formulaArg).Matrix
  4027. var sumRange [][]formulaArg
  4028. if argsList.Len() == 3 {
  4029. sumRange = argsList.Back().Value.(formulaArg).Matrix
  4030. }
  4031. var sum, val float64
  4032. var err error
  4033. for rowIdx, row := range rangeMtx {
  4034. for colIdx, col := range row {
  4035. var ok bool
  4036. fromVal := col.String
  4037. if col.String == "" {
  4038. continue
  4039. }
  4040. if ok, err = formulaCriteriaEval(fromVal, criteria); err != nil {
  4041. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  4042. }
  4043. if ok {
  4044. if argsList.Len() == 3 {
  4045. if len(sumRange) <= rowIdx || len(sumRange[rowIdx]) <= colIdx {
  4046. continue
  4047. }
  4048. fromVal = sumRange[rowIdx][colIdx].String
  4049. }
  4050. if val, err = strconv.ParseFloat(fromVal, 64); err != nil {
  4051. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  4052. }
  4053. sum += val
  4054. }
  4055. }
  4056. }
  4057. return newNumberFormulaArg(sum)
  4058. }
  4059. // SUMSQ function returns the sum of squares of a supplied set of values. The
  4060. // syntax of the function is:
  4061. //
  4062. // SUMSQ(number1,[number2],...)
  4063. //
  4064. func (fn *formulaFuncs) SUMSQ(argsList *list.List) formulaArg {
  4065. var val, sq float64
  4066. var err error
  4067. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  4068. token := arg.Value.(formulaArg)
  4069. switch token.Type {
  4070. case ArgString:
  4071. if token.String == "" {
  4072. continue
  4073. }
  4074. if val, err = strconv.ParseFloat(token.String, 64); err != nil {
  4075. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  4076. }
  4077. sq += val * val
  4078. case ArgNumber:
  4079. sq += token.Number
  4080. case ArgMatrix:
  4081. for _, row := range token.Matrix {
  4082. for _, value := range row {
  4083. if value.String == "" {
  4084. continue
  4085. }
  4086. if val, err = strconv.ParseFloat(value.String, 64); err != nil {
  4087. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  4088. }
  4089. sq += val * val
  4090. }
  4091. }
  4092. }
  4093. }
  4094. return newNumberFormulaArg(sq)
  4095. }
  4096. // TAN function calculates the tangent of a given angle. The syntax of the
  4097. // function is:
  4098. //
  4099. // TAN(number)
  4100. //
  4101. func (fn *formulaFuncs) TAN(argsList *list.List) formulaArg {
  4102. if argsList.Len() != 1 {
  4103. return newErrorFormulaArg(formulaErrorVALUE, "TAN requires 1 numeric argument")
  4104. }
  4105. number := argsList.Front().Value.(formulaArg).ToNumber()
  4106. if number.Type == ArgError {
  4107. return number
  4108. }
  4109. return newNumberFormulaArg(math.Tan(number.Number))
  4110. }
  4111. // TANH function calculates the hyperbolic tangent (tanh) of a supplied
  4112. // number. The syntax of the function is:
  4113. //
  4114. // TANH(number)
  4115. //
  4116. func (fn *formulaFuncs) TANH(argsList *list.List) formulaArg {
  4117. if argsList.Len() != 1 {
  4118. return newErrorFormulaArg(formulaErrorVALUE, "TANH requires 1 numeric argument")
  4119. }
  4120. number := argsList.Front().Value.(formulaArg).ToNumber()
  4121. if number.Type == ArgError {
  4122. return number
  4123. }
  4124. return newNumberFormulaArg(math.Tanh(number.Number))
  4125. }
  4126. // TRUNC function truncates a supplied number to a specified number of decimal
  4127. // places. The syntax of the function is:
  4128. //
  4129. // TRUNC(number,[number_digits])
  4130. //
  4131. func (fn *formulaFuncs) TRUNC(argsList *list.List) formulaArg {
  4132. if argsList.Len() == 0 {
  4133. return newErrorFormulaArg(formulaErrorVALUE, "TRUNC requires at least 1 argument")
  4134. }
  4135. var digits, adjust, rtrim float64
  4136. var err error
  4137. number := argsList.Front().Value.(formulaArg).ToNumber()
  4138. if number.Type == ArgError {
  4139. return number
  4140. }
  4141. if argsList.Len() > 1 {
  4142. d := argsList.Back().Value.(formulaArg).ToNumber()
  4143. if d.Type == ArgError {
  4144. return d
  4145. }
  4146. digits = d.Number
  4147. digits = math.Floor(digits)
  4148. }
  4149. adjust = math.Pow(10, digits)
  4150. x := int((math.Abs(number.Number) - math.Abs(float64(int(number.Number)))) * adjust)
  4151. if x != 0 {
  4152. if rtrim, err = strconv.ParseFloat(strings.TrimRight(strconv.Itoa(x), "0"), 64); err != nil {
  4153. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  4154. }
  4155. }
  4156. if (digits > 0) && (rtrim < adjust/10) {
  4157. return newNumberFormulaArg(number.Number)
  4158. }
  4159. return newNumberFormulaArg(float64(int(number.Number*adjust)) / adjust)
  4160. }
  4161. // Statistical Functions
  4162. // AVERAGE function returns the arithmetic mean of a list of supplied numbers.
  4163. // The syntax of the function is:
  4164. //
  4165. // AVERAGE(number1,[number2],...)
  4166. //
  4167. func (fn *formulaFuncs) AVERAGE(argsList *list.List) formulaArg {
  4168. args := []formulaArg{}
  4169. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  4170. args = append(args, arg.Value.(formulaArg))
  4171. }
  4172. count, sum := fn.countSum(false, args)
  4173. if count == 0 {
  4174. return newErrorFormulaArg(formulaErrorDIV, "AVERAGE divide by zero")
  4175. }
  4176. return newNumberFormulaArg(sum / count)
  4177. }
  4178. // AVERAGEA function returns the arithmetic mean of a list of supplied numbers
  4179. // with text cell and zero values. The syntax of the function is:
  4180. //
  4181. // AVERAGEA(number1,[number2],...)
  4182. //
  4183. func (fn *formulaFuncs) AVERAGEA(argsList *list.List) formulaArg {
  4184. args := []formulaArg{}
  4185. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  4186. args = append(args, arg.Value.(formulaArg))
  4187. }
  4188. count, sum := fn.countSum(true, args)
  4189. if count == 0 {
  4190. return newErrorFormulaArg(formulaErrorDIV, "AVERAGEA divide by zero")
  4191. }
  4192. return newNumberFormulaArg(sum / count)
  4193. }
  4194. // countSum get count and sum for a formula arguments array.
  4195. func (fn *formulaFuncs) countSum(countText bool, args []formulaArg) (count, sum float64) {
  4196. for _, arg := range args {
  4197. switch arg.Type {
  4198. case ArgNumber:
  4199. if countText || !arg.Boolean {
  4200. sum += arg.Number
  4201. count++
  4202. }
  4203. case ArgString:
  4204. if !countText && (arg.Value() == "TRUE" || arg.Value() == "FALSE") {
  4205. continue
  4206. } else if countText && (arg.Value() == "TRUE" || arg.Value() == "FALSE") {
  4207. num := arg.ToBool()
  4208. if num.Type == ArgNumber {
  4209. count++
  4210. sum += num.Number
  4211. continue
  4212. }
  4213. }
  4214. num := arg.ToNumber()
  4215. if countText && num.Type == ArgError && arg.String != "" {
  4216. count++
  4217. }
  4218. if num.Type == ArgNumber {
  4219. sum += num.Number
  4220. count++
  4221. }
  4222. case ArgList, ArgMatrix:
  4223. cnt, summary := fn.countSum(countText, arg.ToList())
  4224. sum += summary
  4225. count += cnt
  4226. }
  4227. }
  4228. return
  4229. }
  4230. // COUNT function returns the count of numeric values in a supplied set of
  4231. // cells or values. This count includes both numbers and dates. The syntax of
  4232. // the function is:
  4233. //
  4234. // COUNT(value1,[value2],...)
  4235. //
  4236. func (fn *formulaFuncs) COUNT(argsList *list.List) formulaArg {
  4237. var count int
  4238. for token := argsList.Front(); token != nil; token = token.Next() {
  4239. arg := token.Value.(formulaArg)
  4240. switch arg.Type {
  4241. case ArgString:
  4242. if arg.ToNumber().Type != ArgError {
  4243. count++
  4244. }
  4245. case ArgNumber:
  4246. count++
  4247. case ArgMatrix:
  4248. for _, row := range arg.Matrix {
  4249. for _, value := range row {
  4250. if value.ToNumber().Type != ArgError {
  4251. count++
  4252. }
  4253. }
  4254. }
  4255. }
  4256. }
  4257. return newNumberFormulaArg(float64(count))
  4258. }
  4259. // COUNTA function returns the number of non-blanks within a supplied set of
  4260. // cells or values. The syntax of the function is:
  4261. //
  4262. // COUNTA(value1,[value2],...)
  4263. //
  4264. func (fn *formulaFuncs) COUNTA(argsList *list.List) formulaArg {
  4265. var count int
  4266. for token := argsList.Front(); token != nil; token = token.Next() {
  4267. arg := token.Value.(formulaArg)
  4268. switch arg.Type {
  4269. case ArgString:
  4270. if arg.String != "" {
  4271. count++
  4272. }
  4273. case ArgNumber:
  4274. count++
  4275. case ArgMatrix:
  4276. for _, row := range arg.ToList() {
  4277. switch row.Type {
  4278. case ArgString:
  4279. if row.String != "" {
  4280. count++
  4281. }
  4282. case ArgNumber:
  4283. count++
  4284. }
  4285. }
  4286. }
  4287. }
  4288. return newNumberFormulaArg(float64(count))
  4289. }
  4290. // COUNTBLANK function returns the number of blank cells in a supplied range.
  4291. // The syntax of the function is:
  4292. //
  4293. // COUNTBLANK(range)
  4294. //
  4295. func (fn *formulaFuncs) COUNTBLANK(argsList *list.List) formulaArg {
  4296. if argsList.Len() != 1 {
  4297. return newErrorFormulaArg(formulaErrorVALUE, "COUNTBLANK requires 1 argument")
  4298. }
  4299. var count int
  4300. token := argsList.Front().Value.(formulaArg)
  4301. switch token.Type {
  4302. case ArgString:
  4303. if token.String == "" {
  4304. count++
  4305. }
  4306. case ArgList, ArgMatrix:
  4307. for _, row := range token.ToList() {
  4308. switch row.Type {
  4309. case ArgString:
  4310. if row.String == "" {
  4311. count++
  4312. }
  4313. case ArgEmpty:
  4314. count++
  4315. }
  4316. }
  4317. case ArgEmpty:
  4318. count++
  4319. }
  4320. return newNumberFormulaArg(float64(count))
  4321. }
  4322. // FISHER function calculates the Fisher Transformation for a supplied value.
  4323. // The syntax of the function is:
  4324. //
  4325. // FISHER(x)
  4326. //
  4327. func (fn *formulaFuncs) FISHER(argsList *list.List) formulaArg {
  4328. if argsList.Len() != 1 {
  4329. return newErrorFormulaArg(formulaErrorVALUE, "FISHER requires 1 numeric argument")
  4330. }
  4331. token := argsList.Front().Value.(formulaArg)
  4332. switch token.Type {
  4333. case ArgString:
  4334. arg := token.ToNumber()
  4335. if arg.Type == ArgNumber {
  4336. if arg.Number <= -1 || arg.Number >= 1 {
  4337. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4338. }
  4339. return newNumberFormulaArg(0.5 * math.Log((1+arg.Number)/(1-arg.Number)))
  4340. }
  4341. case ArgNumber:
  4342. if token.Number <= -1 || token.Number >= 1 {
  4343. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4344. }
  4345. return newNumberFormulaArg(0.5 * math.Log((1+token.Number)/(1-token.Number)))
  4346. }
  4347. return newErrorFormulaArg(formulaErrorVALUE, "FISHER requires 1 numeric argument")
  4348. }
  4349. // FISHERINV function calculates the inverse of the Fisher Transformation and
  4350. // returns a value between -1 and +1. The syntax of the function is:
  4351. //
  4352. // FISHERINV(y)
  4353. //
  4354. func (fn *formulaFuncs) FISHERINV(argsList *list.List) formulaArg {
  4355. if argsList.Len() != 1 {
  4356. return newErrorFormulaArg(formulaErrorVALUE, "FISHERINV requires 1 numeric argument")
  4357. }
  4358. token := argsList.Front().Value.(formulaArg)
  4359. switch token.Type {
  4360. case ArgString:
  4361. arg := token.ToNumber()
  4362. if arg.Type == ArgNumber {
  4363. return newNumberFormulaArg((math.Exp(2*arg.Number) - 1) / (math.Exp(2*arg.Number) + 1))
  4364. }
  4365. case ArgNumber:
  4366. return newNumberFormulaArg((math.Exp(2*token.Number) - 1) / (math.Exp(2*token.Number) + 1))
  4367. }
  4368. return newErrorFormulaArg(formulaErrorVALUE, "FISHERINV requires 1 numeric argument")
  4369. }
  4370. // GAMMA function returns the value of the Gamma Function, Γ(n), for a
  4371. // specified number, n. The syntax of the function is:
  4372. //
  4373. // GAMMA(number)
  4374. //
  4375. func (fn *formulaFuncs) GAMMA(argsList *list.List) formulaArg {
  4376. if argsList.Len() != 1 {
  4377. return newErrorFormulaArg(formulaErrorVALUE, "GAMMA requires 1 numeric argument")
  4378. }
  4379. token := argsList.Front().Value.(formulaArg)
  4380. switch token.Type {
  4381. case ArgString:
  4382. arg := token.ToNumber()
  4383. if arg.Type == ArgNumber {
  4384. if arg.Number <= 0 {
  4385. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4386. }
  4387. return newNumberFormulaArg(math.Gamma(arg.Number))
  4388. }
  4389. case ArgNumber:
  4390. if token.Number <= 0 {
  4391. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4392. }
  4393. return newNumberFormulaArg(math.Gamma(token.Number))
  4394. }
  4395. return newErrorFormulaArg(formulaErrorVALUE, "GAMMA requires 1 numeric argument")
  4396. }
  4397. // GAMMALN function returns the natural logarithm of the Gamma Function, Γ
  4398. // (n). The syntax of the function is:
  4399. //
  4400. // GAMMALN(x)
  4401. //
  4402. func (fn *formulaFuncs) GAMMALN(argsList *list.List) formulaArg {
  4403. if argsList.Len() != 1 {
  4404. return newErrorFormulaArg(formulaErrorVALUE, "GAMMALN requires 1 numeric argument")
  4405. }
  4406. token := argsList.Front().Value.(formulaArg)
  4407. switch token.Type {
  4408. case ArgString:
  4409. arg := token.ToNumber()
  4410. if arg.Type == ArgNumber {
  4411. if arg.Number <= 0 {
  4412. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4413. }
  4414. return newNumberFormulaArg(math.Log(math.Gamma(arg.Number)))
  4415. }
  4416. case ArgNumber:
  4417. if token.Number <= 0 {
  4418. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4419. }
  4420. return newNumberFormulaArg(math.Log(math.Gamma(token.Number)))
  4421. }
  4422. return newErrorFormulaArg(formulaErrorVALUE, "GAMMALN requires 1 numeric argument")
  4423. }
  4424. // HARMEAN function calculates the harmonic mean of a supplied set of values.
  4425. // The syntax of the function is:
  4426. //
  4427. // HARMEAN(number1,[number2],...)
  4428. //
  4429. func (fn *formulaFuncs) HARMEAN(argsList *list.List) formulaArg {
  4430. if argsList.Len() < 1 {
  4431. return newErrorFormulaArg(formulaErrorVALUE, "HARMEAN requires at least 1 argument")
  4432. }
  4433. if min := fn.MIN(argsList); min.Number < 0 {
  4434. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4435. }
  4436. number, val, cnt := 0.0, 0.0, 0.0
  4437. for token := argsList.Front(); token != nil; token = token.Next() {
  4438. arg := token.Value.(formulaArg)
  4439. switch arg.Type {
  4440. case ArgString:
  4441. num := arg.ToNumber()
  4442. if num.Type != ArgNumber {
  4443. continue
  4444. }
  4445. number = num.Number
  4446. case ArgNumber:
  4447. number = arg.Number
  4448. }
  4449. if number <= 0 {
  4450. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4451. }
  4452. val += (1 / number)
  4453. cnt++
  4454. }
  4455. return newNumberFormulaArg(1 / (val / cnt))
  4456. }
  4457. // KURT function calculates the kurtosis of a supplied set of values. The
  4458. // syntax of the function is:
  4459. //
  4460. // KURT(number1,[number2],...)
  4461. //
  4462. func (fn *formulaFuncs) KURT(argsList *list.List) formulaArg {
  4463. if argsList.Len() < 1 {
  4464. return newErrorFormulaArg(formulaErrorVALUE, "KURT requires at least 1 argument")
  4465. }
  4466. mean, stdev := fn.AVERAGE(argsList), fn.STDEV(argsList)
  4467. if stdev.Number > 0 {
  4468. count, summer := 0.0, 0.0
  4469. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  4470. token := arg.Value.(formulaArg)
  4471. switch token.Type {
  4472. case ArgString, ArgNumber:
  4473. num := token.ToNumber()
  4474. if num.Type == ArgError {
  4475. continue
  4476. }
  4477. summer += math.Pow((num.Number-mean.Number)/stdev.Number, 4)
  4478. count++
  4479. case ArgList, ArgMatrix:
  4480. for _, row := range token.ToList() {
  4481. if row.Type == ArgNumber || row.Type == ArgString {
  4482. num := row.ToNumber()
  4483. if num.Type == ArgError {
  4484. continue
  4485. }
  4486. summer += math.Pow((num.Number-mean.Number)/stdev.Number, 4)
  4487. count++
  4488. }
  4489. }
  4490. }
  4491. }
  4492. if count > 3 {
  4493. return newNumberFormulaArg(summer*(count*(count+1)/((count-1)*(count-2)*(count-3))) - (3 * math.Pow(count-1, 2) / ((count - 2) * (count - 3))))
  4494. }
  4495. }
  4496. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  4497. }
  4498. // NORMdotDIST function calculates the Normal Probability Density Function or
  4499. // the Cumulative Normal Distribution. Function for a supplied set of
  4500. // parameters. The syntax of the function is:
  4501. //
  4502. // NORM.DIST(x,mean,standard_dev,cumulative)
  4503. //
  4504. func (fn *formulaFuncs) NORMdotDIST(argsList *list.List) formulaArg {
  4505. if argsList.Len() != 4 {
  4506. return newErrorFormulaArg(formulaErrorVALUE, "NORM.DIST requires 4 arguments")
  4507. }
  4508. return fn.NORMDIST(argsList)
  4509. }
  4510. // NORMDIST function calculates the Normal Probability Density Function or the
  4511. // Cumulative Normal Distribution. Function for a supplied set of parameters.
  4512. // The syntax of the function is:
  4513. //
  4514. // NORMDIST(x,mean,standard_dev,cumulative)
  4515. //
  4516. func (fn *formulaFuncs) NORMDIST(argsList *list.List) formulaArg {
  4517. if argsList.Len() != 4 {
  4518. return newErrorFormulaArg(formulaErrorVALUE, "NORMDIST requires 4 arguments")
  4519. }
  4520. var x, mean, stdDev, cumulative formulaArg
  4521. if x = argsList.Front().Value.(formulaArg).ToNumber(); x.Type != ArgNumber {
  4522. return x
  4523. }
  4524. if mean = argsList.Front().Next().Value.(formulaArg).ToNumber(); mean.Type != ArgNumber {
  4525. return mean
  4526. }
  4527. if stdDev = argsList.Back().Prev().Value.(formulaArg).ToNumber(); stdDev.Type != ArgNumber {
  4528. return stdDev
  4529. }
  4530. if cumulative = argsList.Back().Value.(formulaArg).ToBool(); cumulative.Type == ArgError {
  4531. return cumulative
  4532. }
  4533. if stdDev.Number < 0 {
  4534. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4535. }
  4536. if cumulative.Number == 1 {
  4537. return newNumberFormulaArg(0.5 * (1 + math.Erf((x.Number-mean.Number)/(stdDev.Number*math.Sqrt(2)))))
  4538. }
  4539. return newNumberFormulaArg((1 / (math.Sqrt(2*math.Pi) * stdDev.Number)) * math.Exp(0-(math.Pow(x.Number-mean.Number, 2)/(2*(stdDev.Number*stdDev.Number)))))
  4540. }
  4541. // NORMdotINV function calculates the inverse of the Cumulative Normal
  4542. // Distribution Function for a supplied value of x, and a supplied
  4543. // distribution mean & standard deviation. The syntax of the function is:
  4544. //
  4545. // NORM.INV(probability,mean,standard_dev)
  4546. //
  4547. func (fn *formulaFuncs) NORMdotINV(argsList *list.List) formulaArg {
  4548. if argsList.Len() != 3 {
  4549. return newErrorFormulaArg(formulaErrorVALUE, "NORM.INV requires 3 arguments")
  4550. }
  4551. return fn.NORMINV(argsList)
  4552. }
  4553. // NORMINV function calculates the inverse of the Cumulative Normal
  4554. // Distribution Function for a supplied value of x, and a supplied
  4555. // distribution mean & standard deviation. The syntax of the function is:
  4556. //
  4557. // NORMINV(probability,mean,standard_dev)
  4558. //
  4559. func (fn *formulaFuncs) NORMINV(argsList *list.List) formulaArg {
  4560. if argsList.Len() != 3 {
  4561. return newErrorFormulaArg(formulaErrorVALUE, "NORMINV requires 3 arguments")
  4562. }
  4563. var prob, mean, stdDev formulaArg
  4564. if prob = argsList.Front().Value.(formulaArg).ToNumber(); prob.Type != ArgNumber {
  4565. return prob
  4566. }
  4567. if mean = argsList.Front().Next().Value.(formulaArg).ToNumber(); mean.Type != ArgNumber {
  4568. return mean
  4569. }
  4570. if stdDev = argsList.Back().Value.(formulaArg).ToNumber(); stdDev.Type != ArgNumber {
  4571. return stdDev
  4572. }
  4573. if prob.Number < 0 || prob.Number > 1 {
  4574. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4575. }
  4576. if stdDev.Number < 0 {
  4577. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4578. }
  4579. inv, err := norminv(prob.Number)
  4580. if err != nil {
  4581. return newErrorFormulaArg(err.Error(), err.Error())
  4582. }
  4583. return newNumberFormulaArg(inv*stdDev.Number + mean.Number)
  4584. }
  4585. // NORMdotSdotDIST function calculates the Standard Normal Cumulative
  4586. // Distribution Function for a supplied value. The syntax of the function
  4587. // is:
  4588. //
  4589. // NORM.S.DIST(z)
  4590. //
  4591. func (fn *formulaFuncs) NORMdotSdotDIST(argsList *list.List) formulaArg {
  4592. if argsList.Len() != 2 {
  4593. return newErrorFormulaArg(formulaErrorVALUE, "NORM.S.DIST requires 2 numeric arguments")
  4594. }
  4595. args := list.New().Init()
  4596. args.PushBack(argsList.Front().Value.(formulaArg))
  4597. args.PushBack(formulaArg{Type: ArgNumber, Number: 0})
  4598. args.PushBack(formulaArg{Type: ArgNumber, Number: 1})
  4599. args.PushBack(argsList.Back().Value.(formulaArg))
  4600. return fn.NORMDIST(args)
  4601. }
  4602. // NORMSDIST function calculates the Standard Normal Cumulative Distribution
  4603. // Function for a supplied value. The syntax of the function is:
  4604. //
  4605. // NORMSDIST(z)
  4606. //
  4607. func (fn *formulaFuncs) NORMSDIST(argsList *list.List) formulaArg {
  4608. if argsList.Len() != 1 {
  4609. return newErrorFormulaArg(formulaErrorVALUE, "NORMSDIST requires 1 numeric argument")
  4610. }
  4611. args := list.New().Init()
  4612. args.PushBack(argsList.Front().Value.(formulaArg))
  4613. args.PushBack(formulaArg{Type: ArgNumber, Number: 0})
  4614. args.PushBack(formulaArg{Type: ArgNumber, Number: 1})
  4615. args.PushBack(formulaArg{Type: ArgNumber, Number: 1, Boolean: true})
  4616. return fn.NORMDIST(args)
  4617. }
  4618. // NORMSINV function calculates the inverse of the Standard Normal Cumulative
  4619. // Distribution Function for a supplied probability value. The syntax of the
  4620. // function is:
  4621. //
  4622. // NORMSINV(probability)
  4623. //
  4624. func (fn *formulaFuncs) NORMSINV(argsList *list.List) formulaArg {
  4625. if argsList.Len() != 1 {
  4626. return newErrorFormulaArg(formulaErrorVALUE, "NORMSINV requires 1 numeric argument")
  4627. }
  4628. args := list.New().Init()
  4629. args.PushBack(argsList.Front().Value.(formulaArg))
  4630. args.PushBack(formulaArg{Type: ArgNumber, Number: 0})
  4631. args.PushBack(formulaArg{Type: ArgNumber, Number: 1})
  4632. return fn.NORMINV(args)
  4633. }
  4634. // NORMdotSdotINV function calculates the inverse of the Standard Normal
  4635. // Cumulative Distribution Function for a supplied probability value. The
  4636. // syntax of the function is:
  4637. //
  4638. // NORM.S.INV(probability)
  4639. //
  4640. func (fn *formulaFuncs) NORMdotSdotINV(argsList *list.List) formulaArg {
  4641. if argsList.Len() != 1 {
  4642. return newErrorFormulaArg(formulaErrorVALUE, "NORM.S.INV requires 1 numeric argument")
  4643. }
  4644. args := list.New().Init()
  4645. args.PushBack(argsList.Front().Value.(formulaArg))
  4646. args.PushBack(formulaArg{Type: ArgNumber, Number: 0})
  4647. args.PushBack(formulaArg{Type: ArgNumber, Number: 1})
  4648. return fn.NORMINV(args)
  4649. }
  4650. // norminv returns the inverse of the normal cumulative distribution for the
  4651. // specified value.
  4652. func norminv(p float64) (float64, error) {
  4653. a := map[int]float64{
  4654. 1: -3.969683028665376e+01, 2: 2.209460984245205e+02, 3: -2.759285104469687e+02,
  4655. 4: 1.383577518672690e+02, 5: -3.066479806614716e+01, 6: 2.506628277459239e+00,
  4656. }
  4657. b := map[int]float64{
  4658. 1: -5.447609879822406e+01, 2: 1.615858368580409e+02, 3: -1.556989798598866e+02,
  4659. 4: 6.680131188771972e+01, 5: -1.328068155288572e+01,
  4660. }
  4661. c := map[int]float64{
  4662. 1: -7.784894002430293e-03, 2: -3.223964580411365e-01, 3: -2.400758277161838e+00,
  4663. 4: -2.549732539343734e+00, 5: 4.374664141464968e+00, 6: 2.938163982698783e+00,
  4664. }
  4665. d := map[int]float64{
  4666. 1: 7.784695709041462e-03, 2: 3.224671290700398e-01, 3: 2.445134137142996e+00,
  4667. 4: 3.754408661907416e+00,
  4668. }
  4669. pLow := 0.02425 // Use lower region approx. below this
  4670. pHigh := 1 - pLow // Use upper region approx. above this
  4671. if 0 < p && p < pLow {
  4672. // Rational approximation for lower region.
  4673. q := math.Sqrt(-2 * math.Log(p))
  4674. return (((((c[1]*q+c[2])*q+c[3])*q+c[4])*q+c[5])*q + c[6]) /
  4675. ((((d[1]*q+d[2])*q+d[3])*q+d[4])*q + 1), nil
  4676. } else if pLow <= p && p <= pHigh {
  4677. // Rational approximation for central region.
  4678. q := p - 0.5
  4679. r := q * q
  4680. return (((((a[1]*r+a[2])*r+a[3])*r+a[4])*r+a[5])*r + a[6]) * q /
  4681. (((((b[1]*r+b[2])*r+b[3])*r+b[4])*r+b[5])*r + 1), nil
  4682. } else if pHigh < p && p < 1 {
  4683. // Rational approximation for upper region.
  4684. q := math.Sqrt(-2 * math.Log(1-p))
  4685. return -(((((c[1]*q+c[2])*q+c[3])*q+c[4])*q+c[5])*q + c[6]) /
  4686. ((((d[1]*q+d[2])*q+d[3])*q+d[4])*q + 1), nil
  4687. }
  4688. return 0, errors.New(formulaErrorNUM)
  4689. }
  4690. // kth is an implementation of the formula function LARGE and SMALL.
  4691. func (fn *formulaFuncs) kth(name string, argsList *list.List) formulaArg {
  4692. if argsList.Len() != 2 {
  4693. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires 2 arguments", name))
  4694. }
  4695. array := argsList.Front().Value.(formulaArg).ToList()
  4696. kArg := argsList.Back().Value.(formulaArg).ToNumber()
  4697. if kArg.Type != ArgNumber {
  4698. return kArg
  4699. }
  4700. k := int(kArg.Number)
  4701. if k < 1 {
  4702. return newErrorFormulaArg(formulaErrorNUM, "k should be > 0")
  4703. }
  4704. data := []float64{}
  4705. for _, arg := range array {
  4706. if numArg := arg.ToNumber(); numArg.Type == ArgNumber {
  4707. data = append(data, numArg.Number)
  4708. }
  4709. }
  4710. if len(data) < k {
  4711. return newErrorFormulaArg(formulaErrorNUM, "k should be <= length of array")
  4712. }
  4713. sort.Float64s(data)
  4714. if name == "LARGE" {
  4715. return newNumberFormulaArg(data[len(data)-k])
  4716. }
  4717. return newNumberFormulaArg(data[k-1])
  4718. }
  4719. // LARGE function returns the k'th largest value from an array of numeric
  4720. // values. The syntax of the function is:
  4721. //
  4722. // LARGE(array,k)
  4723. //
  4724. func (fn *formulaFuncs) LARGE(argsList *list.List) formulaArg {
  4725. return fn.kth("LARGE", argsList)
  4726. }
  4727. // MAX function returns the largest value from a supplied set of numeric
  4728. // values. The syntax of the function is:
  4729. //
  4730. // MAX(number1,[number2],...)
  4731. //
  4732. func (fn *formulaFuncs) MAX(argsList *list.List) formulaArg {
  4733. if argsList.Len() == 0 {
  4734. return newErrorFormulaArg(formulaErrorVALUE, "MAX requires at least 1 argument")
  4735. }
  4736. return fn.max(false, argsList)
  4737. }
  4738. // MAXA function returns the largest value from a supplied set of numeric
  4739. // values, while counting text and the logical value FALSE as the value 0 and
  4740. // counting the logical value TRUE as the value 1. The syntax of the function
  4741. // is:
  4742. //
  4743. // MAXA(number1,[number2],...)
  4744. //
  4745. func (fn *formulaFuncs) MAXA(argsList *list.List) formulaArg {
  4746. if argsList.Len() == 0 {
  4747. return newErrorFormulaArg(formulaErrorVALUE, "MAXA requires at least 1 argument")
  4748. }
  4749. return fn.max(true, argsList)
  4750. }
  4751. // max is an implementation of the formula function MAX and MAXA.
  4752. func (fn *formulaFuncs) max(maxa bool, argsList *list.List) formulaArg {
  4753. max := -math.MaxFloat64
  4754. for token := argsList.Front(); token != nil; token = token.Next() {
  4755. arg := token.Value.(formulaArg)
  4756. switch arg.Type {
  4757. case ArgString:
  4758. if !maxa && (arg.Value() == "TRUE" || arg.Value() == "FALSE") {
  4759. continue
  4760. } else {
  4761. num := arg.ToBool()
  4762. if num.Type == ArgNumber && num.Number > max {
  4763. max = num.Number
  4764. continue
  4765. }
  4766. }
  4767. num := arg.ToNumber()
  4768. if num.Type != ArgError && num.Number > max {
  4769. max = num.Number
  4770. }
  4771. case ArgNumber:
  4772. if arg.Number > max {
  4773. max = arg.Number
  4774. }
  4775. case ArgList, ArgMatrix:
  4776. for _, row := range arg.ToList() {
  4777. switch row.Type {
  4778. case ArgString:
  4779. if !maxa && (row.Value() == "TRUE" || row.Value() == "FALSE") {
  4780. continue
  4781. } else {
  4782. num := row.ToBool()
  4783. if num.Type == ArgNumber && num.Number > max {
  4784. max = num.Number
  4785. continue
  4786. }
  4787. }
  4788. num := row.ToNumber()
  4789. if num.Type != ArgError && num.Number > max {
  4790. max = num.Number
  4791. }
  4792. case ArgNumber:
  4793. if row.Number > max {
  4794. max = row.Number
  4795. }
  4796. }
  4797. }
  4798. case ArgError:
  4799. return arg
  4800. }
  4801. }
  4802. if max == -math.MaxFloat64 {
  4803. max = 0
  4804. }
  4805. return newNumberFormulaArg(max)
  4806. }
  4807. // MEDIAN function returns the statistical median (the middle value) of a list
  4808. // of supplied numbers. The syntax of the function is:
  4809. //
  4810. // MEDIAN(number1,[number2],...)
  4811. //
  4812. func (fn *formulaFuncs) MEDIAN(argsList *list.List) formulaArg {
  4813. if argsList.Len() == 0 {
  4814. return newErrorFormulaArg(formulaErrorVALUE, "MEDIAN requires at least 1 argument")
  4815. }
  4816. var values = []float64{}
  4817. var median, digits float64
  4818. var err error
  4819. for token := argsList.Front(); token != nil; token = token.Next() {
  4820. arg := token.Value.(formulaArg)
  4821. switch arg.Type {
  4822. case ArgString:
  4823. num := arg.ToNumber()
  4824. if num.Type == ArgError {
  4825. return newErrorFormulaArg(formulaErrorVALUE, num.Error)
  4826. }
  4827. values = append(values, num.Number)
  4828. case ArgNumber:
  4829. values = append(values, arg.Number)
  4830. case ArgMatrix:
  4831. for _, row := range arg.Matrix {
  4832. for _, value := range row {
  4833. if value.String == "" {
  4834. continue
  4835. }
  4836. if digits, err = strconv.ParseFloat(value.String, 64); err != nil {
  4837. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  4838. }
  4839. values = append(values, digits)
  4840. }
  4841. }
  4842. }
  4843. }
  4844. sort.Float64s(values)
  4845. if len(values)%2 == 0 {
  4846. median = (values[len(values)/2-1] + values[len(values)/2]) / 2
  4847. } else {
  4848. median = values[len(values)/2]
  4849. }
  4850. return newNumberFormulaArg(median)
  4851. }
  4852. // MIN function returns the smallest value from a supplied set of numeric
  4853. // values. The syntax of the function is:
  4854. //
  4855. // MIN(number1,[number2],...)
  4856. //
  4857. func (fn *formulaFuncs) MIN(argsList *list.List) formulaArg {
  4858. if argsList.Len() == 0 {
  4859. return newErrorFormulaArg(formulaErrorVALUE, "MIN requires at least 1 argument")
  4860. }
  4861. return fn.min(false, argsList)
  4862. }
  4863. // MINA function returns the smallest value from a supplied set of numeric
  4864. // values, while counting text and the logical value FALSE as the value 0 and
  4865. // counting the logical value TRUE as the value 1. The syntax of the function
  4866. // is:
  4867. //
  4868. // MINA(number1,[number2],...)
  4869. //
  4870. func (fn *formulaFuncs) MINA(argsList *list.List) formulaArg {
  4871. if argsList.Len() == 0 {
  4872. return newErrorFormulaArg(formulaErrorVALUE, "MINA requires at least 1 argument")
  4873. }
  4874. return fn.min(true, argsList)
  4875. }
  4876. // min is an implementation of the formula function MIN and MINA.
  4877. func (fn *formulaFuncs) min(mina bool, argsList *list.List) formulaArg {
  4878. min := math.MaxFloat64
  4879. for token := argsList.Front(); token != nil; token = token.Next() {
  4880. arg := token.Value.(formulaArg)
  4881. switch arg.Type {
  4882. case ArgString:
  4883. if !mina && (arg.Value() == "TRUE" || arg.Value() == "FALSE") {
  4884. continue
  4885. } else {
  4886. num := arg.ToBool()
  4887. if num.Type == ArgNumber && num.Number < min {
  4888. min = num.Number
  4889. continue
  4890. }
  4891. }
  4892. num := arg.ToNumber()
  4893. if num.Type != ArgError && num.Number < min {
  4894. min = num.Number
  4895. }
  4896. case ArgNumber:
  4897. if arg.Number < min {
  4898. min = arg.Number
  4899. }
  4900. case ArgList, ArgMatrix:
  4901. for _, row := range arg.ToList() {
  4902. switch row.Type {
  4903. case ArgString:
  4904. if !mina && (row.Value() == "TRUE" || row.Value() == "FALSE") {
  4905. continue
  4906. } else {
  4907. num := row.ToBool()
  4908. if num.Type == ArgNumber && num.Number < min {
  4909. min = num.Number
  4910. continue
  4911. }
  4912. }
  4913. num := row.ToNumber()
  4914. if num.Type != ArgError && num.Number < min {
  4915. min = num.Number
  4916. }
  4917. case ArgNumber:
  4918. if row.Number < min {
  4919. min = row.Number
  4920. }
  4921. }
  4922. }
  4923. case ArgError:
  4924. return arg
  4925. }
  4926. }
  4927. if min == math.MaxFloat64 {
  4928. min = 0
  4929. }
  4930. return newNumberFormulaArg(min)
  4931. }
  4932. // PERCENTILEdotINC function returns the k'th percentile (i.e. the value below
  4933. // which k% of the data values fall) for a supplied range of values and a
  4934. // supplied k. The syntax of the function is:
  4935. //
  4936. // PERCENTILE.INC(array,k)
  4937. //
  4938. func (fn *formulaFuncs) PERCENTILEdotINC(argsList *list.List) formulaArg {
  4939. if argsList.Len() != 2 {
  4940. return newErrorFormulaArg(formulaErrorVALUE, "PERCENTILE.INC requires 2 arguments")
  4941. }
  4942. return fn.PERCENTILE(argsList)
  4943. }
  4944. // PERCENTILE function returns the k'th percentile (i.e. the value below which
  4945. // k% of the data values fall) for a supplied range of values and a supplied
  4946. // k. The syntax of the function is:
  4947. //
  4948. // PERCENTILE(array,k)
  4949. //
  4950. func (fn *formulaFuncs) PERCENTILE(argsList *list.List) formulaArg {
  4951. if argsList.Len() != 2 {
  4952. return newErrorFormulaArg(formulaErrorVALUE, "PERCENTILE requires 2 arguments")
  4953. }
  4954. array := argsList.Front().Value.(formulaArg).ToList()
  4955. k := argsList.Back().Value.(formulaArg).ToNumber()
  4956. if k.Type != ArgNumber {
  4957. return k
  4958. }
  4959. if k.Number < 0 || k.Number > 1 {
  4960. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4961. }
  4962. numbers := []float64{}
  4963. for _, arg := range array {
  4964. if arg.Type == ArgError {
  4965. return arg
  4966. }
  4967. num := arg.ToNumber()
  4968. if num.Type == ArgNumber {
  4969. numbers = append(numbers, num.Number)
  4970. }
  4971. }
  4972. cnt := len(numbers)
  4973. sort.Float64s(numbers)
  4974. idx := k.Number * (float64(cnt) - 1)
  4975. base := math.Floor(idx)
  4976. if idx == base {
  4977. return newNumberFormulaArg(numbers[int(idx)])
  4978. }
  4979. next := base + 1
  4980. proportion := idx - base
  4981. return newNumberFormulaArg(numbers[int(base)] + ((numbers[int(next)] - numbers[int(base)]) * proportion))
  4982. }
  4983. // PERMUT function calculates the number of permutations of a specified number
  4984. // of objects from a set of objects. The syntax of the function is:
  4985. //
  4986. // PERMUT(number,number_chosen)
  4987. //
  4988. func (fn *formulaFuncs) PERMUT(argsList *list.List) formulaArg {
  4989. if argsList.Len() != 2 {
  4990. return newErrorFormulaArg(formulaErrorVALUE, "PERMUT requires 2 numeric arguments")
  4991. }
  4992. number := argsList.Front().Value.(formulaArg).ToNumber()
  4993. chosen := argsList.Back().Value.(formulaArg).ToNumber()
  4994. if number.Type != ArgNumber {
  4995. return number
  4996. }
  4997. if chosen.Type != ArgNumber {
  4998. return chosen
  4999. }
  5000. if number.Number < chosen.Number {
  5001. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  5002. }
  5003. return newNumberFormulaArg(math.Round(fact(number.Number) / fact(number.Number-chosen.Number)))
  5004. }
  5005. // PERMUTATIONA function calculates the number of permutations, with
  5006. // repetitions, of a specified number of objects from a set. The syntax of
  5007. // the function is:
  5008. //
  5009. // PERMUTATIONA(number,number_chosen)
  5010. //
  5011. func (fn *formulaFuncs) PERMUTATIONA(argsList *list.List) formulaArg {
  5012. if argsList.Len() < 1 {
  5013. return newErrorFormulaArg(formulaErrorVALUE, "PERMUTATIONA requires 2 numeric arguments")
  5014. }
  5015. number := argsList.Front().Value.(formulaArg).ToNumber()
  5016. chosen := argsList.Back().Value.(formulaArg).ToNumber()
  5017. if number.Type != ArgNumber {
  5018. return number
  5019. }
  5020. if chosen.Type != ArgNumber {
  5021. return chosen
  5022. }
  5023. num, numChosen := math.Floor(number.Number), math.Floor(chosen.Number)
  5024. if num < 0 || numChosen < 0 {
  5025. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  5026. }
  5027. return newNumberFormulaArg(math.Pow(num, numChosen))
  5028. }
  5029. // QUARTILE function returns a requested quartile of a supplied range of
  5030. // values. The syntax of the function is:
  5031. //
  5032. // QUARTILE(array,quart)
  5033. //
  5034. func (fn *formulaFuncs) QUARTILE(argsList *list.List) formulaArg {
  5035. if argsList.Len() != 2 {
  5036. return newErrorFormulaArg(formulaErrorVALUE, "QUARTILE requires 2 arguments")
  5037. }
  5038. quart := argsList.Back().Value.(formulaArg).ToNumber()
  5039. if quart.Type != ArgNumber {
  5040. return quart
  5041. }
  5042. if quart.Number < 0 || quart.Number > 4 {
  5043. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  5044. }
  5045. args := list.New().Init()
  5046. args.PushBack(argsList.Front().Value.(formulaArg))
  5047. args.PushBack(newNumberFormulaArg(quart.Number / 4))
  5048. return fn.PERCENTILE(args)
  5049. }
  5050. // QUARTILEdotINC function returns a requested quartile of a supplied range of
  5051. // values. The syntax of the function is:
  5052. //
  5053. // QUARTILE.INC(array,quart)
  5054. //
  5055. func (fn *formulaFuncs) QUARTILEdotINC(argsList *list.List) formulaArg {
  5056. if argsList.Len() != 2 {
  5057. return newErrorFormulaArg(formulaErrorVALUE, "QUARTILE.INC requires 2 arguments")
  5058. }
  5059. return fn.QUARTILE(argsList)
  5060. }
  5061. // SKEW function calculates the skewness of the distribution of a supplied set
  5062. // of values. The syntax of the function is:
  5063. //
  5064. // SKEW(number1,[number2],...)
  5065. //
  5066. func (fn *formulaFuncs) SKEW(argsList *list.List) formulaArg {
  5067. if argsList.Len() < 1 {
  5068. return newErrorFormulaArg(formulaErrorVALUE, "SKEW requires at least 1 argument")
  5069. }
  5070. mean, stdDev, count, summer := fn.AVERAGE(argsList), fn.STDEV(argsList), 0.0, 0.0
  5071. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  5072. token := arg.Value.(formulaArg)
  5073. switch token.Type {
  5074. case ArgNumber, ArgString:
  5075. num := token.ToNumber()
  5076. if num.Type == ArgError {
  5077. return num
  5078. }
  5079. summer += math.Pow((num.Number-mean.Number)/stdDev.Number, 3)
  5080. count++
  5081. case ArgList, ArgMatrix:
  5082. for _, row := range token.ToList() {
  5083. numArg := row.ToNumber()
  5084. if numArg.Type != ArgNumber {
  5085. continue
  5086. }
  5087. summer += math.Pow((numArg.Number-mean.Number)/stdDev.Number, 3)
  5088. count++
  5089. }
  5090. }
  5091. }
  5092. if count > 2 {
  5093. return newNumberFormulaArg(summer * (count / ((count - 1) * (count - 2))))
  5094. }
  5095. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  5096. }
  5097. // SMALL function returns the k'th smallest value from an array of numeric
  5098. // values. The syntax of the function is:
  5099. //
  5100. // SMALL(array,k)
  5101. //
  5102. func (fn *formulaFuncs) SMALL(argsList *list.List) formulaArg {
  5103. return fn.kth("SMALL", argsList)
  5104. }
  5105. // VARP function returns the Variance of a given set of values. The syntax of
  5106. // the function is:
  5107. //
  5108. // VARP(number1,[number2],...)
  5109. //
  5110. func (fn *formulaFuncs) VARP(argsList *list.List) formulaArg {
  5111. if argsList.Len() < 1 {
  5112. return newErrorFormulaArg(formulaErrorVALUE, "VARP requires at least 1 argument")
  5113. }
  5114. summerA, summerB, count := 0.0, 0.0, 0.0
  5115. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  5116. for _, token := range arg.Value.(formulaArg).ToList() {
  5117. if num := token.ToNumber(); num.Type == ArgNumber {
  5118. summerA += (num.Number * num.Number)
  5119. summerB += num.Number
  5120. count++
  5121. }
  5122. }
  5123. }
  5124. if count > 0 {
  5125. summerA *= count
  5126. summerB *= summerB
  5127. return newNumberFormulaArg((summerA - summerB) / (count * count))
  5128. }
  5129. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  5130. }
  5131. // VARdotP function returns the Variance of a given set of values. The syntax
  5132. // of the function is:
  5133. //
  5134. // VAR.P(number1,[number2],...)
  5135. //
  5136. func (fn *formulaFuncs) VARdotP(argsList *list.List) formulaArg {
  5137. if argsList.Len() < 1 {
  5138. return newErrorFormulaArg(formulaErrorVALUE, "VAR.P requires at least 1 argument")
  5139. }
  5140. return fn.VARP(argsList)
  5141. }
  5142. // Information Functions
  5143. // ISBLANK function tests if a specified cell is blank (empty) and if so,
  5144. // returns TRUE; Otherwise the function returns FALSE. The syntax of the
  5145. // function is:
  5146. //
  5147. // ISBLANK(value)
  5148. //
  5149. func (fn *formulaFuncs) ISBLANK(argsList *list.List) formulaArg {
  5150. if argsList.Len() != 1 {
  5151. return newErrorFormulaArg(formulaErrorVALUE, "ISBLANK requires 1 argument")
  5152. }
  5153. token := argsList.Front().Value.(formulaArg)
  5154. result := "FALSE"
  5155. switch token.Type {
  5156. case ArgUnknown:
  5157. result = "TRUE"
  5158. case ArgString:
  5159. if token.String == "" {
  5160. result = "TRUE"
  5161. }
  5162. }
  5163. return newStringFormulaArg(result)
  5164. }
  5165. // ISERR function tests if an initial supplied expression (or value) returns
  5166. // any Excel Error, except the #N/A error. If so, the function returns the
  5167. // logical value TRUE; If the supplied value is not an error or is the #N/A
  5168. // error, the ISERR function returns FALSE. The syntax of the function is:
  5169. //
  5170. // ISERR(value)
  5171. //
  5172. func (fn *formulaFuncs) ISERR(argsList *list.List) formulaArg {
  5173. if argsList.Len() != 1 {
  5174. return newErrorFormulaArg(formulaErrorVALUE, "ISERR requires 1 argument")
  5175. }
  5176. token := argsList.Front().Value.(formulaArg)
  5177. result := "FALSE"
  5178. if token.Type == ArgError {
  5179. for _, errType := range []string{
  5180. formulaErrorDIV, formulaErrorNAME, formulaErrorNUM,
  5181. formulaErrorVALUE, formulaErrorREF, formulaErrorNULL,
  5182. formulaErrorSPILL, formulaErrorCALC, formulaErrorGETTINGDATA,
  5183. } {
  5184. if errType == token.String {
  5185. result = "TRUE"
  5186. }
  5187. }
  5188. }
  5189. return newStringFormulaArg(result)
  5190. }
  5191. // ISERROR function tests if an initial supplied expression (or value) returns
  5192. // an Excel Error, and if so, returns the logical value TRUE; Otherwise the
  5193. // function returns FALSE. The syntax of the function is:
  5194. //
  5195. // ISERROR(value)
  5196. //
  5197. func (fn *formulaFuncs) ISERROR(argsList *list.List) formulaArg {
  5198. if argsList.Len() != 1 {
  5199. return newErrorFormulaArg(formulaErrorVALUE, "ISERROR requires 1 argument")
  5200. }
  5201. token := argsList.Front().Value.(formulaArg)
  5202. result := "FALSE"
  5203. if token.Type == ArgError {
  5204. for _, errType := range []string{
  5205. formulaErrorDIV, formulaErrorNAME, formulaErrorNA, formulaErrorNUM,
  5206. formulaErrorVALUE, formulaErrorREF, formulaErrorNULL, formulaErrorSPILL,
  5207. formulaErrorCALC, formulaErrorGETTINGDATA,
  5208. } {
  5209. if errType == token.String {
  5210. result = "TRUE"
  5211. }
  5212. }
  5213. }
  5214. return newStringFormulaArg(result)
  5215. }
  5216. // ISEVEN function tests if a supplied number (or numeric expression)
  5217. // evaluates to an even number, and if so, returns TRUE; Otherwise, the
  5218. // function returns FALSE. The syntax of the function is:
  5219. //
  5220. // ISEVEN(value)
  5221. //
  5222. func (fn *formulaFuncs) ISEVEN(argsList *list.List) formulaArg {
  5223. if argsList.Len() != 1 {
  5224. return newErrorFormulaArg(formulaErrorVALUE, "ISEVEN requires 1 argument")
  5225. }
  5226. var (
  5227. token = argsList.Front().Value.(formulaArg)
  5228. result = "FALSE"
  5229. numeric int
  5230. err error
  5231. )
  5232. if token.Type == ArgString {
  5233. if numeric, err = strconv.Atoi(token.String); err != nil {
  5234. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  5235. }
  5236. if numeric == numeric/2*2 {
  5237. return newStringFormulaArg("TRUE")
  5238. }
  5239. }
  5240. return newStringFormulaArg(result)
  5241. }
  5242. // ISNA function tests if an initial supplied expression (or value) returns
  5243. // the Excel #N/A Error, and if so, returns TRUE; Otherwise the function
  5244. // returns FALSE. The syntax of the function is:
  5245. //
  5246. // ISNA(value)
  5247. //
  5248. func (fn *formulaFuncs) ISNA(argsList *list.List) formulaArg {
  5249. if argsList.Len() != 1 {
  5250. return newErrorFormulaArg(formulaErrorVALUE, "ISNA requires 1 argument")
  5251. }
  5252. token := argsList.Front().Value.(formulaArg)
  5253. result := "FALSE"
  5254. if token.Type == ArgError && token.String == formulaErrorNA {
  5255. result = "TRUE"
  5256. }
  5257. return newStringFormulaArg(result)
  5258. }
  5259. // ISNONTEXT function function tests if a supplied value is text. If not, the
  5260. // function returns TRUE; If the supplied value is text, the function returns
  5261. // FALSE. The syntax of the function is:
  5262. //
  5263. // ISNONTEXT(value)
  5264. //
  5265. func (fn *formulaFuncs) ISNONTEXT(argsList *list.List) formulaArg {
  5266. if argsList.Len() != 1 {
  5267. return newErrorFormulaArg(formulaErrorVALUE, "ISNONTEXT requires 1 argument")
  5268. }
  5269. token := argsList.Front().Value.(formulaArg)
  5270. result := "TRUE"
  5271. if token.Type == ArgString && token.String != "" {
  5272. result = "FALSE"
  5273. }
  5274. return newStringFormulaArg(result)
  5275. }
  5276. // ISNUMBER function function tests if a supplied value is a number. If so,
  5277. // the function returns TRUE; Otherwise it returns FALSE. The syntax of the
  5278. // function is:
  5279. //
  5280. // ISNUMBER(value)
  5281. //
  5282. func (fn *formulaFuncs) ISNUMBER(argsList *list.List) formulaArg {
  5283. if argsList.Len() != 1 {
  5284. return newErrorFormulaArg(formulaErrorVALUE, "ISNUMBER requires 1 argument")
  5285. }
  5286. token, result := argsList.Front().Value.(formulaArg), false
  5287. if token.Type == ArgString && token.String != "" {
  5288. if _, err := strconv.Atoi(token.String); err == nil {
  5289. result = true
  5290. }
  5291. }
  5292. return newBoolFormulaArg(result)
  5293. }
  5294. // ISODD function tests if a supplied number (or numeric expression) evaluates
  5295. // to an odd number, and if so, returns TRUE; Otherwise, the function returns
  5296. // FALSE. The syntax of the function is:
  5297. //
  5298. // ISODD(value)
  5299. //
  5300. func (fn *formulaFuncs) ISODD(argsList *list.List) formulaArg {
  5301. if argsList.Len() != 1 {
  5302. return newErrorFormulaArg(formulaErrorVALUE, "ISODD requires 1 argument")
  5303. }
  5304. var (
  5305. token = argsList.Front().Value.(formulaArg)
  5306. result = "FALSE"
  5307. numeric int
  5308. err error
  5309. )
  5310. if token.Type == ArgString {
  5311. if numeric, err = strconv.Atoi(token.String); err != nil {
  5312. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  5313. }
  5314. if numeric != numeric/2*2 {
  5315. return newStringFormulaArg("TRUE")
  5316. }
  5317. }
  5318. return newStringFormulaArg(result)
  5319. }
  5320. // ISTEXT function tests if a supplied value is text, and if so, returns TRUE;
  5321. // Otherwise, the function returns FALSE. The syntax of the function is:
  5322. //
  5323. // ISTEXT(value)
  5324. //
  5325. func (fn *formulaFuncs) ISTEXT(argsList *list.List) formulaArg {
  5326. if argsList.Len() != 1 {
  5327. return newErrorFormulaArg(formulaErrorVALUE, "ISTEXT requires 1 argument")
  5328. }
  5329. token := argsList.Front().Value.(formulaArg)
  5330. if token.ToNumber().Type != ArgError {
  5331. return newBoolFormulaArg(false)
  5332. }
  5333. return newBoolFormulaArg(token.Type == ArgString)
  5334. }
  5335. // N function converts data into a numeric value. The syntax of the function
  5336. // is:
  5337. //
  5338. // N(value)
  5339. //
  5340. func (fn *formulaFuncs) N(argsList *list.List) formulaArg {
  5341. if argsList.Len() != 1 {
  5342. return newErrorFormulaArg(formulaErrorVALUE, "N requires 1 argument")
  5343. }
  5344. token, num := argsList.Front().Value.(formulaArg), 0.0
  5345. if token.Type == ArgError {
  5346. return token
  5347. }
  5348. if arg := token.ToNumber(); arg.Type == ArgNumber {
  5349. num = arg.Number
  5350. }
  5351. if token.Value() == "TRUE" {
  5352. num = 1
  5353. }
  5354. return newNumberFormulaArg(num)
  5355. }
  5356. // NA function returns the Excel #N/A error. This error message has the
  5357. // meaning 'value not available' and is produced when an Excel Formula is
  5358. // unable to find a value that it needs. The syntax of the function is:
  5359. //
  5360. // NA()
  5361. //
  5362. func (fn *formulaFuncs) NA(argsList *list.List) formulaArg {
  5363. if argsList.Len() != 0 {
  5364. return newErrorFormulaArg(formulaErrorVALUE, "NA accepts no arguments")
  5365. }
  5366. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  5367. }
  5368. // SHEET function returns the Sheet number for a specified reference. The
  5369. // syntax of the function is:
  5370. //
  5371. // SHEET()
  5372. //
  5373. func (fn *formulaFuncs) SHEET(argsList *list.List) formulaArg {
  5374. if argsList.Len() != 0 {
  5375. return newErrorFormulaArg(formulaErrorVALUE, "SHEET accepts no arguments")
  5376. }
  5377. return newNumberFormulaArg(float64(fn.f.GetSheetIndex(fn.sheet) + 1))
  5378. }
  5379. // T function tests if a supplied value is text and if so, returns the
  5380. // supplied text; Otherwise, the function returns an empty text string. The
  5381. // syntax of the function is:
  5382. //
  5383. // T(value)
  5384. //
  5385. func (fn *formulaFuncs) T(argsList *list.List) formulaArg {
  5386. if argsList.Len() != 1 {
  5387. return newErrorFormulaArg(formulaErrorVALUE, "T requires 1 argument")
  5388. }
  5389. token := argsList.Front().Value.(formulaArg)
  5390. if token.Type == ArgError {
  5391. return token
  5392. }
  5393. if token.Type == ArgNumber {
  5394. return newStringFormulaArg("")
  5395. }
  5396. return newStringFormulaArg(token.Value())
  5397. }
  5398. // Logical Functions
  5399. // AND function tests a number of supplied conditions and returns TRUE or
  5400. // FALSE. The syntax of the function is:
  5401. //
  5402. // AND(logical_test1,[logical_test2],...)
  5403. //
  5404. func (fn *formulaFuncs) AND(argsList *list.List) formulaArg {
  5405. if argsList.Len() == 0 {
  5406. return newErrorFormulaArg(formulaErrorVALUE, "AND requires at least 1 argument")
  5407. }
  5408. if argsList.Len() > 30 {
  5409. return newErrorFormulaArg(formulaErrorVALUE, "AND accepts at most 30 arguments")
  5410. }
  5411. var (
  5412. and = true
  5413. val float64
  5414. err error
  5415. )
  5416. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  5417. token := arg.Value.(formulaArg)
  5418. switch token.Type {
  5419. case ArgUnknown:
  5420. continue
  5421. case ArgString:
  5422. if token.String == "TRUE" {
  5423. continue
  5424. }
  5425. if token.String == "FALSE" {
  5426. return newStringFormulaArg(token.String)
  5427. }
  5428. if val, err = strconv.ParseFloat(token.String, 64); err != nil {
  5429. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  5430. }
  5431. and = and && (val != 0)
  5432. case ArgMatrix:
  5433. // TODO
  5434. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  5435. }
  5436. }
  5437. return newBoolFormulaArg(and)
  5438. }
  5439. // FALSE function function returns the logical value FALSE. The syntax of the
  5440. // function is:
  5441. //
  5442. // FALSE()
  5443. //
  5444. func (fn *formulaFuncs) FALSE(argsList *list.List) formulaArg {
  5445. if argsList.Len() != 0 {
  5446. return newErrorFormulaArg(formulaErrorVALUE, "FALSE takes no arguments")
  5447. }
  5448. return newBoolFormulaArg(false)
  5449. }
  5450. // IFERROR function receives two values (or expressions) and tests if the
  5451. // first of these evaluates to an error. The syntax of the function is:
  5452. //
  5453. // IFERROR(value,value_if_error)
  5454. //
  5455. func (fn *formulaFuncs) IFERROR(argsList *list.List) formulaArg {
  5456. if argsList.Len() != 2 {
  5457. return newErrorFormulaArg(formulaErrorVALUE, "IFERROR requires 2 arguments")
  5458. }
  5459. value := argsList.Front().Value.(formulaArg)
  5460. if value.Type != ArgError {
  5461. if value.Type == ArgEmpty {
  5462. return newNumberFormulaArg(0)
  5463. }
  5464. return value
  5465. }
  5466. return argsList.Back().Value.(formulaArg)
  5467. }
  5468. // NOT function returns the opposite to a supplied logical value. The syntax
  5469. // of the function is:
  5470. //
  5471. // NOT(logical)
  5472. //
  5473. func (fn *formulaFuncs) NOT(argsList *list.List) formulaArg {
  5474. if argsList.Len() != 1 {
  5475. return newErrorFormulaArg(formulaErrorVALUE, "NOT requires 1 argument")
  5476. }
  5477. token := argsList.Front().Value.(formulaArg)
  5478. switch token.Type {
  5479. case ArgString, ArgList:
  5480. if strings.ToUpper(token.String) == "TRUE" {
  5481. return newBoolFormulaArg(false)
  5482. }
  5483. if strings.ToUpper(token.String) == "FALSE" {
  5484. return newBoolFormulaArg(true)
  5485. }
  5486. case ArgNumber:
  5487. return newBoolFormulaArg(!(token.Number != 0))
  5488. case ArgError:
  5489. return token
  5490. }
  5491. return newErrorFormulaArg(formulaErrorVALUE, "NOT expects 1 boolean or numeric argument")
  5492. }
  5493. // OR function tests a number of supplied conditions and returns either TRUE
  5494. // or FALSE. The syntax of the function is:
  5495. //
  5496. // OR(logical_test1,[logical_test2],...)
  5497. //
  5498. func (fn *formulaFuncs) OR(argsList *list.List) formulaArg {
  5499. if argsList.Len() == 0 {
  5500. return newErrorFormulaArg(formulaErrorVALUE, "OR requires at least 1 argument")
  5501. }
  5502. if argsList.Len() > 30 {
  5503. return newErrorFormulaArg(formulaErrorVALUE, "OR accepts at most 30 arguments")
  5504. }
  5505. var (
  5506. or bool
  5507. val float64
  5508. err error
  5509. )
  5510. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  5511. token := arg.Value.(formulaArg)
  5512. switch token.Type {
  5513. case ArgUnknown:
  5514. continue
  5515. case ArgString:
  5516. if token.String == "FALSE" {
  5517. continue
  5518. }
  5519. if token.String == "TRUE" {
  5520. or = true
  5521. continue
  5522. }
  5523. if val, err = strconv.ParseFloat(token.String, 64); err != nil {
  5524. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  5525. }
  5526. or = val != 0
  5527. case ArgMatrix:
  5528. // TODO
  5529. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  5530. }
  5531. }
  5532. return newStringFormulaArg(strings.ToUpper(strconv.FormatBool(or)))
  5533. }
  5534. // TRUE function returns the logical value TRUE. The syntax of the function
  5535. // is:
  5536. //
  5537. // TRUE()
  5538. //
  5539. func (fn *formulaFuncs) TRUE(argsList *list.List) formulaArg {
  5540. if argsList.Len() != 0 {
  5541. return newErrorFormulaArg(formulaErrorVALUE, "TRUE takes no arguments")
  5542. }
  5543. return newBoolFormulaArg(true)
  5544. }
  5545. // Date and Time Functions
  5546. // DATE returns a date, from a user-supplied year, month and day. The syntax
  5547. // of the function is:
  5548. //
  5549. // DATE(year,month,day)
  5550. //
  5551. func (fn *formulaFuncs) DATE(argsList *list.List) formulaArg {
  5552. if argsList.Len() != 3 {
  5553. return newErrorFormulaArg(formulaErrorVALUE, "DATE requires 3 number arguments")
  5554. }
  5555. year := argsList.Front().Value.(formulaArg).ToNumber()
  5556. month := argsList.Front().Next().Value.(formulaArg).ToNumber()
  5557. day := argsList.Back().Value.(formulaArg).ToNumber()
  5558. if year.Type != ArgNumber || month.Type != ArgNumber || day.Type != ArgNumber {
  5559. return newErrorFormulaArg(formulaErrorVALUE, "DATE requires 3 number arguments")
  5560. }
  5561. d := makeDate(int(year.Number), time.Month(month.Number), int(day.Number))
  5562. return newStringFormulaArg(timeFromExcelTime(daysBetween(excelMinTime1900.Unix(), d)+1, false).String())
  5563. }
  5564. // DATEDIF function calculates the number of days, months, or years between
  5565. // two dates. The syntax of the function is:
  5566. //
  5567. // DATEDIF(start_date,end_date,unit)
  5568. //
  5569. func (fn *formulaFuncs) DATEDIF(argsList *list.List) formulaArg {
  5570. if argsList.Len() != 3 {
  5571. return newErrorFormulaArg(formulaErrorVALUE, "DATEDIF requires 3 number arguments")
  5572. }
  5573. startArg, endArg := argsList.Front().Value.(formulaArg).ToNumber(), argsList.Front().Next().Value.(formulaArg).ToNumber()
  5574. if startArg.Type != ArgNumber || endArg.Type != ArgNumber {
  5575. return startArg
  5576. }
  5577. if startArg.Number > endArg.Number {
  5578. return newErrorFormulaArg(formulaErrorNUM, "start_date > end_date")
  5579. }
  5580. if startArg.Number == endArg.Number {
  5581. return newNumberFormulaArg(0)
  5582. }
  5583. unit := strings.ToLower(argsList.Back().Value.(formulaArg).Value())
  5584. startDate, endDate := timeFromExcelTime(startArg.Number, false), timeFromExcelTime(endArg.Number, false)
  5585. sy, smm, sd := startDate.Date()
  5586. ey, emm, ed := endDate.Date()
  5587. sm, em, diff := int(smm), int(emm), 0.0
  5588. switch unit {
  5589. case "d":
  5590. return newNumberFormulaArg(endArg.Number - startArg.Number)
  5591. case "y":
  5592. diff = float64(ey - sy)
  5593. if em < sm || (em == sm && ed < sd) {
  5594. diff--
  5595. }
  5596. case "m":
  5597. ydiff := ey - sy
  5598. mdiff := em - sm
  5599. if ed < sd {
  5600. mdiff--
  5601. }
  5602. if mdiff < 0 {
  5603. ydiff--
  5604. mdiff += 12
  5605. }
  5606. diff = float64(ydiff*12 + mdiff)
  5607. case "md":
  5608. smMD := em
  5609. if ed < sd {
  5610. smMD--
  5611. }
  5612. diff = endArg.Number - daysBetween(excelMinTime1900.Unix(), makeDate(ey, time.Month(smMD), sd)) - 1
  5613. case "ym":
  5614. diff = float64(em - sm)
  5615. if ed < sd {
  5616. diff--
  5617. }
  5618. if diff < 0 {
  5619. diff += 12
  5620. }
  5621. case "yd":
  5622. syYD := sy
  5623. if em < sm || (em == sm && ed < sd) {
  5624. syYD++
  5625. }
  5626. s := daysBetween(excelMinTime1900.Unix(), makeDate(syYD, time.Month(em), ed))
  5627. e := daysBetween(excelMinTime1900.Unix(), makeDate(sy, time.Month(sm), sd))
  5628. diff = s - e
  5629. default:
  5630. return newErrorFormulaArg(formulaErrorVALUE, "DATEDIF has invalid unit")
  5631. }
  5632. return newNumberFormulaArg(diff)
  5633. }
  5634. // NOW function returns the current date and time. The function receives no
  5635. // arguments and therefore. The syntax of the function is:
  5636. //
  5637. // NOW()
  5638. //
  5639. func (fn *formulaFuncs) NOW(argsList *list.List) formulaArg {
  5640. if argsList.Len() != 0 {
  5641. return newErrorFormulaArg(formulaErrorVALUE, "NOW accepts no arguments")
  5642. }
  5643. now := time.Now()
  5644. _, offset := now.Zone()
  5645. return newNumberFormulaArg(25569.0 + float64(now.Unix()+int64(offset))/86400)
  5646. }
  5647. // TODAY function returns the current date. The function has no arguments and
  5648. // therefore. The syntax of the function is:
  5649. //
  5650. // TODAY()
  5651. //
  5652. func (fn *formulaFuncs) TODAY(argsList *list.List) formulaArg {
  5653. if argsList.Len() != 0 {
  5654. return newErrorFormulaArg(formulaErrorVALUE, "TODAY accepts no arguments")
  5655. }
  5656. now := time.Now()
  5657. _, offset := now.Zone()
  5658. return newNumberFormulaArg(daysBetween(excelMinTime1900.Unix(), now.Unix()+int64(offset)) + 1)
  5659. }
  5660. // makeDate return date as a Unix time, the number of seconds elapsed since
  5661. // January 1, 1970 UTC.
  5662. func makeDate(y int, m time.Month, d int) int64 {
  5663. if y == 1900 && int(m) <= 2 {
  5664. d--
  5665. }
  5666. date := time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
  5667. return date.Unix()
  5668. }
  5669. // daysBetween return time interval of the given start timestamp and end
  5670. // timestamp.
  5671. func daysBetween(startDate, endDate int64) float64 {
  5672. return float64(int(0.5 + float64((endDate-startDate)/86400)))
  5673. }
  5674. // Text Functions
  5675. // CHAR function returns the character relating to a supplied character set
  5676. // number (from 1 to 255). syntax of the function is:
  5677. //
  5678. // CHAR(number)
  5679. //
  5680. func (fn *formulaFuncs) CHAR(argsList *list.List) formulaArg {
  5681. if argsList.Len() != 1 {
  5682. return newErrorFormulaArg(formulaErrorVALUE, "CHAR requires 1 argument")
  5683. }
  5684. arg := argsList.Front().Value.(formulaArg).ToNumber()
  5685. if arg.Type != ArgNumber {
  5686. return arg
  5687. }
  5688. num := int(arg.Number)
  5689. if num < 0 || num > 255 {
  5690. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  5691. }
  5692. return newStringFormulaArg(fmt.Sprintf("%c", num))
  5693. }
  5694. // CLEAN removes all non-printable characters from a supplied text string. The
  5695. // syntax of the function is:
  5696. //
  5697. // CLEAN(text)
  5698. //
  5699. func (fn *formulaFuncs) CLEAN(argsList *list.List) formulaArg {
  5700. if argsList.Len() != 1 {
  5701. return newErrorFormulaArg(formulaErrorVALUE, "CLEAN requires 1 argument")
  5702. }
  5703. b := bytes.Buffer{}
  5704. for _, c := range argsList.Front().Value.(formulaArg).String {
  5705. if c > 31 {
  5706. b.WriteRune(c)
  5707. }
  5708. }
  5709. return newStringFormulaArg(b.String())
  5710. }
  5711. // CODE function converts the first character of a supplied text string into
  5712. // the associated numeric character set code used by your computer. The
  5713. // syntax of the function is:
  5714. //
  5715. // CODE(text)
  5716. //
  5717. func (fn *formulaFuncs) CODE(argsList *list.List) formulaArg {
  5718. return fn.code("CODE", argsList)
  5719. }
  5720. // code is an implementation of the formula function CODE and UNICODE.
  5721. func (fn *formulaFuncs) code(name string, argsList *list.List) formulaArg {
  5722. if argsList.Len() != 1 {
  5723. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires 1 argument", name))
  5724. }
  5725. text := argsList.Front().Value.(formulaArg).Value()
  5726. if len(text) == 0 {
  5727. if name == "CODE" {
  5728. return newNumberFormulaArg(0)
  5729. }
  5730. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  5731. }
  5732. return newNumberFormulaArg(float64(text[0]))
  5733. }
  5734. // CONCAT function joins together a series of supplied text strings into one
  5735. // combined text string.
  5736. //
  5737. // CONCAT(text1,[text2],...)
  5738. //
  5739. func (fn *formulaFuncs) CONCAT(argsList *list.List) formulaArg {
  5740. return fn.concat("CONCAT", argsList)
  5741. }
  5742. // CONCATENATE function joins together a series of supplied text strings into
  5743. // one combined text string.
  5744. //
  5745. // CONCATENATE(text1,[text2],...)
  5746. //
  5747. func (fn *formulaFuncs) CONCATENATE(argsList *list.List) formulaArg {
  5748. return fn.concat("CONCATENATE", argsList)
  5749. }
  5750. // concat is an implementation of the formula function CONCAT and CONCATENATE.
  5751. func (fn *formulaFuncs) concat(name string, argsList *list.List) formulaArg {
  5752. buf := bytes.Buffer{}
  5753. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  5754. token := arg.Value.(formulaArg)
  5755. switch token.Type {
  5756. case ArgString:
  5757. buf.WriteString(token.String)
  5758. case ArgNumber:
  5759. if token.Boolean {
  5760. if token.Number == 0 {
  5761. buf.WriteString("FALSE")
  5762. } else {
  5763. buf.WriteString("TRUE")
  5764. }
  5765. } else {
  5766. buf.WriteString(token.Value())
  5767. }
  5768. default:
  5769. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires arguments to be strings", name))
  5770. }
  5771. }
  5772. return newStringFormulaArg(buf.String())
  5773. }
  5774. // EXACT function tests if two supplied text strings or values are exactly
  5775. // equal and if so, returns TRUE; Otherwise, the function returns FALSE. The
  5776. // function is case-sensitive. The syntax of the function is:
  5777. //
  5778. // EXACT(text1,text2)
  5779. //
  5780. func (fn *formulaFuncs) EXACT(argsList *list.List) formulaArg {
  5781. if argsList.Len() != 2 {
  5782. return newErrorFormulaArg(formulaErrorVALUE, "EXACT requires 2 arguments")
  5783. }
  5784. text1 := argsList.Front().Value.(formulaArg).Value()
  5785. text2 := argsList.Back().Value.(formulaArg).Value()
  5786. return newBoolFormulaArg(text1 == text2)
  5787. }
  5788. // FIXED function rounds a supplied number to a specified number of decimal
  5789. // places and then converts this into text. The syntax of the function is:
  5790. //
  5791. // FIXED(number,[decimals],[no_commas])
  5792. //
  5793. func (fn *formulaFuncs) FIXED(argsList *list.List) formulaArg {
  5794. if argsList.Len() < 1 {
  5795. return newErrorFormulaArg(formulaErrorVALUE, "FIXED requires at least 1 argument")
  5796. }
  5797. if argsList.Len() > 3 {
  5798. return newErrorFormulaArg(formulaErrorVALUE, "FIXED allows at most 3 arguments")
  5799. }
  5800. numArg := argsList.Front().Value.(formulaArg).ToNumber()
  5801. if numArg.Type != ArgNumber {
  5802. return numArg
  5803. }
  5804. precision, decimals, noCommas := 0, 0, false
  5805. s := strings.Split(argsList.Front().Value.(formulaArg).Value(), ".")
  5806. if argsList.Len() == 1 && len(s) == 2 {
  5807. precision = len(s[1])
  5808. decimals = len(s[1])
  5809. }
  5810. if argsList.Len() >= 2 {
  5811. decimalsArg := argsList.Front().Next().Value.(formulaArg).ToNumber()
  5812. if decimalsArg.Type != ArgNumber {
  5813. return decimalsArg
  5814. }
  5815. decimals = int(decimalsArg.Number)
  5816. }
  5817. if argsList.Len() == 3 {
  5818. noCommasArg := argsList.Back().Value.(formulaArg).ToBool()
  5819. if noCommasArg.Type == ArgError {
  5820. return noCommasArg
  5821. }
  5822. noCommas = noCommasArg.Boolean
  5823. }
  5824. n := math.Pow(10, float64(decimals))
  5825. r := numArg.Number * n
  5826. fixed := float64(int(r+math.Copysign(0.5, r))) / n
  5827. if decimals > 0 {
  5828. precision = decimals
  5829. }
  5830. if noCommas {
  5831. return newStringFormulaArg(fmt.Sprintf(fmt.Sprintf("%%.%df", precision), fixed))
  5832. }
  5833. p := message.NewPrinter(language.English)
  5834. return newStringFormulaArg(p.Sprintf(fmt.Sprintf("%%.%df", precision), fixed))
  5835. }
  5836. // FIND function returns the position of a specified character or sub-string
  5837. // within a supplied text string. The function is case-sensitive. The syntax
  5838. // of the function is:
  5839. //
  5840. // FIND(find_text,within_text,[start_num])
  5841. //
  5842. func (fn *formulaFuncs) FIND(argsList *list.List) formulaArg {
  5843. return fn.find("FIND", argsList)
  5844. }
  5845. // FINDB counts each double-byte character as 2 when you have enabled the
  5846. // editing of a language that supports DBCS and then set it as the default
  5847. // language. Otherwise, FINDB counts each character as 1. The syntax of the
  5848. // function is:
  5849. //
  5850. // FINDB(find_text,within_text,[start_num])
  5851. //
  5852. func (fn *formulaFuncs) FINDB(argsList *list.List) formulaArg {
  5853. return fn.find("FINDB", argsList)
  5854. }
  5855. // find is an implementation of the formula function FIND and FINDB.
  5856. func (fn *formulaFuncs) find(name string, argsList *list.List) formulaArg {
  5857. if argsList.Len() < 2 {
  5858. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires at least 2 arguments", name))
  5859. }
  5860. if argsList.Len() > 3 {
  5861. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s allows at most 3 arguments", name))
  5862. }
  5863. findText := argsList.Front().Value.(formulaArg).Value()
  5864. withinText := argsList.Front().Next().Value.(formulaArg).Value()
  5865. startNum, result := 1, 1
  5866. if argsList.Len() == 3 {
  5867. numArg := argsList.Back().Value.(formulaArg).ToNumber()
  5868. if numArg.Type != ArgNumber {
  5869. return numArg
  5870. }
  5871. if numArg.Number < 0 {
  5872. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  5873. }
  5874. startNum = int(numArg.Number)
  5875. }
  5876. if findText == "" {
  5877. return newNumberFormulaArg(float64(startNum))
  5878. }
  5879. for idx := range withinText {
  5880. if result < startNum {
  5881. result++
  5882. }
  5883. if strings.Index(withinText[idx:], findText) == 0 {
  5884. return newNumberFormulaArg(float64(result))
  5885. }
  5886. result++
  5887. }
  5888. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  5889. }
  5890. // LEFT function returns a specified number of characters from the start of a
  5891. // supplied text string. The syntax of the function is:
  5892. //
  5893. // LEFT(text,[num_chars])
  5894. //
  5895. func (fn *formulaFuncs) LEFT(argsList *list.List) formulaArg {
  5896. return fn.leftRight("LEFT", argsList)
  5897. }
  5898. // LEFTB returns the first character or characters in a text string, based on
  5899. // the number of bytes you specify. The syntax of the function is:
  5900. //
  5901. // LEFTB(text,[num_bytes])
  5902. //
  5903. func (fn *formulaFuncs) LEFTB(argsList *list.List) formulaArg {
  5904. return fn.leftRight("LEFTB", argsList)
  5905. }
  5906. // leftRight is an implementation of the formula function LEFT, LEFTB, RIGHT,
  5907. // RIGHTB. TODO: support DBCS include Japanese, Chinese (Simplified), Chinese
  5908. // (Traditional), and Korean.
  5909. func (fn *formulaFuncs) leftRight(name string, argsList *list.List) formulaArg {
  5910. if argsList.Len() < 1 {
  5911. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires at least 1 argument", name))
  5912. }
  5913. if argsList.Len() > 2 {
  5914. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s allows at most 2 arguments", name))
  5915. }
  5916. text, numChars := argsList.Front().Value.(formulaArg).Value(), 1
  5917. if argsList.Len() == 2 {
  5918. numArg := argsList.Back().Value.(formulaArg).ToNumber()
  5919. if numArg.Type != ArgNumber {
  5920. return numArg
  5921. }
  5922. if numArg.Number < 0 {
  5923. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  5924. }
  5925. numChars = int(numArg.Number)
  5926. }
  5927. if len(text) > numChars {
  5928. if name == "LEFT" || name == "LEFTB" {
  5929. return newStringFormulaArg(text[:numChars])
  5930. }
  5931. return newStringFormulaArg(text[len(text)-numChars:])
  5932. }
  5933. return newStringFormulaArg(text)
  5934. }
  5935. // LEN returns the length of a supplied text string. The syntax of the
  5936. // function is:
  5937. //
  5938. // LEN(text)
  5939. //
  5940. func (fn *formulaFuncs) LEN(argsList *list.List) formulaArg {
  5941. if argsList.Len() != 1 {
  5942. return newErrorFormulaArg(formulaErrorVALUE, "LEN requires 1 string argument")
  5943. }
  5944. return newStringFormulaArg(strconv.Itoa(len(argsList.Front().Value.(formulaArg).String)))
  5945. }
  5946. // LENB returns the number of bytes used to represent the characters in a text
  5947. // string. LENB counts 2 bytes per character only when a DBCS language is set
  5948. // as the default language. Otherwise LENB behaves the same as LEN, counting
  5949. // 1 byte per character. The syntax of the function is:
  5950. //
  5951. // LENB(text)
  5952. //
  5953. // TODO: the languages that support DBCS include Japanese, Chinese
  5954. // (Simplified), Chinese (Traditional), and Korean.
  5955. func (fn *formulaFuncs) LENB(argsList *list.List) formulaArg {
  5956. if argsList.Len() != 1 {
  5957. return newErrorFormulaArg(formulaErrorVALUE, "LENB requires 1 string argument")
  5958. }
  5959. return newStringFormulaArg(strconv.Itoa(len(argsList.Front().Value.(formulaArg).String)))
  5960. }
  5961. // LOWER converts all characters in a supplied text string to lower case. The
  5962. // syntax of the function is:
  5963. //
  5964. // LOWER(text)
  5965. //
  5966. func (fn *formulaFuncs) LOWER(argsList *list.List) formulaArg {
  5967. if argsList.Len() != 1 {
  5968. return newErrorFormulaArg(formulaErrorVALUE, "LOWER requires 1 argument")
  5969. }
  5970. return newStringFormulaArg(strings.ToLower(argsList.Front().Value.(formulaArg).String))
  5971. }
  5972. // MID function returns a specified number of characters from the middle of a
  5973. // supplied text string. The syntax of the function is:
  5974. //
  5975. // MID(text,start_num,num_chars)
  5976. //
  5977. func (fn *formulaFuncs) MID(argsList *list.List) formulaArg {
  5978. return fn.mid("MID", argsList)
  5979. }
  5980. // MIDB returns a specific number of characters from a text string, starting
  5981. // at the position you specify, based on the number of bytes you specify. The
  5982. // syntax of the function is:
  5983. //
  5984. // MID(text,start_num,num_chars)
  5985. //
  5986. func (fn *formulaFuncs) MIDB(argsList *list.List) formulaArg {
  5987. return fn.mid("MIDB", argsList)
  5988. }
  5989. // mid is an implementation of the formula function MID and MIDB. TODO:
  5990. // support DBCS include Japanese, Chinese (Simplified), Chinese
  5991. // (Traditional), and Korean.
  5992. func (fn *formulaFuncs) mid(name string, argsList *list.List) formulaArg {
  5993. if argsList.Len() != 3 {
  5994. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires 3 arguments", name))
  5995. }
  5996. text := argsList.Front().Value.(formulaArg).Value()
  5997. startNumArg, numCharsArg := argsList.Front().Next().Value.(formulaArg).ToNumber(), argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  5998. if startNumArg.Type != ArgNumber {
  5999. return startNumArg
  6000. }
  6001. if numCharsArg.Type != ArgNumber {
  6002. return numCharsArg
  6003. }
  6004. startNum := int(startNumArg.Number)
  6005. if startNum < 0 {
  6006. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  6007. }
  6008. textLen := len(text)
  6009. if startNum > textLen {
  6010. return newStringFormulaArg("")
  6011. }
  6012. startNum--
  6013. endNum := startNum + int(numCharsArg.Number)
  6014. if endNum > textLen+1 {
  6015. return newStringFormulaArg(text[startNum:])
  6016. }
  6017. return newStringFormulaArg(text[startNum:endNum])
  6018. }
  6019. // PROPER converts all characters in a supplied text string to proper case
  6020. // (i.e. all letters that do not immediately follow another letter are set to
  6021. // upper case and all other characters are lower case). The syntax of the
  6022. // function is:
  6023. //
  6024. // PROPER(text)
  6025. //
  6026. func (fn *formulaFuncs) PROPER(argsList *list.List) formulaArg {
  6027. if argsList.Len() != 1 {
  6028. return newErrorFormulaArg(formulaErrorVALUE, "PROPER requires 1 argument")
  6029. }
  6030. buf := bytes.Buffer{}
  6031. isLetter := false
  6032. for _, char := range argsList.Front().Value.(formulaArg).String {
  6033. if !isLetter && unicode.IsLetter(char) {
  6034. buf.WriteRune(unicode.ToUpper(char))
  6035. } else {
  6036. buf.WriteRune(unicode.ToLower(char))
  6037. }
  6038. isLetter = unicode.IsLetter(char)
  6039. }
  6040. return newStringFormulaArg(buf.String())
  6041. }
  6042. // REPLACE function replaces all or part of a text string with another string.
  6043. // The syntax of the function is:
  6044. //
  6045. // REPLACE(old_text,start_num,num_chars,new_text)
  6046. //
  6047. func (fn *formulaFuncs) REPLACE(argsList *list.List) formulaArg {
  6048. return fn.replace("REPLACE", argsList)
  6049. }
  6050. // REPLACEB replaces part of a text string, based on the number of bytes you
  6051. // specify, with a different text string.
  6052. //
  6053. // REPLACEB(old_text,start_num,num_chars,new_text)
  6054. //
  6055. func (fn *formulaFuncs) REPLACEB(argsList *list.List) formulaArg {
  6056. return fn.replace("REPLACEB", argsList)
  6057. }
  6058. // replace is an implementation of the formula function REPLACE and REPLACEB.
  6059. // TODO: support DBCS include Japanese, Chinese (Simplified), Chinese
  6060. // (Traditional), and Korean.
  6061. func (fn *formulaFuncs) replace(name string, argsList *list.List) formulaArg {
  6062. if argsList.Len() != 4 {
  6063. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires 4 arguments", name))
  6064. }
  6065. oldText, newText := argsList.Front().Value.(formulaArg).Value(), argsList.Back().Value.(formulaArg).Value()
  6066. startNumArg, numCharsArg := argsList.Front().Next().Value.(formulaArg).ToNumber(), argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  6067. if startNumArg.Type != ArgNumber {
  6068. return startNumArg
  6069. }
  6070. if numCharsArg.Type != ArgNumber {
  6071. return numCharsArg
  6072. }
  6073. oldTextLen, startIdx := len(oldText), int(startNumArg.Number)
  6074. if startIdx > oldTextLen {
  6075. startIdx = oldTextLen + 1
  6076. }
  6077. endIdx := startIdx + int(numCharsArg.Number)
  6078. if endIdx > oldTextLen {
  6079. endIdx = oldTextLen + 1
  6080. }
  6081. if startIdx < 1 || endIdx < 1 {
  6082. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  6083. }
  6084. result := oldText[:startIdx-1] + newText + oldText[endIdx-1:]
  6085. return newStringFormulaArg(result)
  6086. }
  6087. // REPT function returns a supplied text string, repeated a specified number
  6088. // of times. The syntax of the function is:
  6089. //
  6090. // REPT(text,number_times)
  6091. //
  6092. func (fn *formulaFuncs) REPT(argsList *list.List) formulaArg {
  6093. if argsList.Len() != 2 {
  6094. return newErrorFormulaArg(formulaErrorVALUE, "REPT requires 2 arguments")
  6095. }
  6096. text := argsList.Front().Value.(formulaArg)
  6097. if text.Type != ArgString {
  6098. return newErrorFormulaArg(formulaErrorVALUE, "REPT requires first argument to be a string")
  6099. }
  6100. times := argsList.Back().Value.(formulaArg).ToNumber()
  6101. if times.Type != ArgNumber {
  6102. return newErrorFormulaArg(formulaErrorVALUE, "REPT requires second argument to be a number")
  6103. }
  6104. if times.Number < 0 {
  6105. return newErrorFormulaArg(formulaErrorVALUE, "REPT requires second argument to be >= 0")
  6106. }
  6107. if times.Number == 0 {
  6108. return newStringFormulaArg("")
  6109. }
  6110. buf := bytes.Buffer{}
  6111. for i := 0; i < int(times.Number); i++ {
  6112. buf.WriteString(text.String)
  6113. }
  6114. return newStringFormulaArg(buf.String())
  6115. }
  6116. // RIGHT function returns a specified number of characters from the end of a
  6117. // supplied text string. The syntax of the function is:
  6118. //
  6119. // RIGHT(text,[num_chars])
  6120. //
  6121. func (fn *formulaFuncs) RIGHT(argsList *list.List) formulaArg {
  6122. return fn.leftRight("RIGHT", argsList)
  6123. }
  6124. // RIGHTB returns the last character or characters in a text string, based on
  6125. // the number of bytes you specify. The syntax of the function is:
  6126. //
  6127. // RIGHTB(text,[num_bytes])
  6128. //
  6129. func (fn *formulaFuncs) RIGHTB(argsList *list.List) formulaArg {
  6130. return fn.leftRight("RIGHTB", argsList)
  6131. }
  6132. // SUBSTITUTE function replaces one or more instances of a given text string,
  6133. // within an original text string. The syntax of the function is:
  6134. //
  6135. // SUBSTITUTE(text,old_text,new_text,[instance_num])
  6136. //
  6137. func (fn *formulaFuncs) SUBSTITUTE(argsList *list.List) formulaArg {
  6138. if argsList.Len() != 3 && argsList.Len() != 4 {
  6139. return newErrorFormulaArg(formulaErrorVALUE, "SUBSTITUTE requires 3 or 4 arguments")
  6140. }
  6141. text, oldText := argsList.Front().Value.(formulaArg), argsList.Front().Next().Value.(formulaArg)
  6142. newText, instanceNum := argsList.Front().Next().Next().Value.(formulaArg), 0
  6143. if argsList.Len() == 3 {
  6144. return newStringFormulaArg(strings.Replace(text.Value(), oldText.Value(), newText.Value(), -1))
  6145. }
  6146. instanceNumArg := argsList.Back().Value.(formulaArg).ToNumber()
  6147. if instanceNumArg.Type != ArgNumber {
  6148. return instanceNumArg
  6149. }
  6150. instanceNum = int(instanceNumArg.Number)
  6151. if instanceNum < 1 {
  6152. return newErrorFormulaArg(formulaErrorVALUE, "instance_num should be > 0")
  6153. }
  6154. str, oldTextLen, count, chars, pos := text.Value(), len(oldText.Value()), instanceNum, 0, -1
  6155. for {
  6156. count--
  6157. index := strings.Index(str, oldText.Value())
  6158. if index == -1 {
  6159. pos = -1
  6160. break
  6161. } else {
  6162. pos = index + chars
  6163. if count == 0 {
  6164. break
  6165. }
  6166. idx := oldTextLen + index
  6167. chars += idx
  6168. str = str[idx:]
  6169. }
  6170. }
  6171. if pos == -1 {
  6172. return newStringFormulaArg(text.Value())
  6173. }
  6174. pre, post := text.Value()[:pos], text.Value()[pos+oldTextLen:]
  6175. return newStringFormulaArg(pre + newText.Value() + post)
  6176. }
  6177. // TRIM removes extra spaces (i.e. all spaces except for single spaces between
  6178. // words or characters) from a supplied text string. The syntax of the
  6179. // function is:
  6180. //
  6181. // TRIM(text)
  6182. //
  6183. func (fn *formulaFuncs) TRIM(argsList *list.List) formulaArg {
  6184. if argsList.Len() != 1 {
  6185. return newErrorFormulaArg(formulaErrorVALUE, "TRIM requires 1 argument")
  6186. }
  6187. return newStringFormulaArg(strings.TrimSpace(argsList.Front().Value.(formulaArg).String))
  6188. }
  6189. // UNICHAR returns the Unicode character that is referenced by the given
  6190. // numeric value. The syntax of the function is:
  6191. //
  6192. // UNICHAR(number)
  6193. //
  6194. func (fn *formulaFuncs) UNICHAR(argsList *list.List) formulaArg {
  6195. if argsList.Len() != 1 {
  6196. return newErrorFormulaArg(formulaErrorVALUE, "UNICHAR requires 1 argument")
  6197. }
  6198. numArg := argsList.Front().Value.(formulaArg).ToNumber()
  6199. if numArg.Type != ArgNumber {
  6200. return numArg
  6201. }
  6202. if numArg.Number <= 0 || numArg.Number > 55295 {
  6203. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  6204. }
  6205. return newStringFormulaArg(string(rune(numArg.Number)))
  6206. }
  6207. // UNICODE function returns the code point for the first character of a
  6208. // supplied text string. The syntax of the function is:
  6209. //
  6210. // UNICODE(text)
  6211. //
  6212. func (fn *formulaFuncs) UNICODE(argsList *list.List) formulaArg {
  6213. return fn.code("UNICODE", argsList)
  6214. }
  6215. // UPPER converts all characters in a supplied text string to upper case. The
  6216. // syntax of the function is:
  6217. //
  6218. // UPPER(text)
  6219. //
  6220. func (fn *formulaFuncs) UPPER(argsList *list.List) formulaArg {
  6221. if argsList.Len() != 1 {
  6222. return newErrorFormulaArg(formulaErrorVALUE, "UPPER requires 1 argument")
  6223. }
  6224. return newStringFormulaArg(strings.ToUpper(argsList.Front().Value.(formulaArg).String))
  6225. }
  6226. // Conditional Functions
  6227. // IF function tests a supplied condition and returns one result if the
  6228. // condition evaluates to TRUE, and another result if the condition evaluates
  6229. // to FALSE. The syntax of the function is:
  6230. //
  6231. // IF(logical_test,value_if_true,value_if_false)
  6232. //
  6233. func (fn *formulaFuncs) IF(argsList *list.List) formulaArg {
  6234. if argsList.Len() == 0 {
  6235. return newErrorFormulaArg(formulaErrorVALUE, "IF requires at least 1 argument")
  6236. }
  6237. if argsList.Len() > 3 {
  6238. return newErrorFormulaArg(formulaErrorVALUE, "IF accepts at most 3 arguments")
  6239. }
  6240. token := argsList.Front().Value.(formulaArg)
  6241. var (
  6242. cond bool
  6243. err error
  6244. result string
  6245. )
  6246. switch token.Type {
  6247. case ArgString:
  6248. if cond, err = strconv.ParseBool(token.String); err != nil {
  6249. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  6250. }
  6251. if argsList.Len() == 1 {
  6252. return newBoolFormulaArg(cond)
  6253. }
  6254. if cond {
  6255. return newStringFormulaArg(argsList.Front().Next().Value.(formulaArg).String)
  6256. }
  6257. if argsList.Len() == 3 {
  6258. result = argsList.Back().Value.(formulaArg).String
  6259. }
  6260. }
  6261. return newStringFormulaArg(result)
  6262. }
  6263. // Lookup and Reference Functions
  6264. // CHOOSE function returns a value from an array, that corresponds to a
  6265. // supplied index number (position). The syntax of the function is:
  6266. //
  6267. // CHOOSE(index_num,value1,[value2],...)
  6268. //
  6269. func (fn *formulaFuncs) CHOOSE(argsList *list.List) formulaArg {
  6270. if argsList.Len() < 2 {
  6271. return newErrorFormulaArg(formulaErrorVALUE, "CHOOSE requires 2 arguments")
  6272. }
  6273. idx, err := strconv.Atoi(argsList.Front().Value.(formulaArg).String)
  6274. if err != nil {
  6275. return newErrorFormulaArg(formulaErrorVALUE, "CHOOSE requires first argument of type number")
  6276. }
  6277. if argsList.Len() <= idx {
  6278. return newErrorFormulaArg(formulaErrorVALUE, "index_num should be <= to the number of values")
  6279. }
  6280. arg := argsList.Front()
  6281. for i := 0; i < idx; i++ {
  6282. arg = arg.Next()
  6283. }
  6284. var result formulaArg
  6285. switch arg.Value.(formulaArg).Type {
  6286. case ArgString:
  6287. result = newStringFormulaArg(arg.Value.(formulaArg).String)
  6288. case ArgMatrix:
  6289. result = newMatrixFormulaArg(arg.Value.(formulaArg).Matrix)
  6290. }
  6291. return result
  6292. }
  6293. // deepMatchRune finds whether the text deep matches/satisfies the pattern
  6294. // string.
  6295. func deepMatchRune(str, pattern []rune, simple bool) bool {
  6296. for len(pattern) > 0 {
  6297. switch pattern[0] {
  6298. default:
  6299. if len(str) == 0 || str[0] != pattern[0] {
  6300. return false
  6301. }
  6302. case '?':
  6303. if len(str) == 0 && !simple {
  6304. return false
  6305. }
  6306. case '*':
  6307. return deepMatchRune(str, pattern[1:], simple) ||
  6308. (len(str) > 0 && deepMatchRune(str[1:], pattern, simple))
  6309. }
  6310. str = str[1:]
  6311. pattern = pattern[1:]
  6312. }
  6313. return len(str) == 0 && len(pattern) == 0
  6314. }
  6315. // matchPattern finds whether the text matches or satisfies the pattern
  6316. // string. The pattern supports '*' and '?' wildcards in the pattern string.
  6317. func matchPattern(pattern, name string) (matched bool) {
  6318. if pattern == "" {
  6319. return name == pattern
  6320. }
  6321. if pattern == "*" {
  6322. return true
  6323. }
  6324. rname, rpattern := make([]rune, 0, len(name)), make([]rune, 0, len(pattern))
  6325. for _, r := range name {
  6326. rname = append(rname, r)
  6327. }
  6328. for _, r := range pattern {
  6329. rpattern = append(rpattern, r)
  6330. }
  6331. simple := false // Does extended wildcard '*' and '?' match.
  6332. return deepMatchRune(rname, rpattern, simple)
  6333. }
  6334. // compareFormulaArg compares the left-hand sides and the right-hand sides
  6335. // formula arguments by given conditions such as case sensitive, if exact
  6336. // match, and make compare result as formula criteria condition type.
  6337. func compareFormulaArg(lhs, rhs formulaArg, caseSensitive, exactMatch bool) byte {
  6338. if lhs.Type != rhs.Type {
  6339. return criteriaErr
  6340. }
  6341. switch lhs.Type {
  6342. case ArgNumber:
  6343. if lhs.Number == rhs.Number {
  6344. return criteriaEq
  6345. }
  6346. if lhs.Number < rhs.Number {
  6347. return criteriaL
  6348. }
  6349. return criteriaG
  6350. case ArgString:
  6351. ls, rs := lhs.String, rhs.String
  6352. if !caseSensitive {
  6353. ls, rs = strings.ToLower(ls), strings.ToLower(rs)
  6354. }
  6355. if exactMatch {
  6356. match := matchPattern(rs, ls)
  6357. if match {
  6358. return criteriaEq
  6359. }
  6360. return criteriaG
  6361. }
  6362. switch strings.Compare(ls, rs) {
  6363. case 1:
  6364. return criteriaG
  6365. case -1:
  6366. return criteriaL
  6367. case 0:
  6368. return criteriaEq
  6369. }
  6370. return criteriaErr
  6371. case ArgEmpty:
  6372. return criteriaEq
  6373. case ArgList:
  6374. return compareFormulaArgList(lhs, rhs, caseSensitive, exactMatch)
  6375. case ArgMatrix:
  6376. return compareFormulaArgMatrix(lhs, rhs, caseSensitive, exactMatch)
  6377. }
  6378. return criteriaErr
  6379. }
  6380. // compareFormulaArgList compares the left-hand sides and the right-hand sides
  6381. // list type formula arguments.
  6382. func compareFormulaArgList(lhs, rhs formulaArg, caseSensitive, exactMatch bool) byte {
  6383. if len(lhs.List) < len(rhs.List) {
  6384. return criteriaL
  6385. }
  6386. if len(lhs.List) > len(rhs.List) {
  6387. return criteriaG
  6388. }
  6389. for arg := range lhs.List {
  6390. criteria := compareFormulaArg(lhs.List[arg], rhs.List[arg], caseSensitive, exactMatch)
  6391. if criteria != criteriaEq {
  6392. return criteria
  6393. }
  6394. }
  6395. return criteriaEq
  6396. }
  6397. // compareFormulaArgMatrix compares the left-hand sides and the right-hand sides
  6398. // matrix type formula arguments.
  6399. func compareFormulaArgMatrix(lhs, rhs formulaArg, caseSensitive, exactMatch bool) byte {
  6400. if len(lhs.Matrix) < len(rhs.Matrix) {
  6401. return criteriaL
  6402. }
  6403. if len(lhs.Matrix) > len(rhs.Matrix) {
  6404. return criteriaG
  6405. }
  6406. for i := range lhs.Matrix {
  6407. left := lhs.Matrix[i]
  6408. right := lhs.Matrix[i]
  6409. if len(left) < len(right) {
  6410. return criteriaL
  6411. }
  6412. if len(left) > len(right) {
  6413. return criteriaG
  6414. }
  6415. for arg := range left {
  6416. criteria := compareFormulaArg(left[arg], right[arg], caseSensitive, exactMatch)
  6417. if criteria != criteriaEq {
  6418. return criteria
  6419. }
  6420. }
  6421. }
  6422. return criteriaEq
  6423. }
  6424. // COLUMN function returns the first column number within a supplied reference
  6425. // or the number of the current column. The syntax of the function is:
  6426. //
  6427. // COLUMN([reference])
  6428. //
  6429. func (fn *formulaFuncs) COLUMN(argsList *list.List) formulaArg {
  6430. if argsList.Len() > 1 {
  6431. return newErrorFormulaArg(formulaErrorVALUE, "COLUMN requires at most 1 argument")
  6432. }
  6433. if argsList.Len() == 1 {
  6434. if argsList.Front().Value.(formulaArg).cellRanges != nil && argsList.Front().Value.(formulaArg).cellRanges.Len() > 0 {
  6435. return newNumberFormulaArg(float64(argsList.Front().Value.(formulaArg).cellRanges.Front().Value.(cellRange).From.Col))
  6436. }
  6437. if argsList.Front().Value.(formulaArg).cellRefs != nil && argsList.Front().Value.(formulaArg).cellRefs.Len() > 0 {
  6438. return newNumberFormulaArg(float64(argsList.Front().Value.(formulaArg).cellRefs.Front().Value.(cellRef).Col))
  6439. }
  6440. return newErrorFormulaArg(formulaErrorVALUE, "invalid reference")
  6441. }
  6442. col, _, _ := CellNameToCoordinates(fn.cell)
  6443. return newNumberFormulaArg(float64(col))
  6444. }
  6445. // COLUMNS function receives an Excel range and returns the number of columns
  6446. // that are contained within the range. The syntax of the function is:
  6447. //
  6448. // COLUMNS(array)
  6449. //
  6450. func (fn *formulaFuncs) COLUMNS(argsList *list.List) formulaArg {
  6451. if argsList.Len() != 1 {
  6452. return newErrorFormulaArg(formulaErrorVALUE, "COLUMNS requires 1 argument")
  6453. }
  6454. var min, max int
  6455. if argsList.Front().Value.(formulaArg).cellRanges != nil && argsList.Front().Value.(formulaArg).cellRanges.Len() > 0 {
  6456. crs := argsList.Front().Value.(formulaArg).cellRanges
  6457. for cr := crs.Front(); cr != nil; cr = cr.Next() {
  6458. if min == 0 {
  6459. min = cr.Value.(cellRange).From.Col
  6460. }
  6461. if min > cr.Value.(cellRange).From.Col {
  6462. min = cr.Value.(cellRange).From.Col
  6463. }
  6464. if min > cr.Value.(cellRange).To.Col {
  6465. min = cr.Value.(cellRange).To.Col
  6466. }
  6467. if max < cr.Value.(cellRange).To.Col {
  6468. max = cr.Value.(cellRange).To.Col
  6469. }
  6470. if max < cr.Value.(cellRange).From.Col {
  6471. max = cr.Value.(cellRange).From.Col
  6472. }
  6473. }
  6474. }
  6475. if argsList.Front().Value.(formulaArg).cellRefs != nil && argsList.Front().Value.(formulaArg).cellRefs.Len() > 0 {
  6476. cr := argsList.Front().Value.(formulaArg).cellRefs
  6477. for refs := cr.Front(); refs != nil; refs = refs.Next() {
  6478. if min == 0 {
  6479. min = refs.Value.(cellRef).Col
  6480. }
  6481. if min > refs.Value.(cellRef).Col {
  6482. min = refs.Value.(cellRef).Col
  6483. }
  6484. if max < refs.Value.(cellRef).Col {
  6485. max = refs.Value.(cellRef).Col
  6486. }
  6487. }
  6488. }
  6489. if max == TotalColumns {
  6490. return newNumberFormulaArg(float64(TotalColumns))
  6491. }
  6492. result := max - min + 1
  6493. if max == min {
  6494. if min == 0 {
  6495. return newErrorFormulaArg(formulaErrorVALUE, "invalid reference")
  6496. }
  6497. return newNumberFormulaArg(float64(1))
  6498. }
  6499. return newNumberFormulaArg(float64(result))
  6500. }
  6501. // HLOOKUP function 'looks up' a given value in the top row of a data array
  6502. // (or table), and returns the corresponding value from another row of the
  6503. // array. The syntax of the function is:
  6504. //
  6505. // HLOOKUP(lookup_value,table_array,row_index_num,[range_lookup])
  6506. //
  6507. func (fn *formulaFuncs) HLOOKUP(argsList *list.List) formulaArg {
  6508. if argsList.Len() < 3 {
  6509. return newErrorFormulaArg(formulaErrorVALUE, "HLOOKUP requires at least 3 arguments")
  6510. }
  6511. if argsList.Len() > 4 {
  6512. return newErrorFormulaArg(formulaErrorVALUE, "HLOOKUP requires at most 4 arguments")
  6513. }
  6514. lookupValue := argsList.Front().Value.(formulaArg)
  6515. tableArray := argsList.Front().Next().Value.(formulaArg)
  6516. if tableArray.Type != ArgMatrix {
  6517. return newErrorFormulaArg(formulaErrorVALUE, "HLOOKUP requires second argument of table array")
  6518. }
  6519. rowArg := argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  6520. if rowArg.Type != ArgNumber {
  6521. return newErrorFormulaArg(formulaErrorVALUE, "HLOOKUP requires numeric row argument")
  6522. }
  6523. rowIdx, matchIdx, wasExact, exactMatch := int(rowArg.Number)-1, -1, false, false
  6524. if argsList.Len() == 4 {
  6525. rangeLookup := argsList.Back().Value.(formulaArg).ToBool()
  6526. if rangeLookup.Type == ArgError {
  6527. return newErrorFormulaArg(formulaErrorVALUE, rangeLookup.Error)
  6528. }
  6529. if rangeLookup.Number == 0 {
  6530. exactMatch = true
  6531. }
  6532. }
  6533. row := tableArray.Matrix[0]
  6534. if exactMatch || len(tableArray.Matrix) == TotalRows {
  6535. start:
  6536. for idx, mtx := range row {
  6537. lhs := mtx
  6538. switch lookupValue.Type {
  6539. case ArgNumber:
  6540. if !lookupValue.Boolean {
  6541. lhs = mtx.ToNumber()
  6542. if lhs.Type == ArgError {
  6543. lhs = mtx
  6544. }
  6545. }
  6546. case ArgMatrix:
  6547. lhs = tableArray
  6548. }
  6549. if compareFormulaArg(lhs, lookupValue, false, exactMatch) == criteriaEq {
  6550. matchIdx = idx
  6551. wasExact = true
  6552. break start
  6553. }
  6554. }
  6555. } else {
  6556. matchIdx, wasExact = hlookupBinarySearch(row, lookupValue)
  6557. }
  6558. if matchIdx == -1 {
  6559. return newErrorFormulaArg(formulaErrorNA, "HLOOKUP no result found")
  6560. }
  6561. if rowIdx < 0 || rowIdx >= len(tableArray.Matrix) {
  6562. return newErrorFormulaArg(formulaErrorNA, "HLOOKUP has invalid row index")
  6563. }
  6564. row = tableArray.Matrix[rowIdx]
  6565. if wasExact || !exactMatch {
  6566. return row[matchIdx]
  6567. }
  6568. return newErrorFormulaArg(formulaErrorNA, "HLOOKUP no result found")
  6569. }
  6570. // VLOOKUP function 'looks up' a given value in the left-hand column of a
  6571. // data array (or table), and returns the corresponding value from another
  6572. // column of the array. The syntax of the function is:
  6573. //
  6574. // VLOOKUP(lookup_value,table_array,col_index_num,[range_lookup])
  6575. //
  6576. func (fn *formulaFuncs) VLOOKUP(argsList *list.List) formulaArg {
  6577. if argsList.Len() < 3 {
  6578. return newErrorFormulaArg(formulaErrorVALUE, "VLOOKUP requires at least 3 arguments")
  6579. }
  6580. if argsList.Len() > 4 {
  6581. return newErrorFormulaArg(formulaErrorVALUE, "VLOOKUP requires at most 4 arguments")
  6582. }
  6583. lookupValue := argsList.Front().Value.(formulaArg)
  6584. tableArray := argsList.Front().Next().Value.(formulaArg)
  6585. if tableArray.Type != ArgMatrix {
  6586. return newErrorFormulaArg(formulaErrorVALUE, "VLOOKUP requires second argument of table array")
  6587. }
  6588. colIdx := argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  6589. if colIdx.Type != ArgNumber {
  6590. return newErrorFormulaArg(formulaErrorVALUE, "VLOOKUP requires numeric col argument")
  6591. }
  6592. col, matchIdx, wasExact, exactMatch := int(colIdx.Number)-1, -1, false, false
  6593. if argsList.Len() == 4 {
  6594. rangeLookup := argsList.Back().Value.(formulaArg).ToBool()
  6595. if rangeLookup.Type == ArgError {
  6596. return newErrorFormulaArg(formulaErrorVALUE, rangeLookup.Error)
  6597. }
  6598. if rangeLookup.Number == 0 {
  6599. exactMatch = true
  6600. }
  6601. }
  6602. if exactMatch || len(tableArray.Matrix) == TotalRows {
  6603. start:
  6604. for idx, mtx := range tableArray.Matrix {
  6605. lhs := mtx[0]
  6606. switch lookupValue.Type {
  6607. case ArgNumber:
  6608. if !lookupValue.Boolean {
  6609. lhs = mtx[0].ToNumber()
  6610. if lhs.Type == ArgError {
  6611. lhs = mtx[0]
  6612. }
  6613. }
  6614. case ArgMatrix:
  6615. lhs = tableArray
  6616. }
  6617. if compareFormulaArg(lhs, lookupValue, false, exactMatch) == criteriaEq {
  6618. matchIdx = idx
  6619. wasExact = true
  6620. break start
  6621. }
  6622. }
  6623. } else {
  6624. matchIdx, wasExact = vlookupBinarySearch(tableArray, lookupValue)
  6625. }
  6626. if matchIdx == -1 {
  6627. return newErrorFormulaArg(formulaErrorNA, "VLOOKUP no result found")
  6628. }
  6629. mtx := tableArray.Matrix[matchIdx]
  6630. if col < 0 || col >= len(mtx) {
  6631. return newErrorFormulaArg(formulaErrorNA, "VLOOKUP has invalid column index")
  6632. }
  6633. if wasExact || !exactMatch {
  6634. return mtx[col]
  6635. }
  6636. return newErrorFormulaArg(formulaErrorNA, "VLOOKUP no result found")
  6637. }
  6638. // vlookupBinarySearch finds the position of a target value when range lookup
  6639. // is TRUE, if the data of table array can't guarantee be sorted, it will
  6640. // return wrong result.
  6641. func vlookupBinarySearch(tableArray, lookupValue formulaArg) (matchIdx int, wasExact bool) {
  6642. var low, high, lastMatchIdx int = 0, len(tableArray.Matrix) - 1, -1
  6643. for low <= high {
  6644. var mid int = low + (high-low)/2
  6645. mtx := tableArray.Matrix[mid]
  6646. lhs := mtx[0]
  6647. switch lookupValue.Type {
  6648. case ArgNumber:
  6649. if !lookupValue.Boolean {
  6650. lhs = mtx[0].ToNumber()
  6651. if lhs.Type == ArgError {
  6652. lhs = mtx[0]
  6653. }
  6654. }
  6655. case ArgMatrix:
  6656. lhs = tableArray
  6657. }
  6658. result := compareFormulaArg(lhs, lookupValue, false, false)
  6659. if result == criteriaEq {
  6660. matchIdx, wasExact = mid, true
  6661. return
  6662. } else if result == criteriaG {
  6663. high = mid - 1
  6664. } else if result == criteriaL {
  6665. matchIdx, low = mid, mid+1
  6666. if lhs.Value() != "" {
  6667. lastMatchIdx = matchIdx
  6668. }
  6669. } else {
  6670. return -1, false
  6671. }
  6672. }
  6673. matchIdx, wasExact = lastMatchIdx, true
  6674. return
  6675. }
  6676. // vlookupBinarySearch finds the position of a target value when range lookup
  6677. // is TRUE, if the data of table array can't guarantee be sorted, it will
  6678. // return wrong result.
  6679. func hlookupBinarySearch(row []formulaArg, lookupValue formulaArg) (matchIdx int, wasExact bool) {
  6680. var low, high, lastMatchIdx int = 0, len(row) - 1, -1
  6681. for low <= high {
  6682. var mid int = low + (high-low)/2
  6683. mtx := row[mid]
  6684. result := compareFormulaArg(mtx, lookupValue, false, false)
  6685. if result == criteriaEq {
  6686. matchIdx, wasExact = mid, true
  6687. return
  6688. } else if result == criteriaG {
  6689. high = mid - 1
  6690. } else if result == criteriaL {
  6691. low, lastMatchIdx = mid+1, mid
  6692. } else {
  6693. return -1, false
  6694. }
  6695. }
  6696. matchIdx, wasExact = lastMatchIdx, true
  6697. return
  6698. }
  6699. // LOOKUP function performs an approximate match lookup in a one-column or
  6700. // one-row range, and returns the corresponding value from another one-column
  6701. // or one-row range. The syntax of the function is:
  6702. //
  6703. // LOOKUP(lookup_value,lookup_vector,[result_vector])
  6704. //
  6705. func (fn *formulaFuncs) LOOKUP(argsList *list.List) formulaArg {
  6706. if argsList.Len() < 2 {
  6707. return newErrorFormulaArg(formulaErrorVALUE, "LOOKUP requires at least 2 arguments")
  6708. }
  6709. if argsList.Len() > 3 {
  6710. return newErrorFormulaArg(formulaErrorVALUE, "LOOKUP requires at most 3 arguments")
  6711. }
  6712. lookupValue := argsList.Front().Value.(formulaArg)
  6713. lookupVector := argsList.Front().Next().Value.(formulaArg)
  6714. if lookupVector.Type != ArgMatrix && lookupVector.Type != ArgList {
  6715. return newErrorFormulaArg(formulaErrorVALUE, "LOOKUP requires second argument of table array")
  6716. }
  6717. cols, matchIdx := lookupCol(lookupVector), -1
  6718. for idx, col := range cols {
  6719. lhs := lookupValue
  6720. switch col.Type {
  6721. case ArgNumber:
  6722. lhs = lhs.ToNumber()
  6723. if !col.Boolean {
  6724. if lhs.Type == ArgError {
  6725. lhs = lookupValue
  6726. }
  6727. }
  6728. }
  6729. if compareFormulaArg(lhs, col, false, false) == criteriaEq {
  6730. matchIdx = idx
  6731. break
  6732. }
  6733. }
  6734. column := cols
  6735. if argsList.Len() == 3 {
  6736. column = lookupCol(argsList.Back().Value.(formulaArg))
  6737. }
  6738. if matchIdx < 0 || matchIdx >= len(column) {
  6739. return newErrorFormulaArg(formulaErrorNA, "LOOKUP no result found")
  6740. }
  6741. return column[matchIdx]
  6742. }
  6743. // lookupCol extract columns for LOOKUP.
  6744. func lookupCol(arr formulaArg) []formulaArg {
  6745. col := arr.List
  6746. if arr.Type == ArgMatrix {
  6747. col = nil
  6748. for _, r := range arr.Matrix {
  6749. if len(r) > 0 {
  6750. col = append(col, r[0])
  6751. continue
  6752. }
  6753. col = append(col, newEmptyFormulaArg())
  6754. }
  6755. }
  6756. return col
  6757. }
  6758. // ROW function returns the first row number within a supplied reference or
  6759. // the number of the current row. The syntax of the function is:
  6760. //
  6761. // ROW([reference])
  6762. //
  6763. func (fn *formulaFuncs) ROW(argsList *list.List) formulaArg {
  6764. if argsList.Len() > 1 {
  6765. return newErrorFormulaArg(formulaErrorVALUE, "ROW requires at most 1 argument")
  6766. }
  6767. if argsList.Len() == 1 {
  6768. if argsList.Front().Value.(formulaArg).cellRanges != nil && argsList.Front().Value.(formulaArg).cellRanges.Len() > 0 {
  6769. return newNumberFormulaArg(float64(argsList.Front().Value.(formulaArg).cellRanges.Front().Value.(cellRange).From.Row))
  6770. }
  6771. if argsList.Front().Value.(formulaArg).cellRefs != nil && argsList.Front().Value.(formulaArg).cellRefs.Len() > 0 {
  6772. return newNumberFormulaArg(float64(argsList.Front().Value.(formulaArg).cellRefs.Front().Value.(cellRef).Row))
  6773. }
  6774. return newErrorFormulaArg(formulaErrorVALUE, "invalid reference")
  6775. }
  6776. _, row, _ := CellNameToCoordinates(fn.cell)
  6777. return newNumberFormulaArg(float64(row))
  6778. }
  6779. // ROWS function takes an Excel range and returns the number of rows that are
  6780. // contained within the range. The syntax of the function is:
  6781. //
  6782. // ROWS(array)
  6783. //
  6784. func (fn *formulaFuncs) ROWS(argsList *list.List) formulaArg {
  6785. if argsList.Len() != 1 {
  6786. return newErrorFormulaArg(formulaErrorVALUE, "ROWS requires 1 argument")
  6787. }
  6788. var min, max int
  6789. if argsList.Front().Value.(formulaArg).cellRanges != nil && argsList.Front().Value.(formulaArg).cellRanges.Len() > 0 {
  6790. crs := argsList.Front().Value.(formulaArg).cellRanges
  6791. for cr := crs.Front(); cr != nil; cr = cr.Next() {
  6792. if min == 0 {
  6793. min = cr.Value.(cellRange).From.Row
  6794. }
  6795. if min > cr.Value.(cellRange).From.Row {
  6796. min = cr.Value.(cellRange).From.Row
  6797. }
  6798. if min > cr.Value.(cellRange).To.Row {
  6799. min = cr.Value.(cellRange).To.Row
  6800. }
  6801. if max < cr.Value.(cellRange).To.Row {
  6802. max = cr.Value.(cellRange).To.Row
  6803. }
  6804. if max < cr.Value.(cellRange).From.Row {
  6805. max = cr.Value.(cellRange).From.Row
  6806. }
  6807. }
  6808. }
  6809. if argsList.Front().Value.(formulaArg).cellRefs != nil && argsList.Front().Value.(formulaArg).cellRefs.Len() > 0 {
  6810. cr := argsList.Front().Value.(formulaArg).cellRefs
  6811. for refs := cr.Front(); refs != nil; refs = refs.Next() {
  6812. if min == 0 {
  6813. min = refs.Value.(cellRef).Row
  6814. }
  6815. if min > refs.Value.(cellRef).Row {
  6816. min = refs.Value.(cellRef).Row
  6817. }
  6818. if max < refs.Value.(cellRef).Row {
  6819. max = refs.Value.(cellRef).Row
  6820. }
  6821. }
  6822. }
  6823. if max == TotalRows {
  6824. return newStringFormulaArg(strconv.Itoa(TotalRows))
  6825. }
  6826. result := max - min + 1
  6827. if max == min {
  6828. if min == 0 {
  6829. return newErrorFormulaArg(formulaErrorVALUE, "invalid reference")
  6830. }
  6831. return newNumberFormulaArg(float64(1))
  6832. }
  6833. return newStringFormulaArg(strconv.Itoa(result))
  6834. }
  6835. // Web Functions
  6836. // ENCODEURL function returns a URL-encoded string, replacing certain
  6837. // non-alphanumeric characters with the percentage symbol (%) and a
  6838. // hexadecimal number. The syntax of the function is:
  6839. //
  6840. // ENCODEURL(url)
  6841. //
  6842. func (fn *formulaFuncs) ENCODEURL(argsList *list.List) formulaArg {
  6843. if argsList.Len() != 1 {
  6844. return newErrorFormulaArg(formulaErrorVALUE, "ENCODEURL requires 1 argument")
  6845. }
  6846. token := argsList.Front().Value.(formulaArg).Value()
  6847. return newStringFormulaArg(strings.Replace(url.QueryEscape(token), "+", "%20", -1))
  6848. }
  6849. // Financial Functions
  6850. // CUMIPMT function calculates the cumulative interest paid on a loan or
  6851. // investment, between two specified periods. The syntax of the function is:
  6852. //
  6853. // CUMIPMT(rate,nper,pv,start_period,end_period,type)
  6854. //
  6855. func (fn *formulaFuncs) CUMIPMT(argsList *list.List) formulaArg {
  6856. return fn.cumip("CUMIPMT", argsList)
  6857. }
  6858. // CUMPRINC function calculates the cumulative payment on the principal of a
  6859. // loan or investment, between two specified periods. The syntax of the
  6860. // function is:
  6861. //
  6862. // CUMPRINC(rate,nper,pv,start_period,end_period,type)
  6863. //
  6864. func (fn *formulaFuncs) CUMPRINC(argsList *list.List) formulaArg {
  6865. return fn.cumip("CUMPRINC", argsList)
  6866. }
  6867. // cumip is an implementation of the formula function CUMIPMT and CUMPRINC.
  6868. func (fn *formulaFuncs) cumip(name string, argsList *list.List) formulaArg {
  6869. if argsList.Len() != 6 {
  6870. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires 6 arguments", name))
  6871. }
  6872. rate := argsList.Front().Value.(formulaArg).ToNumber()
  6873. if rate.Type != ArgNumber {
  6874. return rate
  6875. }
  6876. nper := argsList.Front().Next().Value.(formulaArg).ToNumber()
  6877. if nper.Type != ArgNumber {
  6878. return nper
  6879. }
  6880. pv := argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  6881. if pv.Type != ArgNumber {
  6882. return pv
  6883. }
  6884. start := argsList.Back().Prev().Prev().Value.(formulaArg).ToNumber()
  6885. if start.Type != ArgNumber {
  6886. return start
  6887. }
  6888. end := argsList.Back().Prev().Value.(formulaArg).ToNumber()
  6889. if end.Type != ArgNumber {
  6890. return end
  6891. }
  6892. typ := argsList.Back().Value.(formulaArg).ToNumber()
  6893. if typ.Type != ArgNumber {
  6894. return typ
  6895. }
  6896. if typ.Number != 0 && typ.Number != 1 {
  6897. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  6898. }
  6899. if start.Number < 1 || start.Number > end.Number {
  6900. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  6901. }
  6902. num, ipmt := 0.0, newNumberFormulaArg(0)
  6903. for per := start.Number; per <= end.Number; per++ {
  6904. args := list.New().Init()
  6905. args.PushBack(rate)
  6906. args.PushBack(newNumberFormulaArg(per))
  6907. args.PushBack(nper)
  6908. args.PushBack(pv)
  6909. args.PushBack(newNumberFormulaArg(0))
  6910. args.PushBack(typ)
  6911. if name == "CUMIPMT" {
  6912. ipmt = fn.IPMT(args)
  6913. } else {
  6914. ipmt = fn.PPMT(args)
  6915. }
  6916. num += ipmt.Number
  6917. }
  6918. return newNumberFormulaArg(num)
  6919. }
  6920. // DB function calculates the depreciation of an asset, using the Fixed
  6921. // Declining Balance Method, for each period of the asset's lifetime. The
  6922. // syntax of the function is:
  6923. //
  6924. // DB(cost,salvage,life,period,[month])
  6925. //
  6926. func (fn *formulaFuncs) DB(argsList *list.List) formulaArg {
  6927. if argsList.Len() < 4 {
  6928. return newErrorFormulaArg(formulaErrorVALUE, "DB requires at least 4 arguments")
  6929. }
  6930. if argsList.Len() > 5 {
  6931. return newErrorFormulaArg(formulaErrorVALUE, "DB allows at most 5 arguments")
  6932. }
  6933. cost := argsList.Front().Value.(formulaArg).ToNumber()
  6934. if cost.Type != ArgNumber {
  6935. return cost
  6936. }
  6937. salvage := argsList.Front().Next().Value.(formulaArg).ToNumber()
  6938. if salvage.Type != ArgNumber {
  6939. return salvage
  6940. }
  6941. life := argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  6942. if life.Type != ArgNumber {
  6943. return life
  6944. }
  6945. period := argsList.Front().Next().Next().Next().Value.(formulaArg).ToNumber()
  6946. if period.Type != ArgNumber {
  6947. return period
  6948. }
  6949. month := newNumberFormulaArg(12)
  6950. if argsList.Len() == 5 {
  6951. if month = argsList.Back().Value.(formulaArg).ToNumber(); month.Type != ArgNumber {
  6952. return month
  6953. }
  6954. }
  6955. if cost.Number == 0 {
  6956. return newNumberFormulaArg(0)
  6957. }
  6958. if (cost.Number <= 0) || ((salvage.Number / cost.Number) < 0) || (life.Number <= 0) || (period.Number < 1) || (month.Number < 1) {
  6959. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  6960. }
  6961. dr := 1 - math.Pow(salvage.Number/cost.Number, 1/life.Number)
  6962. dr = math.Round(dr*1000) / 1000
  6963. pd, depreciation := 0.0, 0.0
  6964. for per := 1; per <= int(period.Number); per++ {
  6965. if per == 1 {
  6966. depreciation = cost.Number * dr * month.Number / 12
  6967. } else if per == int(life.Number+1) {
  6968. depreciation = (cost.Number - pd) * dr * (12 - month.Number) / 12
  6969. } else {
  6970. depreciation = (cost.Number - pd) * dr
  6971. }
  6972. pd += depreciation
  6973. }
  6974. return newNumberFormulaArg(depreciation)
  6975. }
  6976. // DDB function calculates the depreciation of an asset, using the Double
  6977. // Declining Balance Method, or another specified depreciation rate. The
  6978. // syntax of the function is:
  6979. //
  6980. // DDB(cost,salvage,life,period,[factor])
  6981. //
  6982. func (fn *formulaFuncs) DDB(argsList *list.List) formulaArg {
  6983. if argsList.Len() < 4 {
  6984. return newErrorFormulaArg(formulaErrorVALUE, "DDB requires at least 4 arguments")
  6985. }
  6986. if argsList.Len() > 5 {
  6987. return newErrorFormulaArg(formulaErrorVALUE, "DDB allows at most 5 arguments")
  6988. }
  6989. cost := argsList.Front().Value.(formulaArg).ToNumber()
  6990. if cost.Type != ArgNumber {
  6991. return cost
  6992. }
  6993. salvage := argsList.Front().Next().Value.(formulaArg).ToNumber()
  6994. if salvage.Type != ArgNumber {
  6995. return salvage
  6996. }
  6997. life := argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  6998. if life.Type != ArgNumber {
  6999. return life
  7000. }
  7001. period := argsList.Front().Next().Next().Next().Value.(formulaArg).ToNumber()
  7002. if period.Type != ArgNumber {
  7003. return period
  7004. }
  7005. factor := newNumberFormulaArg(2)
  7006. if argsList.Len() == 5 {
  7007. if factor = argsList.Back().Value.(formulaArg).ToNumber(); factor.Type != ArgNumber {
  7008. return factor
  7009. }
  7010. }
  7011. if cost.Number == 0 {
  7012. return newNumberFormulaArg(0)
  7013. }
  7014. if (cost.Number <= 0) || ((salvage.Number / cost.Number) < 0) || (life.Number <= 0) || (period.Number < 1) || (factor.Number <= 0.0) || (period.Number > life.Number) {
  7015. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  7016. }
  7017. pd, depreciation := 0.0, 0.0
  7018. for per := 1; per <= int(period.Number); per++ {
  7019. depreciation = math.Min((cost.Number-pd)*(factor.Number/life.Number), (cost.Number - salvage.Number - pd))
  7020. pd += depreciation
  7021. }
  7022. return newNumberFormulaArg(depreciation)
  7023. }
  7024. // DOLLARDE function converts a dollar value in fractional notation, into a
  7025. // dollar value expressed as a decimal. The syntax of the function is:
  7026. //
  7027. // DOLLARDE(fractional_dollar,fraction)
  7028. //
  7029. func (fn *formulaFuncs) DOLLARDE(argsList *list.List) formulaArg {
  7030. return fn.dollar("DOLLARDE", argsList)
  7031. }
  7032. // DOLLARFR function converts a dollar value in decimal notation, into a
  7033. // dollar value that is expressed in fractional notation. The syntax of the
  7034. // function is:
  7035. //
  7036. // DOLLARFR(decimal_dollar,fraction)
  7037. //
  7038. func (fn *formulaFuncs) DOLLARFR(argsList *list.List) formulaArg {
  7039. return fn.dollar("DOLLARFR", argsList)
  7040. }
  7041. // dollar is an implementation of the formula function DOLLARDE and DOLLARFR.
  7042. func (fn *formulaFuncs) dollar(name string, argsList *list.List) formulaArg {
  7043. if argsList.Len() != 2 {
  7044. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires 2 arguments", name))
  7045. }
  7046. dollar := argsList.Front().Value.(formulaArg).ToNumber()
  7047. if dollar.Type != ArgNumber {
  7048. return dollar
  7049. }
  7050. frac := argsList.Back().Value.(formulaArg).ToNumber()
  7051. if frac.Type != ArgNumber {
  7052. return frac
  7053. }
  7054. if frac.Number < 0 {
  7055. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  7056. }
  7057. if frac.Number == 0 {
  7058. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  7059. }
  7060. cents := math.Mod(dollar.Number, 1)
  7061. if name == "DOLLARDE" {
  7062. cents /= frac.Number
  7063. cents *= math.Pow(10, math.Ceil(math.Log10(frac.Number)))
  7064. } else {
  7065. cents *= frac.Number
  7066. cents *= math.Pow(10, -math.Ceil(math.Log10(frac.Number)))
  7067. }
  7068. return newNumberFormulaArg(math.Floor(dollar.Number) + cents)
  7069. }
  7070. // EFFECT function returns the effective annual interest rate for a given
  7071. // nominal interest rate and number of compounding periods per year. The
  7072. // syntax of the function is:
  7073. //
  7074. // EFFECT(nominal_rate,npery)
  7075. //
  7076. func (fn *formulaFuncs) EFFECT(argsList *list.List) formulaArg {
  7077. if argsList.Len() != 2 {
  7078. return newErrorFormulaArg(formulaErrorVALUE, "EFFECT requires 2 arguments")
  7079. }
  7080. rate := argsList.Front().Value.(formulaArg).ToNumber()
  7081. if rate.Type != ArgNumber {
  7082. return rate
  7083. }
  7084. npery := argsList.Back().Value.(formulaArg).ToNumber()
  7085. if npery.Type != ArgNumber {
  7086. return npery
  7087. }
  7088. if rate.Number <= 0 || npery.Number < 1 {
  7089. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  7090. }
  7091. return newNumberFormulaArg(math.Pow((1+rate.Number/npery.Number), npery.Number) - 1)
  7092. }
  7093. // FV function calculates the Future Value of an investment with periodic
  7094. // constant payments and a constant interest rate. The syntax of the function
  7095. // is:
  7096. //
  7097. // FV(rate,nper,[pmt],[pv],[type])
  7098. //
  7099. func (fn *formulaFuncs) FV(argsList *list.List) formulaArg {
  7100. if argsList.Len() < 3 {
  7101. return newErrorFormulaArg(formulaErrorVALUE, "FV requires at least 3 arguments")
  7102. }
  7103. if argsList.Len() > 5 {
  7104. return newErrorFormulaArg(formulaErrorVALUE, "FV allows at most 5 arguments")
  7105. }
  7106. rate := argsList.Front().Value.(formulaArg).ToNumber()
  7107. if rate.Type != ArgNumber {
  7108. return rate
  7109. }
  7110. nper := argsList.Front().Next().Value.(formulaArg).ToNumber()
  7111. if nper.Type != ArgNumber {
  7112. return nper
  7113. }
  7114. pmt := argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  7115. if pmt.Type != ArgNumber {
  7116. return pmt
  7117. }
  7118. pv, typ := newNumberFormulaArg(0), newNumberFormulaArg(0)
  7119. if argsList.Len() >= 4 {
  7120. if pv = argsList.Front().Next().Next().Next().Value.(formulaArg).ToNumber(); pv.Type != ArgNumber {
  7121. return pv
  7122. }
  7123. }
  7124. if argsList.Len() == 5 {
  7125. if typ = argsList.Back().Value.(formulaArg).ToNumber(); typ.Type != ArgNumber {
  7126. return typ
  7127. }
  7128. }
  7129. if typ.Number != 0 && typ.Number != 1 {
  7130. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  7131. }
  7132. if rate.Number != 0 {
  7133. return newNumberFormulaArg(-pv.Number*math.Pow(1+rate.Number, nper.Number) - pmt.Number*(1+rate.Number*typ.Number)*(math.Pow(1+rate.Number, nper.Number)-1)/rate.Number)
  7134. }
  7135. return newNumberFormulaArg(-pv.Number - pmt.Number*nper.Number)
  7136. }
  7137. // FVSCHEDULE function calculates the Future Value of an investment with a
  7138. // variable interest rate. The syntax of the function is:
  7139. //
  7140. // FVSCHEDULE(principal,schedule)
  7141. //
  7142. func (fn *formulaFuncs) FVSCHEDULE(argsList *list.List) formulaArg {
  7143. if argsList.Len() != 2 {
  7144. return newErrorFormulaArg(formulaErrorVALUE, "FVSCHEDULE requires 2 arguments")
  7145. }
  7146. pri := argsList.Front().Value.(formulaArg).ToNumber()
  7147. if pri.Type != ArgNumber {
  7148. return pri
  7149. }
  7150. principal := pri.Number
  7151. for _, arg := range argsList.Back().Value.(formulaArg).ToList() {
  7152. if arg.Value() == "" {
  7153. continue
  7154. }
  7155. rate := arg.ToNumber()
  7156. if rate.Type != ArgNumber {
  7157. return rate
  7158. }
  7159. principal *= (1 + rate.Number)
  7160. }
  7161. return newNumberFormulaArg(principal)
  7162. }
  7163. // IPMT function calculates the interest payment, during a specific period of a
  7164. // loan or investment that is paid in constant periodic payments, with a
  7165. // constant interest rate. The syntax of the function is:
  7166. //
  7167. // IPMT(rate,per,nper,pv,[fv],[type])
  7168. //
  7169. func (fn *formulaFuncs) IPMT(argsList *list.List) formulaArg {
  7170. return fn.ipmt("IPMT", argsList)
  7171. }
  7172. // ipmt is an implementation of the formula function IPMT and PPMT.
  7173. func (fn *formulaFuncs) ipmt(name string, argsList *list.List) formulaArg {
  7174. if argsList.Len() < 4 {
  7175. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires at least 4 arguments", name))
  7176. }
  7177. if argsList.Len() > 6 {
  7178. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s allows at most 6 arguments", name))
  7179. }
  7180. rate := argsList.Front().Value.(formulaArg).ToNumber()
  7181. if rate.Type != ArgNumber {
  7182. return rate
  7183. }
  7184. per := argsList.Front().Next().Value.(formulaArg).ToNumber()
  7185. if per.Type != ArgNumber {
  7186. return per
  7187. }
  7188. nper := argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  7189. if nper.Type != ArgNumber {
  7190. return nper
  7191. }
  7192. pv := argsList.Front().Next().Next().Next().Value.(formulaArg).ToNumber()
  7193. if pv.Type != ArgNumber {
  7194. return pv
  7195. }
  7196. fv, typ := newNumberFormulaArg(0), newNumberFormulaArg(0)
  7197. if argsList.Len() >= 5 {
  7198. if fv = argsList.Front().Next().Next().Next().Next().Value.(formulaArg).ToNumber(); fv.Type != ArgNumber {
  7199. return fv
  7200. }
  7201. }
  7202. if argsList.Len() == 6 {
  7203. if typ = argsList.Back().Value.(formulaArg).ToNumber(); typ.Type != ArgNumber {
  7204. return typ
  7205. }
  7206. }
  7207. if typ.Number != 0 && typ.Number != 1 {
  7208. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  7209. }
  7210. if per.Number <= 0 || per.Number > nper.Number {
  7211. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  7212. }
  7213. args := list.New().Init()
  7214. args.PushBack(rate)
  7215. args.PushBack(nper)
  7216. args.PushBack(pv)
  7217. args.PushBack(fv)
  7218. args.PushBack(typ)
  7219. pmt, capital, interest, principal := fn.PMT(args), pv.Number, 0.0, 0.0
  7220. for i := 1; i <= int(per.Number); i++ {
  7221. if typ.Number != 0 && i == 1 {
  7222. interest = 0
  7223. } else {
  7224. interest = -capital * rate.Number
  7225. }
  7226. principal = pmt.Number - interest
  7227. capital += principal
  7228. }
  7229. if name == "IPMT" {
  7230. return newNumberFormulaArg(interest)
  7231. }
  7232. return newNumberFormulaArg(principal)
  7233. }
  7234. // IRR function returns the Internal Rate of Return for a supplied series of
  7235. // periodic cash flows (i.e. an initial investment value and a series of net
  7236. // income values). The syntax of the function is:
  7237. //
  7238. // IRR(values,[guess])
  7239. //
  7240. func (fn *formulaFuncs) IRR(argsList *list.List) formulaArg {
  7241. if argsList.Len() < 1 {
  7242. return newErrorFormulaArg(formulaErrorVALUE, "IRR requires at least 1 argument")
  7243. }
  7244. if argsList.Len() > 2 {
  7245. return newErrorFormulaArg(formulaErrorVALUE, "IRR allows at most 2 arguments")
  7246. }
  7247. values, guess := argsList.Front().Value.(formulaArg).ToList(), newNumberFormulaArg(0.1)
  7248. if argsList.Len() > 1 {
  7249. if guess = argsList.Back().Value.(formulaArg).ToNumber(); guess.Type != ArgNumber {
  7250. return guess
  7251. }
  7252. }
  7253. x1, x2 := newNumberFormulaArg(0), guess
  7254. args := list.New().Init()
  7255. args.PushBack(x1)
  7256. for _, v := range values {
  7257. args.PushBack(v)
  7258. }
  7259. f1 := fn.NPV(args)
  7260. args.Front().Value = x2
  7261. f2 := fn.NPV(args)
  7262. for i := 0; i < maxFinancialIterations; i++ {
  7263. if f1.Number*f2.Number < 0 {
  7264. break
  7265. }
  7266. if math.Abs(f1.Number) < math.Abs((f2.Number)) {
  7267. x1.Number += 1.6 * (x1.Number - x2.Number)
  7268. args.Front().Value = x1
  7269. f1 = fn.NPV(args)
  7270. continue
  7271. }
  7272. x2.Number += 1.6 * (x2.Number - x1.Number)
  7273. args.Front().Value = x2
  7274. f2 = fn.NPV(args)
  7275. }
  7276. if f1.Number*f2.Number > 0 {
  7277. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  7278. }
  7279. args.Front().Value = x1
  7280. f := fn.NPV(args)
  7281. var rtb, dx, xMid, fMid float64
  7282. if f.Number < 0 {
  7283. rtb = x1.Number
  7284. dx = x2.Number - x1.Number
  7285. } else {
  7286. rtb = x2.Number
  7287. dx = x1.Number - x2.Number
  7288. }
  7289. for i := 0; i < maxFinancialIterations; i++ {
  7290. dx *= 0.5
  7291. xMid = rtb + dx
  7292. args.Front().Value = newNumberFormulaArg(xMid)
  7293. fMid = fn.NPV(args).Number
  7294. if fMid <= 0 {
  7295. rtb = xMid
  7296. }
  7297. if math.Abs(fMid) < financialPercision || math.Abs(dx) < financialPercision {
  7298. break
  7299. }
  7300. }
  7301. return newNumberFormulaArg(xMid)
  7302. }
  7303. // ISPMT function calculates the interest paid during a specific period of a
  7304. // loan or investment. The syntax of the function is:
  7305. //
  7306. // ISPMT(rate,per,nper,pv)
  7307. //
  7308. func (fn *formulaFuncs) ISPMT(argsList *list.List) formulaArg {
  7309. if argsList.Len() != 4 {
  7310. return newErrorFormulaArg(formulaErrorVALUE, "ISPMT requires 4 arguments")
  7311. }
  7312. rate := argsList.Front().Value.(formulaArg).ToNumber()
  7313. if rate.Type != ArgNumber {
  7314. return rate
  7315. }
  7316. per := argsList.Front().Next().Value.(formulaArg).ToNumber()
  7317. if per.Type != ArgNumber {
  7318. return per
  7319. }
  7320. nper := argsList.Back().Prev().Value.(formulaArg).ToNumber()
  7321. if nper.Type != ArgNumber {
  7322. return nper
  7323. }
  7324. pv := argsList.Back().Value.(formulaArg).ToNumber()
  7325. if pv.Type != ArgNumber {
  7326. return pv
  7327. }
  7328. pr, payment, num := pv.Number, pv.Number/nper.Number, 0.0
  7329. for i := 0; i <= int(per.Number); i++ {
  7330. num = rate.Number * pr * -1
  7331. pr -= payment
  7332. if i == int(nper.Number) {
  7333. num = 0
  7334. }
  7335. }
  7336. return newNumberFormulaArg(num)
  7337. }
  7338. // MIRR function returns the Modified Internal Rate of Return for a supplied
  7339. // series of periodic cash flows (i.e. a set of values, which includes an
  7340. // initial investment value and a series of net income values). The syntax of
  7341. // the function is:
  7342. //
  7343. // MIRR(values,finance_rate,reinvest_rate)
  7344. //
  7345. func (fn *formulaFuncs) MIRR(argsList *list.List) formulaArg {
  7346. if argsList.Len() != 3 {
  7347. return newErrorFormulaArg(formulaErrorVALUE, "MIRR requires 3 arguments")
  7348. }
  7349. values := argsList.Front().Value.(formulaArg).ToList()
  7350. financeRate := argsList.Front().Next().Value.(formulaArg).ToNumber()
  7351. if financeRate.Type != ArgNumber {
  7352. return financeRate
  7353. }
  7354. reinvestRate := argsList.Back().Value.(formulaArg).ToNumber()
  7355. if reinvestRate.Type != ArgNumber {
  7356. return reinvestRate
  7357. }
  7358. n, fr, rr, npvPos, npvNeg := len(values), 1+financeRate.Number, 1+reinvestRate.Number, 0.0, 0.0
  7359. for i, v := range values {
  7360. val := v.ToNumber()
  7361. if val.Number >= 0 {
  7362. npvPos += val.Number / math.Pow(float64(rr), float64(i))
  7363. continue
  7364. }
  7365. npvNeg += val.Number / math.Pow(float64(fr), float64(i))
  7366. }
  7367. if npvNeg == 0 || npvPos == 0 || reinvestRate.Number <= -1 {
  7368. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  7369. }
  7370. return newNumberFormulaArg(math.Pow(-npvPos*math.Pow(rr, float64(n))/(npvNeg*rr), 1/(float64(n)-1)) - 1)
  7371. }
  7372. // NOMINAL function returns the nominal interest rate for a given effective
  7373. // interest rate and number of compounding periods per year. The syntax of
  7374. // the function is:
  7375. //
  7376. // NOMINAL(effect_rate,npery)
  7377. //
  7378. func (fn *formulaFuncs) NOMINAL(argsList *list.List) formulaArg {
  7379. if argsList.Len() != 2 {
  7380. return newErrorFormulaArg(formulaErrorVALUE, "NOMINAL requires 2 arguments")
  7381. }
  7382. rate := argsList.Front().Value.(formulaArg).ToNumber()
  7383. if rate.Type != ArgNumber {
  7384. return rate
  7385. }
  7386. npery := argsList.Back().Value.(formulaArg).ToNumber()
  7387. if npery.Type != ArgNumber {
  7388. return npery
  7389. }
  7390. if rate.Number <= 0 || npery.Number < 1 {
  7391. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  7392. }
  7393. return newNumberFormulaArg(npery.Number * (math.Pow(rate.Number+1, 1/npery.Number) - 1))
  7394. }
  7395. // NPER function calculates the number of periods required to pay off a loan,
  7396. // for a constant periodic payment and a constant interest rate. The syntax
  7397. // of the function is:
  7398. //
  7399. // NPER(rate,pmt,pv,[fv],[type])
  7400. //
  7401. func (fn *formulaFuncs) NPER(argsList *list.List) formulaArg {
  7402. if argsList.Len() < 3 {
  7403. return newErrorFormulaArg(formulaErrorVALUE, "NPER requires at least 3 arguments")
  7404. }
  7405. if argsList.Len() > 5 {
  7406. return newErrorFormulaArg(formulaErrorVALUE, "NPER allows at most 5 arguments")
  7407. }
  7408. rate := argsList.Front().Value.(formulaArg).ToNumber()
  7409. if rate.Type != ArgNumber {
  7410. return rate
  7411. }
  7412. pmt := argsList.Front().Next().Value.(formulaArg).ToNumber()
  7413. if pmt.Type != ArgNumber {
  7414. return pmt
  7415. }
  7416. pv := argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  7417. if pv.Type != ArgNumber {
  7418. return pv
  7419. }
  7420. fv, typ := newNumberFormulaArg(0), newNumberFormulaArg(0)
  7421. if argsList.Len() >= 4 {
  7422. if fv = argsList.Front().Next().Next().Next().Value.(formulaArg).ToNumber(); fv.Type != ArgNumber {
  7423. return fv
  7424. }
  7425. }
  7426. if argsList.Len() == 5 {
  7427. if typ = argsList.Back().Value.(formulaArg).ToNumber(); typ.Type != ArgNumber {
  7428. return typ
  7429. }
  7430. }
  7431. if typ.Number != 0 && typ.Number != 1 {
  7432. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  7433. }
  7434. if pmt.Number == 0 {
  7435. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  7436. }
  7437. if rate.Number != 0 {
  7438. p := math.Log((pmt.Number*(1+rate.Number*typ.Number)/rate.Number-fv.Number)/(pv.Number+pmt.Number*(1+rate.Number*typ.Number)/rate.Number)) / math.Log(1+rate.Number)
  7439. return newNumberFormulaArg(p)
  7440. }
  7441. return newNumberFormulaArg((-pv.Number - fv.Number) / pmt.Number)
  7442. }
  7443. // NPV function calculates the Net Present Value of an investment, based on a
  7444. // supplied discount rate, and a series of future payments and income. The
  7445. // syntax of the function is:
  7446. //
  7447. // NPV(rate,value1,[value2],[value3],...)
  7448. //
  7449. func (fn *formulaFuncs) NPV(argsList *list.List) formulaArg {
  7450. if argsList.Len() < 2 {
  7451. return newErrorFormulaArg(formulaErrorVALUE, "NPV requires at least 2 arguments")
  7452. }
  7453. rate := argsList.Front().Value.(formulaArg).ToNumber()
  7454. if rate.Type != ArgNumber {
  7455. return rate
  7456. }
  7457. val, i := 0.0, 1
  7458. for arg := argsList.Front().Next(); arg != nil; arg = arg.Next() {
  7459. num := arg.Value.(formulaArg).ToNumber()
  7460. if num.Type != ArgNumber {
  7461. continue
  7462. }
  7463. val += num.Number / math.Pow(1+rate.Number, float64(i))
  7464. i++
  7465. }
  7466. return newNumberFormulaArg(val)
  7467. }
  7468. // PDURATION function calculates the number of periods required for an
  7469. // investment to reach a specified future value. The syntax of the function
  7470. // is:
  7471. //
  7472. // PDURATION(rate,pv,fv)
  7473. //
  7474. func (fn *formulaFuncs) PDURATION(argsList *list.List) formulaArg {
  7475. if argsList.Len() != 3 {
  7476. return newErrorFormulaArg(formulaErrorVALUE, "PDURATION requires 3 arguments")
  7477. }
  7478. rate := argsList.Front().Value.(formulaArg).ToNumber()
  7479. if rate.Type != ArgNumber {
  7480. return rate
  7481. }
  7482. pv := argsList.Front().Next().Value.(formulaArg).ToNumber()
  7483. if pv.Type != ArgNumber {
  7484. return pv
  7485. }
  7486. fv := argsList.Back().Value.(formulaArg).ToNumber()
  7487. if fv.Type != ArgNumber {
  7488. return fv
  7489. }
  7490. if rate.Number <= 0 || pv.Number <= 0 || fv.Number <= 0 {
  7491. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  7492. }
  7493. return newNumberFormulaArg((math.Log(fv.Number) - math.Log(pv.Number)) / math.Log(1+rate.Number))
  7494. }
  7495. // PMT function calculates the constant periodic payment required to pay off
  7496. // (or partially pay off) a loan or investment, with a constant interest
  7497. // rate, over a specified period. The syntax of the function is:
  7498. //
  7499. // PMT(rate,nper,pv,[fv],[type])
  7500. //
  7501. func (fn *formulaFuncs) PMT(argsList *list.List) formulaArg {
  7502. if argsList.Len() < 3 {
  7503. return newErrorFormulaArg(formulaErrorVALUE, "PMT requires at least 3 arguments")
  7504. }
  7505. if argsList.Len() > 5 {
  7506. return newErrorFormulaArg(formulaErrorVALUE, "PMT allows at most 5 arguments")
  7507. }
  7508. rate := argsList.Front().Value.(formulaArg).ToNumber()
  7509. if rate.Type != ArgNumber {
  7510. return rate
  7511. }
  7512. nper := argsList.Front().Next().Value.(formulaArg).ToNumber()
  7513. if nper.Type != ArgNumber {
  7514. return nper
  7515. }
  7516. pv := argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  7517. if pv.Type != ArgNumber {
  7518. return pv
  7519. }
  7520. fv, typ := newNumberFormulaArg(0), newNumberFormulaArg(0)
  7521. if argsList.Len() >= 4 {
  7522. if fv = argsList.Front().Next().Next().Next().Value.(formulaArg).ToNumber(); fv.Type != ArgNumber {
  7523. return fv
  7524. }
  7525. }
  7526. if argsList.Len() == 5 {
  7527. if typ = argsList.Back().Value.(formulaArg).ToNumber(); typ.Type != ArgNumber {
  7528. return typ
  7529. }
  7530. }
  7531. if typ.Number != 0 && typ.Number != 1 {
  7532. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  7533. }
  7534. if rate.Number != 0 {
  7535. p := (-fv.Number - pv.Number*math.Pow((1+rate.Number), nper.Number)) / (1 + rate.Number*typ.Number) / ((math.Pow((1+rate.Number), nper.Number) - 1) / rate.Number)
  7536. return newNumberFormulaArg(p)
  7537. }
  7538. return newNumberFormulaArg((-pv.Number - fv.Number) / nper.Number)
  7539. }
  7540. // PPMT function calculates the payment on the principal, during a specific
  7541. // period of a loan or investment that is paid in constant periodic payments,
  7542. // with a constant interest rate. The syntax of the function is:
  7543. //
  7544. // PPMT(rate,per,nper,pv,[fv],[type])
  7545. //
  7546. func (fn *formulaFuncs) PPMT(argsList *list.List) formulaArg {
  7547. return fn.ipmt("PPMT", argsList)
  7548. }