polyclip-ts.umd.js 149 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811
  1. // polyclip-ts v0.16.8 Copyright (c) 2022 Luiz Felipe Machado Barboza
  2. (function (global, factory) {
  3. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  4. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  5. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.polyclip = global.polyclip || {}));
  6. })(this, (function (exports) { 'use strict';
  7. var version = "0.16.8";
  8. var constant = (x) => {
  9. return () => {
  10. return x;
  11. };
  12. };
  13. var compare$1 = (eps) => {
  14. const almostEqual = eps ? (a, b) => b.minus(a).abs().isLessThanOrEqualTo(eps)
  15. : constant(false);
  16. return (a, b) => {
  17. if (almostEqual(a, b))
  18. return 0;
  19. return a.comparedTo(b);
  20. };
  21. };
  22. function orient (eps) {
  23. const almostCollinear = eps ? (area2, ax, ay, cx, cy) => area2.exponentiatedBy(2).isLessThanOrEqualTo(cx.minus(ax).exponentiatedBy(2).plus(cy.minus(ay).exponentiatedBy(2))
  24. .times(eps))
  25. : constant(false);
  26. return (a, b, c) => {
  27. const ax = a.x, ay = a.y, cx = c.x, cy = c.y;
  28. const area2 = ay.minus(cy).times(b.x.minus(cx)).minus(ax.minus(cx).times(b.y.minus(cy)));
  29. if (almostCollinear(area2, ax, ay, cx, cy))
  30. return 0;
  31. return area2.comparedTo(0);
  32. };
  33. }
  34. /*
  35. * bignumber.js v9.1.0
  36. * A JavaScript library for arbitrary-precision arithmetic.
  37. * https://github.com/MikeMcl/bignumber.js
  38. * Copyright (c) 2022 Michael Mclaughlin <M8ch88l@gmail.com>
  39. * MIT Licensed.
  40. *
  41. * BigNumber.prototype methods | BigNumber methods
  42. * |
  43. * absoluteValue abs | clone
  44. * comparedTo | config set
  45. * decimalPlaces dp | DECIMAL_PLACES
  46. * dividedBy div | ROUNDING_MODE
  47. * dividedToIntegerBy idiv | EXPONENTIAL_AT
  48. * exponentiatedBy pow | RANGE
  49. * integerValue | CRYPTO
  50. * isEqualTo eq | MODULO_MODE
  51. * isFinite | POW_PRECISION
  52. * isGreaterThan gt | FORMAT
  53. * isGreaterThanOrEqualTo gte | ALPHABET
  54. * isInteger | isBigNumber
  55. * isLessThan lt | maximum max
  56. * isLessThanOrEqualTo lte | minimum min
  57. * isNaN | random
  58. * isNegative | sum
  59. * isPositive |
  60. * isZero |
  61. * minus |
  62. * modulo mod |
  63. * multipliedBy times |
  64. * negated |
  65. * plus |
  66. * precision sd |
  67. * shiftedBy |
  68. * squareRoot sqrt |
  69. * toExponential |
  70. * toFixed |
  71. * toFormat |
  72. * toFraction |
  73. * toJSON |
  74. * toNumber |
  75. * toPrecision |
  76. * toString |
  77. * valueOf |
  78. *
  79. */
  80. var
  81. isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,
  82. mathceil = Math.ceil,
  83. mathfloor = Math.floor,
  84. bignumberError = '[BigNumber Error] ',
  85. tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ',
  86. BASE = 1e14,
  87. LOG_BASE = 14,
  88. MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1
  89. // MAX_INT32 = 0x7fffffff, // 2^31 - 1
  90. POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],
  91. SQRT_BASE = 1e7,
  92. // EDITABLE
  93. // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
  94. // the arguments to toExponential, toFixed, toFormat, and toPrecision.
  95. MAX = 1E9; // 0 to MAX_INT32
  96. /*
  97. * Create and return a BigNumber constructor.
  98. */
  99. function clone(configObject) {
  100. var div, convertBase, parseNumeric,
  101. P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null },
  102. ONE = new BigNumber(1),
  103. //----------------------------- EDITABLE CONFIG DEFAULTS -------------------------------
  104. // The default values below must be integers within the inclusive ranges stated.
  105. // The values can also be changed at run-time using BigNumber.set.
  106. // The maximum number of decimal places for operations involving division.
  107. DECIMAL_PLACES = 20, // 0 to MAX
  108. // The rounding mode used when rounding to the above decimal places, and when using
  109. // toExponential, toFixed, toFormat and toPrecision, and round (default value).
  110. // UP 0 Away from zero.
  111. // DOWN 1 Towards zero.
  112. // CEIL 2 Towards +Infinity.
  113. // FLOOR 3 Towards -Infinity.
  114. // HALF_UP 4 Towards nearest neighbour. If equidistant, up.
  115. // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
  116. // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
  117. // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
  118. // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
  119. ROUNDING_MODE = 4, // 0 to 8
  120. // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
  121. // The exponent value at and beneath which toString returns exponential notation.
  122. // Number type: -7
  123. TO_EXP_NEG = -7, // 0 to -MAX
  124. // The exponent value at and above which toString returns exponential notation.
  125. // Number type: 21
  126. TO_EXP_POS = 21, // 0 to MAX
  127. // RANGE : [MIN_EXP, MAX_EXP]
  128. // The minimum exponent value, beneath which underflow to zero occurs.
  129. // Number type: -324 (5e-324)
  130. MIN_EXP = -1e7, // -1 to -MAX
  131. // The maximum exponent value, above which overflow to Infinity occurs.
  132. // Number type: 308 (1.7976931348623157e+308)
  133. // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
  134. MAX_EXP = 1e7, // 1 to MAX
  135. // Whether to use cryptographically-secure random number generation, if available.
  136. CRYPTO = false, // true or false
  137. // The modulo mode used when calculating the modulus: a mod n.
  138. // The quotient (q = a / n) is calculated according to the corresponding rounding mode.
  139. // The remainder (r) is calculated as: r = a - n * q.
  140. //
  141. // UP 0 The remainder is positive if the dividend is negative, else is negative.
  142. // DOWN 1 The remainder has the same sign as the dividend.
  143. // This modulo mode is commonly known as 'truncated division' and is
  144. // equivalent to (a % n) in JavaScript.
  145. // FLOOR 3 The remainder has the same sign as the divisor (Python %).
  146. // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
  147. // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
  148. // The remainder is always positive.
  149. //
  150. // The truncated division, floored division, Euclidian division and IEEE 754 remainder
  151. // modes are commonly used for the modulus operation.
  152. // Although the other rounding modes can also be used, they may not give useful results.
  153. MODULO_MODE = 1, // 0 to 9
  154. // The maximum number of significant digits of the result of the exponentiatedBy operation.
  155. // If POW_PRECISION is 0, there will be unlimited significant digits.
  156. POW_PRECISION = 0, // 0 to MAX
  157. // The format specification used by the BigNumber.prototype.toFormat method.
  158. FORMAT = {
  159. prefix: '',
  160. groupSize: 3,
  161. secondaryGroupSize: 0,
  162. groupSeparator: ',',
  163. decimalSeparator: '.',
  164. fractionGroupSize: 0,
  165. fractionGroupSeparator: '\xA0', // non-breaking space
  166. suffix: ''
  167. },
  168. // The alphabet used for base conversion. It must be at least 2 characters long, with no '+',
  169. // '-', '.', whitespace, or repeated character.
  170. // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'
  171. ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz',
  172. alphabetHasNormalDecimalDigits = true;
  173. //------------------------------------------------------------------------------------------
  174. // CONSTRUCTOR
  175. /*
  176. * The BigNumber constructor and exported function.
  177. * Create and return a new instance of a BigNumber object.
  178. *
  179. * v {number|string|BigNumber} A numeric value.
  180. * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive.
  181. */
  182. function BigNumber(v, b) {
  183. var alphabet, c, caseChanged, e, i, isNum, len, str,
  184. x = this;
  185. // Enable constructor call without `new`.
  186. if (!(x instanceof BigNumber)) return new BigNumber(v, b);
  187. if (b == null) {
  188. if (v && v._isBigNumber === true) {
  189. x.s = v.s;
  190. if (!v.c || v.e > MAX_EXP) {
  191. x.c = x.e = null;
  192. } else if (v.e < MIN_EXP) {
  193. x.c = [x.e = 0];
  194. } else {
  195. x.e = v.e;
  196. x.c = v.c.slice();
  197. }
  198. return;
  199. }
  200. if ((isNum = typeof v == 'number') && v * 0 == 0) {
  201. // Use `1 / n` to handle minus zero also.
  202. x.s = 1 / v < 0 ? (v = -v, -1) : 1;
  203. // Fast path for integers, where n < 2147483648 (2**31).
  204. if (v === ~~v) {
  205. for (e = 0, i = v; i >= 10; i /= 10, e++);
  206. if (e > MAX_EXP) {
  207. x.c = x.e = null;
  208. } else {
  209. x.e = e;
  210. x.c = [v];
  211. }
  212. return;
  213. }
  214. str = String(v);
  215. } else {
  216. if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum);
  217. x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;
  218. }
  219. // Decimal point?
  220. if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
  221. // Exponential form?
  222. if ((i = str.search(/e/i)) > 0) {
  223. // Determine exponent.
  224. if (e < 0) e = i;
  225. e += +str.slice(i + 1);
  226. str = str.substring(0, i);
  227. } else if (e < 0) {
  228. // Integer.
  229. e = str.length;
  230. }
  231. } else {
  232. // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'
  233. intCheck(b, 2, ALPHABET.length, 'Base');
  234. // Allow exponential notation to be used with base 10 argument, while
  235. // also rounding to DECIMAL_PLACES as with other bases.
  236. if (b == 10 && alphabetHasNormalDecimalDigits) {
  237. x = new BigNumber(v);
  238. return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);
  239. }
  240. str = String(v);
  241. if (isNum = typeof v == 'number') {
  242. // Avoid potential interpretation of Infinity and NaN as base 44+ values.
  243. if (v * 0 != 0) return parseNumeric(x, str, isNum, b);
  244. x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1;
  245. // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'
  246. if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) {
  247. throw Error
  248. (tooManyDigits + v);
  249. }
  250. } else {
  251. x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;
  252. }
  253. alphabet = ALPHABET.slice(0, b);
  254. e = i = 0;
  255. // Check that str is a valid base b number.
  256. // Don't use RegExp, so alphabet can contain special characters.
  257. for (len = str.length; i < len; i++) {
  258. if (alphabet.indexOf(c = str.charAt(i)) < 0) {
  259. if (c == '.') {
  260. // If '.' is not the first character and it has not be found before.
  261. if (i > e) {
  262. e = len;
  263. continue;
  264. }
  265. } else if (!caseChanged) {
  266. // Allow e.g. hexadecimal 'FF' as well as 'ff'.
  267. if (str == str.toUpperCase() && (str = str.toLowerCase()) ||
  268. str == str.toLowerCase() && (str = str.toUpperCase())) {
  269. caseChanged = true;
  270. i = -1;
  271. e = 0;
  272. continue;
  273. }
  274. }
  275. return parseNumeric(x, String(v), isNum, b);
  276. }
  277. }
  278. // Prevent later check for length on converted number.
  279. isNum = false;
  280. str = convertBase(str, b, 10, x.s);
  281. // Decimal point?
  282. if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
  283. else e = str.length;
  284. }
  285. // Determine leading zeros.
  286. for (i = 0; str.charCodeAt(i) === 48; i++);
  287. // Determine trailing zeros.
  288. for (len = str.length; str.charCodeAt(--len) === 48;);
  289. if (str = str.slice(i, ++len)) {
  290. len -= i;
  291. // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'
  292. if (isNum && BigNumber.DEBUG &&
  293. len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) {
  294. throw Error
  295. (tooManyDigits + (x.s * v));
  296. }
  297. // Overflow?
  298. if ((e = e - i - 1) > MAX_EXP) {
  299. // Infinity.
  300. x.c = x.e = null;
  301. // Underflow?
  302. } else if (e < MIN_EXP) {
  303. // Zero.
  304. x.c = [x.e = 0];
  305. } else {
  306. x.e = e;
  307. x.c = [];
  308. // Transform base
  309. // e is the base 10 exponent.
  310. // i is where to slice str to get the first element of the coefficient array.
  311. i = (e + 1) % LOG_BASE;
  312. if (e < 0) i += LOG_BASE; // i < 1
  313. if (i < len) {
  314. if (i) x.c.push(+str.slice(0, i));
  315. for (len -= LOG_BASE; i < len;) {
  316. x.c.push(+str.slice(i, i += LOG_BASE));
  317. }
  318. i = LOG_BASE - (str = str.slice(i)).length;
  319. } else {
  320. i -= len;
  321. }
  322. for (; i--; str += '0');
  323. x.c.push(+str);
  324. }
  325. } else {
  326. // Zero.
  327. x.c = [x.e = 0];
  328. }
  329. }
  330. // CONSTRUCTOR PROPERTIES
  331. BigNumber.clone = clone;
  332. BigNumber.ROUND_UP = 0;
  333. BigNumber.ROUND_DOWN = 1;
  334. BigNumber.ROUND_CEIL = 2;
  335. BigNumber.ROUND_FLOOR = 3;
  336. BigNumber.ROUND_HALF_UP = 4;
  337. BigNumber.ROUND_HALF_DOWN = 5;
  338. BigNumber.ROUND_HALF_EVEN = 6;
  339. BigNumber.ROUND_HALF_CEIL = 7;
  340. BigNumber.ROUND_HALF_FLOOR = 8;
  341. BigNumber.EUCLID = 9;
  342. /*
  343. * Configure infrequently-changing library-wide settings.
  344. *
  345. * Accept an object with the following optional properties (if the value of a property is
  346. * a number, it must be an integer within the inclusive range stated):
  347. *
  348. * DECIMAL_PLACES {number} 0 to MAX
  349. * ROUNDING_MODE {number} 0 to 8
  350. * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX]
  351. * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX]
  352. * CRYPTO {boolean} true or false
  353. * MODULO_MODE {number} 0 to 9
  354. * POW_PRECISION {number} 0 to MAX
  355. * ALPHABET {string} A string of two or more unique characters which does
  356. * not contain '.'.
  357. * FORMAT {object} An object with some of the following properties:
  358. * prefix {string}
  359. * groupSize {number}
  360. * secondaryGroupSize {number}
  361. * groupSeparator {string}
  362. * decimalSeparator {string}
  363. * fractionGroupSize {number}
  364. * fractionGroupSeparator {string}
  365. * suffix {string}
  366. *
  367. * (The values assigned to the above FORMAT object properties are not checked for validity.)
  368. *
  369. * E.g.
  370. * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
  371. *
  372. * Ignore properties/parameters set to null or undefined, except for ALPHABET.
  373. *
  374. * Return an object with the properties current values.
  375. */
  376. BigNumber.config = BigNumber.set = function (obj) {
  377. var p, v;
  378. if (obj != null) {
  379. if (typeof obj == 'object') {
  380. // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
  381. // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}'
  382. if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) {
  383. v = obj[p];
  384. intCheck(v, 0, MAX, p);
  385. DECIMAL_PLACES = v;
  386. }
  387. // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
  388. // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}'
  389. if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) {
  390. v = obj[p];
  391. intCheck(v, 0, 8, p);
  392. ROUNDING_MODE = v;
  393. }
  394. // EXPONENTIAL_AT {number|number[]}
  395. // Integer, -MAX to MAX inclusive or
  396. // [integer -MAX to 0 inclusive, 0 to MAX inclusive].
  397. // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}'
  398. if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) {
  399. v = obj[p];
  400. if (v && v.pop) {
  401. intCheck(v[0], -MAX, 0, p);
  402. intCheck(v[1], 0, MAX, p);
  403. TO_EXP_NEG = v[0];
  404. TO_EXP_POS = v[1];
  405. } else {
  406. intCheck(v, -MAX, MAX, p);
  407. TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);
  408. }
  409. }
  410. // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
  411. // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
  412. // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}'
  413. if (obj.hasOwnProperty(p = 'RANGE')) {
  414. v = obj[p];
  415. if (v && v.pop) {
  416. intCheck(v[0], -MAX, -1, p);
  417. intCheck(v[1], 1, MAX, p);
  418. MIN_EXP = v[0];
  419. MAX_EXP = v[1];
  420. } else {
  421. intCheck(v, -MAX, MAX, p);
  422. if (v) {
  423. MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);
  424. } else {
  425. throw Error
  426. (bignumberError + p + ' cannot be zero: ' + v);
  427. }
  428. }
  429. }
  430. // CRYPTO {boolean} true or false.
  431. // '[BigNumber Error] CRYPTO not true or false: {v}'
  432. // '[BigNumber Error] crypto unavailable'
  433. if (obj.hasOwnProperty(p = 'CRYPTO')) {
  434. v = obj[p];
  435. if (v === !!v) {
  436. if (v) {
  437. if (typeof crypto != 'undefined' && crypto &&
  438. (crypto.getRandomValues || crypto.randomBytes)) {
  439. CRYPTO = v;
  440. } else {
  441. CRYPTO = !v;
  442. throw Error
  443. (bignumberError + 'crypto unavailable');
  444. }
  445. } else {
  446. CRYPTO = v;
  447. }
  448. } else {
  449. throw Error
  450. (bignumberError + p + ' not true or false: ' + v);
  451. }
  452. }
  453. // MODULO_MODE {number} Integer, 0 to 9 inclusive.
  454. // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}'
  455. if (obj.hasOwnProperty(p = 'MODULO_MODE')) {
  456. v = obj[p];
  457. intCheck(v, 0, 9, p);
  458. MODULO_MODE = v;
  459. }
  460. // POW_PRECISION {number} Integer, 0 to MAX inclusive.
  461. // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}'
  462. if (obj.hasOwnProperty(p = 'POW_PRECISION')) {
  463. v = obj[p];
  464. intCheck(v, 0, MAX, p);
  465. POW_PRECISION = v;
  466. }
  467. // FORMAT {object}
  468. // '[BigNumber Error] FORMAT not an object: {v}'
  469. if (obj.hasOwnProperty(p = 'FORMAT')) {
  470. v = obj[p];
  471. if (typeof v == 'object') FORMAT = v;
  472. else throw Error
  473. (bignumberError + p + ' not an object: ' + v);
  474. }
  475. // ALPHABET {string}
  476. // '[BigNumber Error] ALPHABET invalid: {v}'
  477. if (obj.hasOwnProperty(p = 'ALPHABET')) {
  478. v = obj[p];
  479. // Disallow if less than two characters,
  480. // or if it contains '+', '-', '.', whitespace, or a repeated character.
  481. if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) {
  482. alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789';
  483. ALPHABET = v;
  484. } else {
  485. throw Error
  486. (bignumberError + p + ' invalid: ' + v);
  487. }
  488. }
  489. } else {
  490. // '[BigNumber Error] Object expected: {v}'
  491. throw Error
  492. (bignumberError + 'Object expected: ' + obj);
  493. }
  494. }
  495. return {
  496. DECIMAL_PLACES: DECIMAL_PLACES,
  497. ROUNDING_MODE: ROUNDING_MODE,
  498. EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],
  499. RANGE: [MIN_EXP, MAX_EXP],
  500. CRYPTO: CRYPTO,
  501. MODULO_MODE: MODULO_MODE,
  502. POW_PRECISION: POW_PRECISION,
  503. FORMAT: FORMAT,
  504. ALPHABET: ALPHABET
  505. };
  506. };
  507. /*
  508. * Return true if v is a BigNumber instance, otherwise return false.
  509. *
  510. * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed.
  511. *
  512. * v {any}
  513. *
  514. * '[BigNumber Error] Invalid BigNumber: {v}'
  515. */
  516. BigNumber.isBigNumber = function (v) {
  517. if (!v || v._isBigNumber !== true) return false;
  518. if (!BigNumber.DEBUG) return true;
  519. var i, n,
  520. c = v.c,
  521. e = v.e,
  522. s = v.s;
  523. out: if ({}.toString.call(c) == '[object Array]') {
  524. if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) {
  525. // If the first element is zero, the BigNumber value must be zero.
  526. if (c[0] === 0) {
  527. if (e === 0 && c.length === 1) return true;
  528. break out;
  529. }
  530. // Calculate number of digits that c[0] should have, based on the exponent.
  531. i = (e + 1) % LOG_BASE;
  532. if (i < 1) i += LOG_BASE;
  533. // Calculate number of digits of c[0].
  534. //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) {
  535. if (String(c[0]).length == i) {
  536. for (i = 0; i < c.length; i++) {
  537. n = c[i];
  538. if (n < 0 || n >= BASE || n !== mathfloor(n)) break out;
  539. }
  540. // Last element cannot be zero, unless it is the only element.
  541. if (n !== 0) return true;
  542. }
  543. }
  544. // Infinity/NaN
  545. } else if (c === null && e === null && (s === null || s === 1 || s === -1)) {
  546. return true;
  547. }
  548. throw Error
  549. (bignumberError + 'Invalid BigNumber: ' + v);
  550. };
  551. /*
  552. * Return a new BigNumber whose value is the maximum of the arguments.
  553. *
  554. * arguments {number|string|BigNumber}
  555. */
  556. BigNumber.maximum = BigNumber.max = function () {
  557. return maxOrMin(arguments, P.lt);
  558. };
  559. /*
  560. * Return a new BigNumber whose value is the minimum of the arguments.
  561. *
  562. * arguments {number|string|BigNumber}
  563. */
  564. BigNumber.minimum = BigNumber.min = function () {
  565. return maxOrMin(arguments, P.gt);
  566. };
  567. /*
  568. * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
  569. * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
  570. * zeros are produced).
  571. *
  572. * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
  573. *
  574. * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}'
  575. * '[BigNumber Error] crypto unavailable'
  576. */
  577. BigNumber.random = (function () {
  578. var pow2_53 = 0x20000000000000;
  579. // Return a 53 bit integer n, where 0 <= n < 9007199254740992.
  580. // Check if Math.random() produces more than 32 bits of randomness.
  581. // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
  582. // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
  583. var random53bitInt = (Math.random() * pow2_53) & 0x1fffff
  584. ? function () { return mathfloor(Math.random() * pow2_53); }
  585. : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +
  586. (Math.random() * 0x800000 | 0); };
  587. return function (dp) {
  588. var a, b, e, k, v,
  589. i = 0,
  590. c = [],
  591. rand = new BigNumber(ONE);
  592. if (dp == null) dp = DECIMAL_PLACES;
  593. else intCheck(dp, 0, MAX);
  594. k = mathceil(dp / LOG_BASE);
  595. if (CRYPTO) {
  596. // Browsers supporting crypto.getRandomValues.
  597. if (crypto.getRandomValues) {
  598. a = crypto.getRandomValues(new Uint32Array(k *= 2));
  599. for (; i < k;) {
  600. // 53 bits:
  601. // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
  602. // 11111 11111111 11111111 11111111 11100000 00000000 00000000
  603. // ((Math.pow(2, 32) - 1) >>> 11).toString(2)
  604. // 11111 11111111 11111111
  605. // 0x20000 is 2^21.
  606. v = a[i] * 0x20000 + (a[i + 1] >>> 11);
  607. // Rejection sampling:
  608. // 0 <= v < 9007199254740992
  609. // Probability that v >= 9e15, is
  610. // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
  611. if (v >= 9e15) {
  612. b = crypto.getRandomValues(new Uint32Array(2));
  613. a[i] = b[0];
  614. a[i + 1] = b[1];
  615. } else {
  616. // 0 <= v <= 8999999999999999
  617. // 0 <= (v % 1e14) <= 99999999999999
  618. c.push(v % 1e14);
  619. i += 2;
  620. }
  621. }
  622. i = k / 2;
  623. // Node.js supporting crypto.randomBytes.
  624. } else if (crypto.randomBytes) {
  625. // buffer
  626. a = crypto.randomBytes(k *= 7);
  627. for (; i < k;) {
  628. // 0x1000000000000 is 2^48, 0x10000000000 is 2^40
  629. // 0x100000000 is 2^32, 0x1000000 is 2^24
  630. // 11111 11111111 11111111 11111111 11111111 11111111 11111111
  631. // 0 <= v < 9007199254740992
  632. v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) +
  633. (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) +
  634. (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6];
  635. if (v >= 9e15) {
  636. crypto.randomBytes(7).copy(a, i);
  637. } else {
  638. // 0 <= (v % 1e14) <= 99999999999999
  639. c.push(v % 1e14);
  640. i += 7;
  641. }
  642. }
  643. i = k / 7;
  644. } else {
  645. CRYPTO = false;
  646. throw Error
  647. (bignumberError + 'crypto unavailable');
  648. }
  649. }
  650. // Use Math.random.
  651. if (!CRYPTO) {
  652. for (; i < k;) {
  653. v = random53bitInt();
  654. if (v < 9e15) c[i++] = v % 1e14;
  655. }
  656. }
  657. k = c[--i];
  658. dp %= LOG_BASE;
  659. // Convert trailing digits to zeros according to dp.
  660. if (k && dp) {
  661. v = POWS_TEN[LOG_BASE - dp];
  662. c[i] = mathfloor(k / v) * v;
  663. }
  664. // Remove trailing elements which are zero.
  665. for (; c[i] === 0; c.pop(), i--);
  666. // Zero?
  667. if (i < 0) {
  668. c = [e = 0];
  669. } else {
  670. // Remove leading elements which are zero and adjust exponent accordingly.
  671. for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);
  672. // Count the digits of the first element of c to determine leading zeros, and...
  673. for (i = 1, v = c[0]; v >= 10; v /= 10, i++);
  674. // adjust the exponent accordingly.
  675. if (i < LOG_BASE) e -= LOG_BASE - i;
  676. }
  677. rand.e = e;
  678. rand.c = c;
  679. return rand;
  680. };
  681. })();
  682. /*
  683. * Return a BigNumber whose value is the sum of the arguments.
  684. *
  685. * arguments {number|string|BigNumber}
  686. */
  687. BigNumber.sum = function () {
  688. var i = 1,
  689. args = arguments,
  690. sum = new BigNumber(args[0]);
  691. for (; i < args.length;) sum = sum.plus(args[i++]);
  692. return sum;
  693. };
  694. // PRIVATE FUNCTIONS
  695. // Called by BigNumber and BigNumber.prototype.toString.
  696. convertBase = (function () {
  697. var decimal = '0123456789';
  698. /*
  699. * Convert string of baseIn to an array of numbers of baseOut.
  700. * Eg. toBaseOut('255', 10, 16) returns [15, 15].
  701. * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5].
  702. */
  703. function toBaseOut(str, baseIn, baseOut, alphabet) {
  704. var j,
  705. arr = [0],
  706. arrL,
  707. i = 0,
  708. len = str.length;
  709. for (; i < len;) {
  710. for (arrL = arr.length; arrL--; arr[arrL] *= baseIn);
  711. arr[0] += alphabet.indexOf(str.charAt(i++));
  712. for (j = 0; j < arr.length; j++) {
  713. if (arr[j] > baseOut - 1) {
  714. if (arr[j + 1] == null) arr[j + 1] = 0;
  715. arr[j + 1] += arr[j] / baseOut | 0;
  716. arr[j] %= baseOut;
  717. }
  718. }
  719. }
  720. return arr.reverse();
  721. }
  722. // Convert a numeric string of baseIn to a numeric string of baseOut.
  723. // If the caller is toString, we are converting from base 10 to baseOut.
  724. // If the caller is BigNumber, we are converting from baseIn to base 10.
  725. return function (str, baseIn, baseOut, sign, callerIsToString) {
  726. var alphabet, d, e, k, r, x, xc, y,
  727. i = str.indexOf('.'),
  728. dp = DECIMAL_PLACES,
  729. rm = ROUNDING_MODE;
  730. // Non-integer.
  731. if (i >= 0) {
  732. k = POW_PRECISION;
  733. // Unlimited precision.
  734. POW_PRECISION = 0;
  735. str = str.replace('.', '');
  736. y = new BigNumber(baseIn);
  737. x = y.pow(str.length - i);
  738. POW_PRECISION = k;
  739. // Convert str as if an integer, then restore the fraction part by dividing the
  740. // result by its base raised to a power.
  741. y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'),
  742. 10, baseOut, decimal);
  743. y.e = y.c.length;
  744. }
  745. // Convert the number as integer.
  746. xc = toBaseOut(str, baseIn, baseOut, callerIsToString
  747. ? (alphabet = ALPHABET, decimal)
  748. : (alphabet = decimal, ALPHABET));
  749. // xc now represents str as an integer and converted to baseOut. e is the exponent.
  750. e = k = xc.length;
  751. // Remove trailing zeros.
  752. for (; xc[--k] == 0; xc.pop());
  753. // Zero?
  754. if (!xc[0]) return alphabet.charAt(0);
  755. // Does str represent an integer? If so, no need for the division.
  756. if (i < 0) {
  757. --e;
  758. } else {
  759. x.c = xc;
  760. x.e = e;
  761. // The sign is needed for correct rounding.
  762. x.s = sign;
  763. x = div(x, y, dp, rm, baseOut);
  764. xc = x.c;
  765. r = x.r;
  766. e = x.e;
  767. }
  768. // xc now represents str converted to baseOut.
  769. // THe index of the rounding digit.
  770. d = e + dp + 1;
  771. // The rounding digit: the digit to the right of the digit that may be rounded up.
  772. i = xc[d];
  773. // Look at the rounding digits and mode to determine whether to round up.
  774. k = baseOut / 2;
  775. r = r || d < 0 || xc[d + 1] != null;
  776. r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))
  777. : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||
  778. rm == (x.s < 0 ? 8 : 7));
  779. // If the index of the rounding digit is not greater than zero, or xc represents
  780. // zero, then the result of the base conversion is zero or, if rounding up, a value
  781. // such as 0.00001.
  782. if (d < 1 || !xc[0]) {
  783. // 1^-dp or 0
  784. str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0);
  785. } else {
  786. // Truncate xc to the required number of decimal places.
  787. xc.length = d;
  788. // Round up?
  789. if (r) {
  790. // Rounding up may mean the previous digit has to be rounded up and so on.
  791. for (--baseOut; ++xc[--d] > baseOut;) {
  792. xc[d] = 0;
  793. if (!d) {
  794. ++e;
  795. xc = [1].concat(xc);
  796. }
  797. }
  798. }
  799. // Determine trailing zeros.
  800. for (k = xc.length; !xc[--k];);
  801. // E.g. [4, 11, 15] becomes 4bf.
  802. for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++]));
  803. // Add leading zeros, decimal point and trailing zeros as required.
  804. str = toFixedPoint(str, e, alphabet.charAt(0));
  805. }
  806. // The caller will add the sign.
  807. return str;
  808. };
  809. })();
  810. // Perform division in the specified base. Called by div and convertBase.
  811. div = (function () {
  812. // Assume non-zero x and k.
  813. function multiply(x, k, base) {
  814. var m, temp, xlo, xhi,
  815. carry = 0,
  816. i = x.length,
  817. klo = k % SQRT_BASE,
  818. khi = k / SQRT_BASE | 0;
  819. for (x = x.slice(); i--;) {
  820. xlo = x[i] % SQRT_BASE;
  821. xhi = x[i] / SQRT_BASE | 0;
  822. m = khi * xlo + xhi * klo;
  823. temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;
  824. carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;
  825. x[i] = temp % base;
  826. }
  827. if (carry) x = [carry].concat(x);
  828. return x;
  829. }
  830. function compare(a, b, aL, bL) {
  831. var i, cmp;
  832. if (aL != bL) {
  833. cmp = aL > bL ? 1 : -1;
  834. } else {
  835. for (i = cmp = 0; i < aL; i++) {
  836. if (a[i] != b[i]) {
  837. cmp = a[i] > b[i] ? 1 : -1;
  838. break;
  839. }
  840. }
  841. }
  842. return cmp;
  843. }
  844. function subtract(a, b, aL, base) {
  845. var i = 0;
  846. // Subtract b from a.
  847. for (; aL--;) {
  848. a[aL] -= i;
  849. i = a[aL] < b[aL] ? 1 : 0;
  850. a[aL] = i * base + a[aL] - b[aL];
  851. }
  852. // Remove leading zeros.
  853. for (; !a[0] && a.length > 1; a.splice(0, 1));
  854. }
  855. // x: dividend, y: divisor.
  856. return function (x, y, dp, rm, base) {
  857. var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,
  858. yL, yz,
  859. s = x.s == y.s ? 1 : -1,
  860. xc = x.c,
  861. yc = y.c;
  862. // Either NaN, Infinity or 0?
  863. if (!xc || !xc[0] || !yc || !yc[0]) {
  864. return new BigNumber(
  865. // Return NaN if either NaN, or both Infinity or 0.
  866. !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN :
  867. // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
  868. xc && xc[0] == 0 || !yc ? s * 0 : s / 0
  869. );
  870. }
  871. q = new BigNumber(s);
  872. qc = q.c = [];
  873. e = x.e - y.e;
  874. s = dp + e + 1;
  875. if (!base) {
  876. base = BASE;
  877. e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE);
  878. s = s / LOG_BASE | 0;
  879. }
  880. // Result exponent may be one less then the current value of e.
  881. // The coefficients of the BigNumbers from convertBase may have trailing zeros.
  882. for (i = 0; yc[i] == (xc[i] || 0); i++);
  883. if (yc[i] > (xc[i] || 0)) e--;
  884. if (s < 0) {
  885. qc.push(1);
  886. more = true;
  887. } else {
  888. xL = xc.length;
  889. yL = yc.length;
  890. i = 0;
  891. s += 2;
  892. // Normalise xc and yc so highest order digit of yc is >= base / 2.
  893. n = mathfloor(base / (yc[0] + 1));
  894. // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1.
  895. // if (n > 1 || n++ == 1 && yc[0] < base / 2) {
  896. if (n > 1) {
  897. yc = multiply(yc, n, base);
  898. xc = multiply(xc, n, base);
  899. yL = yc.length;
  900. xL = xc.length;
  901. }
  902. xi = yL;
  903. rem = xc.slice(0, yL);
  904. remL = rem.length;
  905. // Add zeros to make remainder as long as divisor.
  906. for (; remL < yL; rem[remL++] = 0);
  907. yz = yc.slice();
  908. yz = [0].concat(yz);
  909. yc0 = yc[0];
  910. if (yc[1] >= base / 2) yc0++;
  911. // Not necessary, but to prevent trial digit n > base, when using base 3.
  912. // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15;
  913. do {
  914. n = 0;
  915. // Compare divisor and remainder.
  916. cmp = compare(yc, rem, yL, remL);
  917. // If divisor < remainder.
  918. if (cmp < 0) {
  919. // Calculate trial digit, n.
  920. rem0 = rem[0];
  921. if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);
  922. // n is how many times the divisor goes into the current remainder.
  923. n = mathfloor(rem0 / yc0);
  924. // Algorithm:
  925. // product = divisor multiplied by trial digit (n).
  926. // Compare product and remainder.
  927. // If product is greater than remainder:
  928. // Subtract divisor from product, decrement trial digit.
  929. // Subtract product from remainder.
  930. // If product was less than remainder at the last compare:
  931. // Compare new remainder and divisor.
  932. // If remainder is greater than divisor:
  933. // Subtract divisor from remainder, increment trial digit.
  934. if (n > 1) {
  935. // n may be > base only when base is 3.
  936. if (n >= base) n = base - 1;
  937. // product = divisor * trial digit.
  938. prod = multiply(yc, n, base);
  939. prodL = prod.length;
  940. remL = rem.length;
  941. // Compare product and remainder.
  942. // If product > remainder then trial digit n too high.
  943. // n is 1 too high about 5% of the time, and is not known to have
  944. // ever been more than 1 too high.
  945. while (compare(prod, rem, prodL, remL) == 1) {
  946. n--;
  947. // Subtract divisor from product.
  948. subtract(prod, yL < prodL ? yz : yc, prodL, base);
  949. prodL = prod.length;
  950. cmp = 1;
  951. }
  952. } else {
  953. // n is 0 or 1, cmp is -1.
  954. // If n is 0, there is no need to compare yc and rem again below,
  955. // so change cmp to 1 to avoid it.
  956. // If n is 1, leave cmp as -1, so yc and rem are compared again.
  957. if (n == 0) {
  958. // divisor < remainder, so n must be at least 1.
  959. cmp = n = 1;
  960. }
  961. // product = divisor
  962. prod = yc.slice();
  963. prodL = prod.length;
  964. }
  965. if (prodL < remL) prod = [0].concat(prod);
  966. // Subtract product from remainder.
  967. subtract(rem, prod, remL, base);
  968. remL = rem.length;
  969. // If product was < remainder.
  970. if (cmp == -1) {
  971. // Compare divisor and new remainder.
  972. // If divisor < new remainder, subtract divisor from remainder.
  973. // Trial digit n too low.
  974. // n is 1 too low about 5% of the time, and very rarely 2 too low.
  975. while (compare(yc, rem, yL, remL) < 1) {
  976. n++;
  977. // Subtract divisor from remainder.
  978. subtract(rem, yL < remL ? yz : yc, remL, base);
  979. remL = rem.length;
  980. }
  981. }
  982. } else if (cmp === 0) {
  983. n++;
  984. rem = [0];
  985. } // else cmp === 1 and n will be 0
  986. // Add the next digit, n, to the result array.
  987. qc[i++] = n;
  988. // Update the remainder.
  989. if (rem[0]) {
  990. rem[remL++] = xc[xi] || 0;
  991. } else {
  992. rem = [xc[xi]];
  993. remL = 1;
  994. }
  995. } while ((xi++ < xL || rem[0] != null) && s--);
  996. more = rem[0] != null;
  997. // Leading zero?
  998. if (!qc[0]) qc.splice(0, 1);
  999. }
  1000. if (base == BASE) {
  1001. // To calculate q.e, first get the number of digits of qc[0].
  1002. for (i = 1, s = qc[0]; s >= 10; s /= 10, i++);
  1003. round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more);
  1004. // Caller is convertBase.
  1005. } else {
  1006. q.e = e;
  1007. q.r = +more;
  1008. }
  1009. return q;
  1010. };
  1011. })();
  1012. /*
  1013. * Return a string representing the value of BigNumber n in fixed-point or exponential
  1014. * notation rounded to the specified decimal places or significant digits.
  1015. *
  1016. * n: a BigNumber.
  1017. * i: the index of the last digit required (i.e. the digit that may be rounded up).
  1018. * rm: the rounding mode.
  1019. * id: 1 (toExponential) or 2 (toPrecision).
  1020. */
  1021. function format(n, i, rm, id) {
  1022. var c0, e, ne, len, str;
  1023. if (rm == null) rm = ROUNDING_MODE;
  1024. else intCheck(rm, 0, 8);
  1025. if (!n.c) return n.toString();
  1026. c0 = n.c[0];
  1027. ne = n.e;
  1028. if (i == null) {
  1029. str = coeffToString(n.c);
  1030. str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS)
  1031. ? toExponential(str, ne)
  1032. : toFixedPoint(str, ne, '0');
  1033. } else {
  1034. n = round(new BigNumber(n), i, rm);
  1035. // n.e may have changed if the value was rounded up.
  1036. e = n.e;
  1037. str = coeffToString(n.c);
  1038. len = str.length;
  1039. // toPrecision returns exponential notation if the number of significant digits
  1040. // specified is less than the number of digits necessary to represent the integer
  1041. // part of the value in fixed-point notation.
  1042. // Exponential notation.
  1043. if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) {
  1044. // Append zeros?
  1045. for (; len < i; str += '0', len++);
  1046. str = toExponential(str, e);
  1047. // Fixed-point notation.
  1048. } else {
  1049. i -= ne;
  1050. str = toFixedPoint(str, e, '0');
  1051. // Append zeros?
  1052. if (e + 1 > len) {
  1053. if (--i > 0) for (str += '.'; i--; str += '0');
  1054. } else {
  1055. i += e - len;
  1056. if (i > 0) {
  1057. if (e + 1 == len) str += '.';
  1058. for (; i--; str += '0');
  1059. }
  1060. }
  1061. }
  1062. }
  1063. return n.s < 0 && c0 ? '-' + str : str;
  1064. }
  1065. // Handle BigNumber.max and BigNumber.min.
  1066. function maxOrMin(args, method) {
  1067. var n,
  1068. i = 1,
  1069. m = new BigNumber(args[0]);
  1070. for (; i < args.length; i++) {
  1071. n = new BigNumber(args[i]);
  1072. // If any number is NaN, return NaN.
  1073. if (!n.s) {
  1074. m = n;
  1075. break;
  1076. } else if (method.call(m, n)) {
  1077. m = n;
  1078. }
  1079. }
  1080. return m;
  1081. }
  1082. /*
  1083. * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.
  1084. * Called by minus, plus and times.
  1085. */
  1086. function normalise(n, c, e) {
  1087. var i = 1,
  1088. j = c.length;
  1089. // Remove trailing zeros.
  1090. for (; !c[--j]; c.pop());
  1091. // Calculate the base 10 exponent. First get the number of digits of c[0].
  1092. for (j = c[0]; j >= 10; j /= 10, i++);
  1093. // Overflow?
  1094. if ((e = i + e * LOG_BASE - 1) > MAX_EXP) {
  1095. // Infinity.
  1096. n.c = n.e = null;
  1097. // Underflow?
  1098. } else if (e < MIN_EXP) {
  1099. // Zero.
  1100. n.c = [n.e = 0];
  1101. } else {
  1102. n.e = e;
  1103. n.c = c;
  1104. }
  1105. return n;
  1106. }
  1107. // Handle values that fail the validity test in BigNumber.
  1108. parseNumeric = (function () {
  1109. var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i,
  1110. dotAfter = /^([^.]+)\.$/,
  1111. dotBefore = /^\.([^.]+)$/,
  1112. isInfinityOrNaN = /^-?(Infinity|NaN)$/,
  1113. whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
  1114. return function (x, str, isNum, b) {
  1115. var base,
  1116. s = isNum ? str : str.replace(whitespaceOrPlus, '');
  1117. // No exception on ±Infinity or NaN.
  1118. if (isInfinityOrNaN.test(s)) {
  1119. x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
  1120. } else {
  1121. if (!isNum) {
  1122. // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i
  1123. s = s.replace(basePrefix, function (m, p1, p2) {
  1124. base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8;
  1125. return !b || b == base ? p1 : m;
  1126. });
  1127. if (b) {
  1128. base = b;
  1129. // E.g. '1.' to '1', '.1' to '0.1'
  1130. s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1');
  1131. }
  1132. if (str != s) return new BigNumber(s, base);
  1133. }
  1134. // '[BigNumber Error] Not a number: {n}'
  1135. // '[BigNumber Error] Not a base {b} number: {n}'
  1136. if (BigNumber.DEBUG) {
  1137. throw Error
  1138. (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str);
  1139. }
  1140. // NaN
  1141. x.s = null;
  1142. }
  1143. x.c = x.e = null;
  1144. }
  1145. })();
  1146. /*
  1147. * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
  1148. * If r is truthy, it is known that there are more digits after the rounding digit.
  1149. */
  1150. function round(x, sd, rm, r) {
  1151. var d, i, j, k, n, ni, rd,
  1152. xc = x.c,
  1153. pows10 = POWS_TEN;
  1154. // if x is not Infinity or NaN...
  1155. if (xc) {
  1156. // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.
  1157. // n is a base 1e14 number, the value of the element of array x.c containing rd.
  1158. // ni is the index of n within x.c.
  1159. // d is the number of digits of n.
  1160. // i is the index of rd within n including leading zeros.
  1161. // j is the actual index of rd within n (if < 0, rd is a leading zero).
  1162. out: {
  1163. // Get the number of digits of the first element of xc.
  1164. for (d = 1, k = xc[0]; k >= 10; k /= 10, d++);
  1165. i = sd - d;
  1166. // If the rounding digit is in the first element of xc...
  1167. if (i < 0) {
  1168. i += LOG_BASE;
  1169. j = sd;
  1170. n = xc[ni = 0];
  1171. // Get the rounding digit at index j of n.
  1172. rd = n / pows10[d - j - 1] % 10 | 0;
  1173. } else {
  1174. ni = mathceil((i + 1) / LOG_BASE);
  1175. if (ni >= xc.length) {
  1176. if (r) {
  1177. // Needed by sqrt.
  1178. for (; xc.length <= ni; xc.push(0));
  1179. n = rd = 0;
  1180. d = 1;
  1181. i %= LOG_BASE;
  1182. j = i - LOG_BASE + 1;
  1183. } else {
  1184. break out;
  1185. }
  1186. } else {
  1187. n = k = xc[ni];
  1188. // Get the number of digits of n.
  1189. for (d = 1; k >= 10; k /= 10, d++);
  1190. // Get the index of rd within n.
  1191. i %= LOG_BASE;
  1192. // Get the index of rd within n, adjusted for leading zeros.
  1193. // The number of leading zeros of n is given by LOG_BASE - d.
  1194. j = i - LOG_BASE + d;
  1195. // Get the rounding digit at index j of n.
  1196. rd = j < 0 ? 0 : n / pows10[d - j - 1] % 10 | 0;
  1197. }
  1198. }
  1199. r = r || sd < 0 ||
  1200. // Are there any non-zero digits after the rounding digit?
  1201. // The expression n % pows10[d - j - 1] returns all digits of n to the right
  1202. // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
  1203. xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]);
  1204. r = rm < 4
  1205. ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))
  1206. : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 &&
  1207. // Check whether the digit to the left of the rounding digit is odd.
  1208. ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 ||
  1209. rm == (x.s < 0 ? 8 : 7));
  1210. if (sd < 1 || !xc[0]) {
  1211. xc.length = 0;
  1212. if (r) {
  1213. // Convert sd to decimal places.
  1214. sd -= x.e + 1;
  1215. // 1, 0.1, 0.01, 0.001, 0.0001 etc.
  1216. xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];
  1217. x.e = -sd || 0;
  1218. } else {
  1219. // Zero.
  1220. xc[0] = x.e = 0;
  1221. }
  1222. return x;
  1223. }
  1224. // Remove excess digits.
  1225. if (i == 0) {
  1226. xc.length = ni;
  1227. k = 1;
  1228. ni--;
  1229. } else {
  1230. xc.length = ni + 1;
  1231. k = pows10[LOG_BASE - i];
  1232. // E.g. 56700 becomes 56000 if 7 is the rounding digit.
  1233. // j > 0 means i > number of leading zeros of n.
  1234. xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0;
  1235. }
  1236. // Round up?
  1237. if (r) {
  1238. for (; ;) {
  1239. // If the digit to be rounded up is in the first element of xc...
  1240. if (ni == 0) {
  1241. // i will be the length of xc[0] before k is added.
  1242. for (i = 1, j = xc[0]; j >= 10; j /= 10, i++);
  1243. j = xc[0] += k;
  1244. for (k = 1; j >= 10; j /= 10, k++);
  1245. // if i != k the length has increased.
  1246. if (i != k) {
  1247. x.e++;
  1248. if (xc[0] == BASE) xc[0] = 1;
  1249. }
  1250. break;
  1251. } else {
  1252. xc[ni] += k;
  1253. if (xc[ni] != BASE) break;
  1254. xc[ni--] = 0;
  1255. k = 1;
  1256. }
  1257. }
  1258. }
  1259. // Remove trailing zeros.
  1260. for (i = xc.length; xc[--i] === 0; xc.pop());
  1261. }
  1262. // Overflow? Infinity.
  1263. if (x.e > MAX_EXP) {
  1264. x.c = x.e = null;
  1265. // Underflow? Zero.
  1266. } else if (x.e < MIN_EXP) {
  1267. x.c = [x.e = 0];
  1268. }
  1269. }
  1270. return x;
  1271. }
  1272. function valueOf(n) {
  1273. var str,
  1274. e = n.e;
  1275. if (e === null) return n.toString();
  1276. str = coeffToString(n.c);
  1277. str = e <= TO_EXP_NEG || e >= TO_EXP_POS
  1278. ? toExponential(str, e)
  1279. : toFixedPoint(str, e, '0');
  1280. return n.s < 0 ? '-' + str : str;
  1281. }
  1282. // PROTOTYPE/INSTANCE METHODS
  1283. /*
  1284. * Return a new BigNumber whose value is the absolute value of this BigNumber.
  1285. */
  1286. P.absoluteValue = P.abs = function () {
  1287. var x = new BigNumber(this);
  1288. if (x.s < 0) x.s = 1;
  1289. return x;
  1290. };
  1291. /*
  1292. * Return
  1293. * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),
  1294. * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),
  1295. * 0 if they have the same value,
  1296. * or null if the value of either is NaN.
  1297. */
  1298. P.comparedTo = function (y, b) {
  1299. return compare(this, new BigNumber(y, b));
  1300. };
  1301. /*
  1302. * If dp is undefined or null or true or false, return the number of decimal places of the
  1303. * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.
  1304. *
  1305. * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this
  1306. * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or
  1307. * ROUNDING_MODE if rm is omitted.
  1308. *
  1309. * [dp] {number} Decimal places: integer, 0 to MAX inclusive.
  1310. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1311. *
  1312. * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'
  1313. */
  1314. P.decimalPlaces = P.dp = function (dp, rm) {
  1315. var c, n, v,
  1316. x = this;
  1317. if (dp != null) {
  1318. intCheck(dp, 0, MAX);
  1319. if (rm == null) rm = ROUNDING_MODE;
  1320. else intCheck(rm, 0, 8);
  1321. return round(new BigNumber(x), dp + x.e + 1, rm);
  1322. }
  1323. if (!(c = x.c)) return null;
  1324. n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;
  1325. // Subtract the number of trailing zeros of the last number.
  1326. if (v = c[v]) for (; v % 10 == 0; v /= 10, n--);
  1327. if (n < 0) n = 0;
  1328. return n;
  1329. };
  1330. /*
  1331. * n / 0 = I
  1332. * n / N = N
  1333. * n / I = 0
  1334. * 0 / n = 0
  1335. * 0 / 0 = N
  1336. * 0 / N = N
  1337. * 0 / I = 0
  1338. * N / n = N
  1339. * N / 0 = N
  1340. * N / N = N
  1341. * N / I = N
  1342. * I / n = I
  1343. * I / 0 = I
  1344. * I / N = N
  1345. * I / I = N
  1346. *
  1347. * Return a new BigNumber whose value is the value of this BigNumber divided by the value of
  1348. * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.
  1349. */
  1350. P.dividedBy = P.div = function (y, b) {
  1351. return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE);
  1352. };
  1353. /*
  1354. * Return a new BigNumber whose value is the integer part of dividing the value of this
  1355. * BigNumber by the value of BigNumber(y, b).
  1356. */
  1357. P.dividedToIntegerBy = P.idiv = function (y, b) {
  1358. return div(this, new BigNumber(y, b), 0, 1);
  1359. };
  1360. /*
  1361. * Return a BigNumber whose value is the value of this BigNumber exponentiated by n.
  1362. *
  1363. * If m is present, return the result modulo m.
  1364. * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.
  1365. * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE.
  1366. *
  1367. * The modular power operation works efficiently when x, n, and m are integers, otherwise it
  1368. * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0.
  1369. *
  1370. * n {number|string|BigNumber} The exponent. An integer.
  1371. * [m] {number|string|BigNumber} The modulus.
  1372. *
  1373. * '[BigNumber Error] Exponent not an integer: {n}'
  1374. */
  1375. P.exponentiatedBy = P.pow = function (n, m) {
  1376. var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y,
  1377. x = this;
  1378. n = new BigNumber(n);
  1379. // Allow NaN and ±Infinity, but not other non-integers.
  1380. if (n.c && !n.isInteger()) {
  1381. throw Error
  1382. (bignumberError + 'Exponent not an integer: ' + valueOf(n));
  1383. }
  1384. if (m != null) m = new BigNumber(m);
  1385. // Exponent of MAX_SAFE_INTEGER is 15.
  1386. nIsBig = n.e > 14;
  1387. // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0.
  1388. if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) {
  1389. // The sign of the result of pow when x is negative depends on the evenness of n.
  1390. // If +n overflows to ±Infinity, the evenness of n would be not be known.
  1391. y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? 2 - isOdd(n) : +valueOf(n)));
  1392. return m ? y.mod(m) : y;
  1393. }
  1394. nIsNeg = n.s < 0;
  1395. if (m) {
  1396. // x % m returns NaN if abs(m) is zero, or m is NaN.
  1397. if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN);
  1398. isModExp = !nIsNeg && x.isInteger() && m.isInteger();
  1399. if (isModExp) x = x.mod(m);
  1400. // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15.
  1401. // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15.
  1402. } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0
  1403. // [1, 240000000]
  1404. ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7
  1405. // [80000000000000] [99999750000000]
  1406. : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) {
  1407. // If x is negative and n is odd, k = -0, else k = 0.
  1408. k = x.s < 0 && isOdd(n) ? -0 : 0;
  1409. // If x >= 1, k = ±Infinity.
  1410. if (x.e > -1) k = 1 / k;
  1411. // If n is negative return ±0, else return ±Infinity.
  1412. return new BigNumber(nIsNeg ? 1 / k : k);
  1413. } else if (POW_PRECISION) {
  1414. // Truncating each coefficient array to a length of k after each multiplication
  1415. // equates to truncating significant digits to POW_PRECISION + [28, 41],
  1416. // i.e. there will be a minimum of 28 guard digits retained.
  1417. k = mathceil(POW_PRECISION / LOG_BASE + 2);
  1418. }
  1419. if (nIsBig) {
  1420. half = new BigNumber(0.5);
  1421. if (nIsNeg) n.s = 1;
  1422. nIsOdd = isOdd(n);
  1423. } else {
  1424. i = Math.abs(+valueOf(n));
  1425. nIsOdd = i % 2;
  1426. }
  1427. y = new BigNumber(ONE);
  1428. // Performs 54 loop iterations for n of 9007199254740991.
  1429. for (; ;) {
  1430. if (nIsOdd) {
  1431. y = y.times(x);
  1432. if (!y.c) break;
  1433. if (k) {
  1434. if (y.c.length > k) y.c.length = k;
  1435. } else if (isModExp) {
  1436. y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m));
  1437. }
  1438. }
  1439. if (i) {
  1440. i = mathfloor(i / 2);
  1441. if (i === 0) break;
  1442. nIsOdd = i % 2;
  1443. } else {
  1444. n = n.times(half);
  1445. round(n, n.e + 1, 1);
  1446. if (n.e > 14) {
  1447. nIsOdd = isOdd(n);
  1448. } else {
  1449. i = +valueOf(n);
  1450. if (i === 0) break;
  1451. nIsOdd = i % 2;
  1452. }
  1453. }
  1454. x = x.times(x);
  1455. if (k) {
  1456. if (x.c && x.c.length > k) x.c.length = k;
  1457. } else if (isModExp) {
  1458. x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m));
  1459. }
  1460. }
  1461. if (isModExp) return y;
  1462. if (nIsNeg) y = ONE.div(y);
  1463. return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y;
  1464. };
  1465. /*
  1466. * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer
  1467. * using rounding mode rm, or ROUNDING_MODE if rm is omitted.
  1468. *
  1469. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1470. *
  1471. * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}'
  1472. */
  1473. P.integerValue = function (rm) {
  1474. var n = new BigNumber(this);
  1475. if (rm == null) rm = ROUNDING_MODE;
  1476. else intCheck(rm, 0, 8);
  1477. return round(n, n.e + 1, rm);
  1478. };
  1479. /*
  1480. * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),
  1481. * otherwise return false.
  1482. */
  1483. P.isEqualTo = P.eq = function (y, b) {
  1484. return compare(this, new BigNumber(y, b)) === 0;
  1485. };
  1486. /*
  1487. * Return true if the value of this BigNumber is a finite number, otherwise return false.
  1488. */
  1489. P.isFinite = function () {
  1490. return !!this.c;
  1491. };
  1492. /*
  1493. * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),
  1494. * otherwise return false.
  1495. */
  1496. P.isGreaterThan = P.gt = function (y, b) {
  1497. return compare(this, new BigNumber(y, b)) > 0;
  1498. };
  1499. /*
  1500. * Return true if the value of this BigNumber is greater than or equal to the value of
  1501. * BigNumber(y, b), otherwise return false.
  1502. */
  1503. P.isGreaterThanOrEqualTo = P.gte = function (y, b) {
  1504. return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0;
  1505. };
  1506. /*
  1507. * Return true if the value of this BigNumber is an integer, otherwise return false.
  1508. */
  1509. P.isInteger = function () {
  1510. return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;
  1511. };
  1512. /*
  1513. * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),
  1514. * otherwise return false.
  1515. */
  1516. P.isLessThan = P.lt = function (y, b) {
  1517. return compare(this, new BigNumber(y, b)) < 0;
  1518. };
  1519. /*
  1520. * Return true if the value of this BigNumber is less than or equal to the value of
  1521. * BigNumber(y, b), otherwise return false.
  1522. */
  1523. P.isLessThanOrEqualTo = P.lte = function (y, b) {
  1524. return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0;
  1525. };
  1526. /*
  1527. * Return true if the value of this BigNumber is NaN, otherwise return false.
  1528. */
  1529. P.isNaN = function () {
  1530. return !this.s;
  1531. };
  1532. /*
  1533. * Return true if the value of this BigNumber is negative, otherwise return false.
  1534. */
  1535. P.isNegative = function () {
  1536. return this.s < 0;
  1537. };
  1538. /*
  1539. * Return true if the value of this BigNumber is positive, otherwise return false.
  1540. */
  1541. P.isPositive = function () {
  1542. return this.s > 0;
  1543. };
  1544. /*
  1545. * Return true if the value of this BigNumber is 0 or -0, otherwise return false.
  1546. */
  1547. P.isZero = function () {
  1548. return !!this.c && this.c[0] == 0;
  1549. };
  1550. /*
  1551. * n - 0 = n
  1552. * n - N = N
  1553. * n - I = -I
  1554. * 0 - n = -n
  1555. * 0 - 0 = 0
  1556. * 0 - N = N
  1557. * 0 - I = -I
  1558. * N - n = N
  1559. * N - 0 = N
  1560. * N - N = N
  1561. * N - I = N
  1562. * I - n = I
  1563. * I - 0 = I
  1564. * I - N = N
  1565. * I - I = N
  1566. *
  1567. * Return a new BigNumber whose value is the value of this BigNumber minus the value of
  1568. * BigNumber(y, b).
  1569. */
  1570. P.minus = function (y, b) {
  1571. var i, j, t, xLTy,
  1572. x = this,
  1573. a = x.s;
  1574. y = new BigNumber(y, b);
  1575. b = y.s;
  1576. // Either NaN?
  1577. if (!a || !b) return new BigNumber(NaN);
  1578. // Signs differ?
  1579. if (a != b) {
  1580. y.s = -b;
  1581. return x.plus(y);
  1582. }
  1583. var xe = x.e / LOG_BASE,
  1584. ye = y.e / LOG_BASE,
  1585. xc = x.c,
  1586. yc = y.c;
  1587. if (!xe || !ye) {
  1588. // Either Infinity?
  1589. if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN);
  1590. // Either zero?
  1591. if (!xc[0] || !yc[0]) {
  1592. // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
  1593. return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x :
  1594. // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
  1595. ROUNDING_MODE == 3 ? -0 : 0);
  1596. }
  1597. }
  1598. xe = bitFloor(xe);
  1599. ye = bitFloor(ye);
  1600. xc = xc.slice();
  1601. // Determine which is the bigger number.
  1602. if (a = xe - ye) {
  1603. if (xLTy = a < 0) {
  1604. a = -a;
  1605. t = xc;
  1606. } else {
  1607. ye = xe;
  1608. t = yc;
  1609. }
  1610. t.reverse();
  1611. // Prepend zeros to equalise exponents.
  1612. for (b = a; b--; t.push(0));
  1613. t.reverse();
  1614. } else {
  1615. // Exponents equal. Check digit by digit.
  1616. j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b;
  1617. for (a = b = 0; b < j; b++) {
  1618. if (xc[b] != yc[b]) {
  1619. xLTy = xc[b] < yc[b];
  1620. break;
  1621. }
  1622. }
  1623. }
  1624. // x < y? Point xc to the array of the bigger number.
  1625. if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;
  1626. b = (j = yc.length) - (i = xc.length);
  1627. // Append zeros to xc if shorter.
  1628. // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.
  1629. if (b > 0) for (; b--; xc[i++] = 0);
  1630. b = BASE - 1;
  1631. // Subtract yc from xc.
  1632. for (; j > a;) {
  1633. if (xc[--j] < yc[j]) {
  1634. for (i = j; i && !xc[--i]; xc[i] = b);
  1635. --xc[i];
  1636. xc[j] += BASE;
  1637. }
  1638. xc[j] -= yc[j];
  1639. }
  1640. // Remove leading zeros and adjust exponent accordingly.
  1641. for (; xc[0] == 0; xc.splice(0, 1), --ye);
  1642. // Zero?
  1643. if (!xc[0]) {
  1644. // Following IEEE 754 (2008) 6.3,
  1645. // n - n = +0 but n - n = -0 when rounding towards -Infinity.
  1646. y.s = ROUNDING_MODE == 3 ? -1 : 1;
  1647. y.c = [y.e = 0];
  1648. return y;
  1649. }
  1650. // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity
  1651. // for finite x and y.
  1652. return normalise(y, xc, ye);
  1653. };
  1654. /*
  1655. * n % 0 = N
  1656. * n % N = N
  1657. * n % I = n
  1658. * 0 % n = 0
  1659. * -0 % n = -0
  1660. * 0 % 0 = N
  1661. * 0 % N = N
  1662. * 0 % I = 0
  1663. * N % n = N
  1664. * N % 0 = N
  1665. * N % N = N
  1666. * N % I = N
  1667. * I % n = N
  1668. * I % 0 = N
  1669. * I % N = N
  1670. * I % I = N
  1671. *
  1672. * Return a new BigNumber whose value is the value of this BigNumber modulo the value of
  1673. * BigNumber(y, b). The result depends on the value of MODULO_MODE.
  1674. */
  1675. P.modulo = P.mod = function (y, b) {
  1676. var q, s,
  1677. x = this;
  1678. y = new BigNumber(y, b);
  1679. // Return NaN if x is Infinity or NaN, or y is NaN or zero.
  1680. if (!x.c || !y.s || y.c && !y.c[0]) {
  1681. return new BigNumber(NaN);
  1682. // Return x if y is Infinity or x is zero.
  1683. } else if (!y.c || x.c && !x.c[0]) {
  1684. return new BigNumber(x);
  1685. }
  1686. if (MODULO_MODE == 9) {
  1687. // Euclidian division: q = sign(y) * floor(x / abs(y))
  1688. // r = x - qy where 0 <= r < abs(y)
  1689. s = y.s;
  1690. y.s = 1;
  1691. q = div(x, y, 0, 3);
  1692. y.s = s;
  1693. q.s *= s;
  1694. } else {
  1695. q = div(x, y, 0, MODULO_MODE);
  1696. }
  1697. y = x.minus(q.times(y));
  1698. // To match JavaScript %, ensure sign of zero is sign of dividend.
  1699. if (!y.c[0] && MODULO_MODE == 1) y.s = x.s;
  1700. return y;
  1701. };
  1702. /*
  1703. * n * 0 = 0
  1704. * n * N = N
  1705. * n * I = I
  1706. * 0 * n = 0
  1707. * 0 * 0 = 0
  1708. * 0 * N = N
  1709. * 0 * I = N
  1710. * N * n = N
  1711. * N * 0 = N
  1712. * N * N = N
  1713. * N * I = N
  1714. * I * n = I
  1715. * I * 0 = N
  1716. * I * N = N
  1717. * I * I = I
  1718. *
  1719. * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value
  1720. * of BigNumber(y, b).
  1721. */
  1722. P.multipliedBy = P.times = function (y, b) {
  1723. var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,
  1724. base, sqrtBase,
  1725. x = this,
  1726. xc = x.c,
  1727. yc = (y = new BigNumber(y, b)).c;
  1728. // Either NaN, ±Infinity or ±0?
  1729. if (!xc || !yc || !xc[0] || !yc[0]) {
  1730. // Return NaN if either is NaN, or one is 0 and the other is Infinity.
  1731. if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {
  1732. y.c = y.e = y.s = null;
  1733. } else {
  1734. y.s *= x.s;
  1735. // Return ±Infinity if either is ±Infinity.
  1736. if (!xc || !yc) {
  1737. y.c = y.e = null;
  1738. // Return ±0 if either is ±0.
  1739. } else {
  1740. y.c = [0];
  1741. y.e = 0;
  1742. }
  1743. }
  1744. return y;
  1745. }
  1746. e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE);
  1747. y.s *= x.s;
  1748. xcL = xc.length;
  1749. ycL = yc.length;
  1750. // Ensure xc points to longer array and xcL to its length.
  1751. if (xcL < ycL) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;
  1752. // Initialise the result array with zeros.
  1753. for (i = xcL + ycL, zc = []; i--; zc.push(0));
  1754. base = BASE;
  1755. sqrtBase = SQRT_BASE;
  1756. for (i = ycL; --i >= 0;) {
  1757. c = 0;
  1758. ylo = yc[i] % sqrtBase;
  1759. yhi = yc[i] / sqrtBase | 0;
  1760. for (k = xcL, j = i + k; j > i;) {
  1761. xlo = xc[--k] % sqrtBase;
  1762. xhi = xc[k] / sqrtBase | 0;
  1763. m = yhi * xlo + xhi * ylo;
  1764. xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c;
  1765. c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi;
  1766. zc[j--] = xlo % base;
  1767. }
  1768. zc[j] = c;
  1769. }
  1770. if (c) {
  1771. ++e;
  1772. } else {
  1773. zc.splice(0, 1);
  1774. }
  1775. return normalise(y, zc, e);
  1776. };
  1777. /*
  1778. * Return a new BigNumber whose value is the value of this BigNumber negated,
  1779. * i.e. multiplied by -1.
  1780. */
  1781. P.negated = function () {
  1782. var x = new BigNumber(this);
  1783. x.s = -x.s || null;
  1784. return x;
  1785. };
  1786. /*
  1787. * n + 0 = n
  1788. * n + N = N
  1789. * n + I = I
  1790. * 0 + n = n
  1791. * 0 + 0 = 0
  1792. * 0 + N = N
  1793. * 0 + I = I
  1794. * N + n = N
  1795. * N + 0 = N
  1796. * N + N = N
  1797. * N + I = N
  1798. * I + n = I
  1799. * I + 0 = I
  1800. * I + N = N
  1801. * I + I = I
  1802. *
  1803. * Return a new BigNumber whose value is the value of this BigNumber plus the value of
  1804. * BigNumber(y, b).
  1805. */
  1806. P.plus = function (y, b) {
  1807. var t,
  1808. x = this,
  1809. a = x.s;
  1810. y = new BigNumber(y, b);
  1811. b = y.s;
  1812. // Either NaN?
  1813. if (!a || !b) return new BigNumber(NaN);
  1814. // Signs differ?
  1815. if (a != b) {
  1816. y.s = -b;
  1817. return x.minus(y);
  1818. }
  1819. var xe = x.e / LOG_BASE,
  1820. ye = y.e / LOG_BASE,
  1821. xc = x.c,
  1822. yc = y.c;
  1823. if (!xe || !ye) {
  1824. // Return ±Infinity if either ±Infinity.
  1825. if (!xc || !yc) return new BigNumber(a / 0);
  1826. // Either zero?
  1827. // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
  1828. if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0);
  1829. }
  1830. xe = bitFloor(xe);
  1831. ye = bitFloor(ye);
  1832. xc = xc.slice();
  1833. // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.
  1834. if (a = xe - ye) {
  1835. if (a > 0) {
  1836. ye = xe;
  1837. t = yc;
  1838. } else {
  1839. a = -a;
  1840. t = xc;
  1841. }
  1842. t.reverse();
  1843. for (; a--; t.push(0));
  1844. t.reverse();
  1845. }
  1846. a = xc.length;
  1847. b = yc.length;
  1848. // Point xc to the longer array, and b to the shorter length.
  1849. if (a - b < 0) t = yc, yc = xc, xc = t, b = a;
  1850. // Only start adding at yc.length - 1 as the further digits of xc can be ignored.
  1851. for (a = 0; b;) {
  1852. a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0;
  1853. xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;
  1854. }
  1855. if (a) {
  1856. xc = [a].concat(xc);
  1857. ++ye;
  1858. }
  1859. // No need to check for zero, as +x + +y != 0 && -x + -y != 0
  1860. // ye = MAX_EXP + 1 possible
  1861. return normalise(y, xc, ye);
  1862. };
  1863. /*
  1864. * If sd is undefined or null or true or false, return the number of significant digits of
  1865. * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.
  1866. * If sd is true include integer-part trailing zeros in the count.
  1867. *
  1868. * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this
  1869. * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or
  1870. * ROUNDING_MODE if rm is omitted.
  1871. *
  1872. * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive.
  1873. * boolean: whether to count integer-part trailing zeros: true or false.
  1874. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1875. *
  1876. * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'
  1877. */
  1878. P.precision = P.sd = function (sd, rm) {
  1879. var c, n, v,
  1880. x = this;
  1881. if (sd != null && sd !== !!sd) {
  1882. intCheck(sd, 1, MAX);
  1883. if (rm == null) rm = ROUNDING_MODE;
  1884. else intCheck(rm, 0, 8);
  1885. return round(new BigNumber(x), sd, rm);
  1886. }
  1887. if (!(c = x.c)) return null;
  1888. v = c.length - 1;
  1889. n = v * LOG_BASE + 1;
  1890. if (v = c[v]) {
  1891. // Subtract the number of trailing zeros of the last element.
  1892. for (; v % 10 == 0; v /= 10, n--);
  1893. // Add the number of digits of the first element.
  1894. for (v = c[0]; v >= 10; v /= 10, n++);
  1895. }
  1896. if (sd && x.e + 1 > n) n = x.e + 1;
  1897. return n;
  1898. };
  1899. /*
  1900. * Return a new BigNumber whose value is the value of this BigNumber shifted by k places
  1901. * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.
  1902. *
  1903. * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
  1904. *
  1905. * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}'
  1906. */
  1907. P.shiftedBy = function (k) {
  1908. intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);
  1909. return this.times('1e' + k);
  1910. };
  1911. /*
  1912. * sqrt(-n) = N
  1913. * sqrt(N) = N
  1914. * sqrt(-I) = N
  1915. * sqrt(I) = I
  1916. * sqrt(0) = 0
  1917. * sqrt(-0) = -0
  1918. *
  1919. * Return a new BigNumber whose value is the square root of the value of this BigNumber,
  1920. * rounded according to DECIMAL_PLACES and ROUNDING_MODE.
  1921. */
  1922. P.squareRoot = P.sqrt = function () {
  1923. var m, n, r, rep, t,
  1924. x = this,
  1925. c = x.c,
  1926. s = x.s,
  1927. e = x.e,
  1928. dp = DECIMAL_PLACES + 4,
  1929. half = new BigNumber('0.5');
  1930. // Negative/NaN/Infinity/zero?
  1931. if (s !== 1 || !c || !c[0]) {
  1932. return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0);
  1933. }
  1934. // Initial estimate.
  1935. s = Math.sqrt(+valueOf(x));
  1936. // Math.sqrt underflow/overflow?
  1937. // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
  1938. if (s == 0 || s == 1 / 0) {
  1939. n = coeffToString(c);
  1940. if ((n.length + e) % 2 == 0) n += '0';
  1941. s = Math.sqrt(+n);
  1942. e = bitFloor((e + 1) / 2) - (e < 0 || e % 2);
  1943. if (s == 1 / 0) {
  1944. n = '5e' + e;
  1945. } else {
  1946. n = s.toExponential();
  1947. n = n.slice(0, n.indexOf('e') + 1) + e;
  1948. }
  1949. r = new BigNumber(n);
  1950. } else {
  1951. r = new BigNumber(s + '');
  1952. }
  1953. // Check for zero.
  1954. // r could be zero if MIN_EXP is changed after the this value was created.
  1955. // This would cause a division by zero (x/t) and hence Infinity below, which would cause
  1956. // coeffToString to throw.
  1957. if (r.c[0]) {
  1958. e = r.e;
  1959. s = e + dp;
  1960. if (s < 3) s = 0;
  1961. // Newton-Raphson iteration.
  1962. for (; ;) {
  1963. t = r;
  1964. r = half.times(t.plus(div(x, t, dp, 1)));
  1965. if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) {
  1966. // The exponent of r may here be one less than the final result exponent,
  1967. // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits
  1968. // are indexed correctly.
  1969. if (r.e < e) --s;
  1970. n = n.slice(s - 3, s + 1);
  1971. // The 4th rounding digit may be in error by -1 so if the 4 rounding digits
  1972. // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the
  1973. // iteration.
  1974. if (n == '9999' || !rep && n == '4999') {
  1975. // On the first iteration only, check to see if rounding up gives the
  1976. // exact result as the nines may infinitely repeat.
  1977. if (!rep) {
  1978. round(t, t.e + DECIMAL_PLACES + 2, 0);
  1979. if (t.times(t).eq(x)) {
  1980. r = t;
  1981. break;
  1982. }
  1983. }
  1984. dp += 4;
  1985. s += 4;
  1986. rep = 1;
  1987. } else {
  1988. // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact
  1989. // result. If not, then there are further digits and m will be truthy.
  1990. if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
  1991. // Truncate to the first rounding digit.
  1992. round(r, r.e + DECIMAL_PLACES + 2, 1);
  1993. m = !r.times(r).eq(x);
  1994. }
  1995. break;
  1996. }
  1997. }
  1998. }
  1999. }
  2000. return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m);
  2001. };
  2002. /*
  2003. * Return a string representing the value of this BigNumber in exponential notation and
  2004. * rounded using ROUNDING_MODE to dp fixed decimal places.
  2005. *
  2006. * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
  2007. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  2008. *
  2009. * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'
  2010. */
  2011. P.toExponential = function (dp, rm) {
  2012. if (dp != null) {
  2013. intCheck(dp, 0, MAX);
  2014. dp++;
  2015. }
  2016. return format(this, dp, rm, 1);
  2017. };
  2018. /*
  2019. * Return a string representing the value of this BigNumber in fixed-point notation rounding
  2020. * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
  2021. *
  2022. * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
  2023. * but e.g. (-0.00001).toFixed(0) is '-0'.
  2024. *
  2025. * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
  2026. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  2027. *
  2028. * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'
  2029. */
  2030. P.toFixed = function (dp, rm) {
  2031. if (dp != null) {
  2032. intCheck(dp, 0, MAX);
  2033. dp = dp + this.e + 1;
  2034. }
  2035. return format(this, dp, rm);
  2036. };
  2037. /*
  2038. * Return a string representing the value of this BigNumber in fixed-point notation rounded
  2039. * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties
  2040. * of the format or FORMAT object (see BigNumber.set).
  2041. *
  2042. * The formatting object may contain some or all of the properties shown below.
  2043. *
  2044. * FORMAT = {
  2045. * prefix: '',
  2046. * groupSize: 3,
  2047. * secondaryGroupSize: 0,
  2048. * groupSeparator: ',',
  2049. * decimalSeparator: '.',
  2050. * fractionGroupSize: 0,
  2051. * fractionGroupSeparator: '\xA0', // non-breaking space
  2052. * suffix: ''
  2053. * };
  2054. *
  2055. * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
  2056. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  2057. * [format] {object} Formatting options. See FORMAT pbject above.
  2058. *
  2059. * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'
  2060. * '[BigNumber Error] Argument not an object: {format}'
  2061. */
  2062. P.toFormat = function (dp, rm, format) {
  2063. var str,
  2064. x = this;
  2065. if (format == null) {
  2066. if (dp != null && rm && typeof rm == 'object') {
  2067. format = rm;
  2068. rm = null;
  2069. } else if (dp && typeof dp == 'object') {
  2070. format = dp;
  2071. dp = rm = null;
  2072. } else {
  2073. format = FORMAT;
  2074. }
  2075. } else if (typeof format != 'object') {
  2076. throw Error
  2077. (bignumberError + 'Argument not an object: ' + format);
  2078. }
  2079. str = x.toFixed(dp, rm);
  2080. if (x.c) {
  2081. var i,
  2082. arr = str.split('.'),
  2083. g1 = +format.groupSize,
  2084. g2 = +format.secondaryGroupSize,
  2085. groupSeparator = format.groupSeparator || '',
  2086. intPart = arr[0],
  2087. fractionPart = arr[1],
  2088. isNeg = x.s < 0,
  2089. intDigits = isNeg ? intPart.slice(1) : intPart,
  2090. len = intDigits.length;
  2091. if (g2) i = g1, g1 = g2, g2 = i, len -= i;
  2092. if (g1 > 0 && len > 0) {
  2093. i = len % g1 || g1;
  2094. intPart = intDigits.substr(0, i);
  2095. for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1);
  2096. if (g2 > 0) intPart += groupSeparator + intDigits.slice(i);
  2097. if (isNeg) intPart = '-' + intPart;
  2098. }
  2099. str = fractionPart
  2100. ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize)
  2101. ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'),
  2102. '$&' + (format.fractionGroupSeparator || ''))
  2103. : fractionPart)
  2104. : intPart;
  2105. }
  2106. return (format.prefix || '') + str + (format.suffix || '');
  2107. };
  2108. /*
  2109. * Return an array of two BigNumbers representing the value of this BigNumber as a simple
  2110. * fraction with an integer numerator and an integer denominator.
  2111. * The denominator will be a positive non-zero value less than or equal to the specified
  2112. * maximum denominator. If a maximum denominator is not specified, the denominator will be
  2113. * the lowest value necessary to represent the number exactly.
  2114. *
  2115. * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator.
  2116. *
  2117. * '[BigNumber Error] Argument {not an integer|out of range} : {md}'
  2118. */
  2119. P.toFraction = function (md) {
  2120. var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s,
  2121. x = this,
  2122. xc = x.c;
  2123. if (md != null) {
  2124. n = new BigNumber(md);
  2125. // Throw if md is less than one or is not an integer, unless it is Infinity.
  2126. if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) {
  2127. throw Error
  2128. (bignumberError + 'Argument ' +
  2129. (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n));
  2130. }
  2131. }
  2132. if (!xc) return new BigNumber(x);
  2133. d = new BigNumber(ONE);
  2134. n1 = d0 = new BigNumber(ONE);
  2135. d1 = n0 = new BigNumber(ONE);
  2136. s = coeffToString(xc);
  2137. // Determine initial denominator.
  2138. // d is a power of 10 and the minimum max denominator that specifies the value exactly.
  2139. e = d.e = s.length - x.e - 1;
  2140. d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp];
  2141. md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n;
  2142. exp = MAX_EXP;
  2143. MAX_EXP = 1 / 0;
  2144. n = new BigNumber(s);
  2145. // n0 = d1 = 0
  2146. n0.c[0] = 0;
  2147. for (; ;) {
  2148. q = div(n, d, 0, 1);
  2149. d2 = d0.plus(q.times(d1));
  2150. if (d2.comparedTo(md) == 1) break;
  2151. d0 = d1;
  2152. d1 = d2;
  2153. n1 = n0.plus(q.times(d2 = n1));
  2154. n0 = d2;
  2155. d = n.minus(q.times(d2 = d));
  2156. n = d2;
  2157. }
  2158. d2 = div(md.minus(d0), d1, 0, 1);
  2159. n0 = n0.plus(d2.times(n1));
  2160. d0 = d0.plus(d2.times(d1));
  2161. n0.s = n1.s = x.s;
  2162. e = e * 2;
  2163. // Determine which fraction is closer to x, n0/d0 or n1/d1
  2164. r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo(
  2165. div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0];
  2166. MAX_EXP = exp;
  2167. return r;
  2168. };
  2169. /*
  2170. * Return the value of this BigNumber converted to a number primitive.
  2171. */
  2172. P.toNumber = function () {
  2173. return +valueOf(this);
  2174. };
  2175. /*
  2176. * Return a string representing the value of this BigNumber rounded to sd significant digits
  2177. * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
  2178. * necessary to represent the integer part of the value in fixed-point notation, then use
  2179. * exponential notation.
  2180. *
  2181. * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
  2182. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  2183. *
  2184. * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'
  2185. */
  2186. P.toPrecision = function (sd, rm) {
  2187. if (sd != null) intCheck(sd, 1, MAX);
  2188. return format(this, sd, rm, 2);
  2189. };
  2190. /*
  2191. * Return a string representing the value of this BigNumber in base b, or base 10 if b is
  2192. * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and
  2193. * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent
  2194. * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than
  2195. * TO_EXP_NEG, return exponential notation.
  2196. *
  2197. * [b] {number} Integer, 2 to ALPHABET.length inclusive.
  2198. *
  2199. * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'
  2200. */
  2201. P.toString = function (b) {
  2202. var str,
  2203. n = this,
  2204. s = n.s,
  2205. e = n.e;
  2206. // Infinity or NaN?
  2207. if (e === null) {
  2208. if (s) {
  2209. str = 'Infinity';
  2210. if (s < 0) str = '-' + str;
  2211. } else {
  2212. str = 'NaN';
  2213. }
  2214. } else {
  2215. if (b == null) {
  2216. str = e <= TO_EXP_NEG || e >= TO_EXP_POS
  2217. ? toExponential(coeffToString(n.c), e)
  2218. : toFixedPoint(coeffToString(n.c), e, '0');
  2219. } else if (b === 10 && alphabetHasNormalDecimalDigits) {
  2220. n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE);
  2221. str = toFixedPoint(coeffToString(n.c), n.e, '0');
  2222. } else {
  2223. intCheck(b, 2, ALPHABET.length, 'Base');
  2224. str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true);
  2225. }
  2226. if (s < 0 && n.c[0]) str = '-' + str;
  2227. }
  2228. return str;
  2229. };
  2230. /*
  2231. * Return as toString, but do not accept a base argument, and include the minus sign for
  2232. * negative zero.
  2233. */
  2234. P.valueOf = P.toJSON = function () {
  2235. return valueOf(this);
  2236. };
  2237. P._isBigNumber = true;
  2238. P[Symbol.toStringTag] = 'BigNumber';
  2239. // Node.js v10.12.0+
  2240. P[Symbol.for('nodejs.util.inspect.custom')] = P.valueOf;
  2241. if (configObject != null) BigNumber.set(configObject);
  2242. return BigNumber;
  2243. }
  2244. // PRIVATE HELPER FUNCTIONS
  2245. // These functions don't need access to variables,
  2246. // e.g. DECIMAL_PLACES, in the scope of the `clone` function above.
  2247. function bitFloor(n) {
  2248. var i = n | 0;
  2249. return n > 0 || n === i ? i : i - 1;
  2250. }
  2251. // Return a coefficient array as a string of base 10 digits.
  2252. function coeffToString(a) {
  2253. var s, z,
  2254. i = 1,
  2255. j = a.length,
  2256. r = a[0] + '';
  2257. for (; i < j;) {
  2258. s = a[i++] + '';
  2259. z = LOG_BASE - s.length;
  2260. for (; z--; s = '0' + s);
  2261. r += s;
  2262. }
  2263. // Determine trailing zeros.
  2264. for (j = r.length; r.charCodeAt(--j) === 48;);
  2265. return r.slice(0, j + 1 || 1);
  2266. }
  2267. // Compare the value of BigNumbers x and y.
  2268. function compare(x, y) {
  2269. var a, b,
  2270. xc = x.c,
  2271. yc = y.c,
  2272. i = x.s,
  2273. j = y.s,
  2274. k = x.e,
  2275. l = y.e;
  2276. // Either NaN?
  2277. if (!i || !j) return null;
  2278. a = xc && !xc[0];
  2279. b = yc && !yc[0];
  2280. // Either zero?
  2281. if (a || b) return a ? b ? 0 : -j : i;
  2282. // Signs differ?
  2283. if (i != j) return i;
  2284. a = i < 0;
  2285. b = k == l;
  2286. // Either Infinity?
  2287. if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1;
  2288. // Compare exponents.
  2289. if (!b) return k > l ^ a ? 1 : -1;
  2290. j = (k = xc.length) < (l = yc.length) ? k : l;
  2291. // Compare digit by digit.
  2292. for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1;
  2293. // Compare lengths.
  2294. return k == l ? 0 : k > l ^ a ? 1 : -1;
  2295. }
  2296. /*
  2297. * Check that n is a primitive number, an integer, and in range, otherwise throw.
  2298. */
  2299. function intCheck(n, min, max, name) {
  2300. if (n < min || n > max || n !== mathfloor(n)) {
  2301. throw Error
  2302. (bignumberError + (name || 'Argument') + (typeof n == 'number'
  2303. ? n < min || n > max ? ' out of range: ' : ' not an integer: '
  2304. : ' not a primitive number: ') + String(n));
  2305. }
  2306. }
  2307. // Assumes finite n.
  2308. function isOdd(n) {
  2309. var k = n.c.length - 1;
  2310. return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0;
  2311. }
  2312. function toExponential(str, e) {
  2313. return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) +
  2314. (e < 0 ? 'e' : 'e+') + e;
  2315. }
  2316. function toFixedPoint(str, e, z) {
  2317. var len, zs;
  2318. // Negative exponent?
  2319. if (e < 0) {
  2320. // Prepend zeros.
  2321. for (zs = z + '.'; ++e; zs += z);
  2322. str = zs + str;
  2323. // Positive exponent
  2324. } else {
  2325. len = str.length;
  2326. // Append zeros.
  2327. if (++e > len) {
  2328. for (zs = z, e -= len; --e; zs += z);
  2329. str += zs;
  2330. } else if (e < len) {
  2331. str = str.slice(0, e) + '.' + str.slice(e);
  2332. }
  2333. }
  2334. return str;
  2335. }
  2336. // EXPORT
  2337. var BigNumber = clone();
  2338. // src/index.ts
  2339. var SplayTreeNode = class {
  2340. key;
  2341. left = null;
  2342. right = null;
  2343. constructor(key) {
  2344. this.key = key;
  2345. }
  2346. };
  2347. var SplayTreeSetNode = class extends SplayTreeNode {
  2348. constructor(key) {
  2349. super(key);
  2350. }
  2351. };
  2352. var SplayTree = class {
  2353. size = 0;
  2354. modificationCount = 0;
  2355. splayCount = 0;
  2356. splay(key) {
  2357. const root = this.root;
  2358. if (root == null) {
  2359. this.compare(key, key);
  2360. return -1;
  2361. }
  2362. let right = null;
  2363. let newTreeRight = null;
  2364. let left = null;
  2365. let newTreeLeft = null;
  2366. let current = root;
  2367. const compare = this.compare;
  2368. let comp;
  2369. while (true) {
  2370. comp = compare(current.key, key);
  2371. if (comp > 0) {
  2372. let currentLeft = current.left;
  2373. if (currentLeft == null) break;
  2374. comp = compare(currentLeft.key, key);
  2375. if (comp > 0) {
  2376. current.left = currentLeft.right;
  2377. currentLeft.right = current;
  2378. current = currentLeft;
  2379. currentLeft = current.left;
  2380. if (currentLeft == null) break;
  2381. }
  2382. if (right == null) {
  2383. newTreeRight = current;
  2384. } else {
  2385. right.left = current;
  2386. }
  2387. right = current;
  2388. current = currentLeft;
  2389. } else if (comp < 0) {
  2390. let currentRight = current.right;
  2391. if (currentRight == null) break;
  2392. comp = compare(currentRight.key, key);
  2393. if (comp < 0) {
  2394. current.right = currentRight.left;
  2395. currentRight.left = current;
  2396. current = currentRight;
  2397. currentRight = current.right;
  2398. if (currentRight == null) break;
  2399. }
  2400. if (left == null) {
  2401. newTreeLeft = current;
  2402. } else {
  2403. left.right = current;
  2404. }
  2405. left = current;
  2406. current = currentRight;
  2407. } else {
  2408. break;
  2409. }
  2410. }
  2411. if (left != null) {
  2412. left.right = current.left;
  2413. current.left = newTreeLeft;
  2414. }
  2415. if (right != null) {
  2416. right.left = current.right;
  2417. current.right = newTreeRight;
  2418. }
  2419. if (this.root !== current) {
  2420. this.root = current;
  2421. this.splayCount++;
  2422. }
  2423. return comp;
  2424. }
  2425. splayMin(node) {
  2426. let current = node;
  2427. let nextLeft = current.left;
  2428. while (nextLeft != null) {
  2429. const left = nextLeft;
  2430. current.left = left.right;
  2431. left.right = current;
  2432. current = left;
  2433. nextLeft = current.left;
  2434. }
  2435. return current;
  2436. }
  2437. splayMax(node) {
  2438. let current = node;
  2439. let nextRight = current.right;
  2440. while (nextRight != null) {
  2441. const right = nextRight;
  2442. current.right = right.left;
  2443. right.left = current;
  2444. current = right;
  2445. nextRight = current.right;
  2446. }
  2447. return current;
  2448. }
  2449. _delete(key) {
  2450. if (this.root == null) return null;
  2451. const comp = this.splay(key);
  2452. if (comp != 0) return null;
  2453. let root = this.root;
  2454. const result = root;
  2455. const left = root.left;
  2456. this.size--;
  2457. if (left == null) {
  2458. this.root = root.right;
  2459. } else {
  2460. const right = root.right;
  2461. root = this.splayMax(left);
  2462. root.right = right;
  2463. this.root = root;
  2464. }
  2465. this.modificationCount++;
  2466. return result;
  2467. }
  2468. addNewRoot(node, comp) {
  2469. this.size++;
  2470. this.modificationCount++;
  2471. const root = this.root;
  2472. if (root == null) {
  2473. this.root = node;
  2474. return;
  2475. }
  2476. if (comp < 0) {
  2477. node.left = root;
  2478. node.right = root.right;
  2479. root.right = null;
  2480. } else {
  2481. node.right = root;
  2482. node.left = root.left;
  2483. root.left = null;
  2484. }
  2485. this.root = node;
  2486. }
  2487. _first() {
  2488. const root = this.root;
  2489. if (root == null) return null;
  2490. this.root = this.splayMin(root);
  2491. return this.root;
  2492. }
  2493. _last() {
  2494. const root = this.root;
  2495. if (root == null) return null;
  2496. this.root = this.splayMax(root);
  2497. return this.root;
  2498. }
  2499. clear() {
  2500. this.root = null;
  2501. this.size = 0;
  2502. this.modificationCount++;
  2503. }
  2504. has(key) {
  2505. return this.validKey(key) && this.splay(key) == 0;
  2506. }
  2507. defaultCompare() {
  2508. return (a, b) => a < b ? -1 : a > b ? 1 : 0;
  2509. }
  2510. wrap() {
  2511. return {
  2512. getRoot: () => {
  2513. return this.root;
  2514. },
  2515. setRoot: (root) => {
  2516. this.root = root;
  2517. },
  2518. getSize: () => {
  2519. return this.size;
  2520. },
  2521. getModificationCount: () => {
  2522. return this.modificationCount;
  2523. },
  2524. getSplayCount: () => {
  2525. return this.splayCount;
  2526. },
  2527. setSplayCount: (count) => {
  2528. this.splayCount = count;
  2529. },
  2530. splay: (key) => {
  2531. return this.splay(key);
  2532. },
  2533. has: (key) => {
  2534. return this.has(key);
  2535. }
  2536. };
  2537. }
  2538. };
  2539. var SplayTreeSet = class _SplayTreeSet extends SplayTree {
  2540. root = null;
  2541. compare;
  2542. validKey;
  2543. constructor(compare, isValidKey) {
  2544. super();
  2545. this.compare = compare ?? this.defaultCompare();
  2546. this.validKey = isValidKey ?? ((v) => v != null && v != void 0);
  2547. }
  2548. delete(element) {
  2549. if (!this.validKey(element)) return false;
  2550. return this._delete(element) != null;
  2551. }
  2552. deleteAll(elements) {
  2553. for (const element of elements) {
  2554. this.delete(element);
  2555. }
  2556. }
  2557. forEach(f) {
  2558. const nodes = this[Symbol.iterator]();
  2559. let result;
  2560. while (result = nodes.next(), !result.done) {
  2561. f(result.value, result.value, this);
  2562. }
  2563. }
  2564. add(element) {
  2565. const compare = this.splay(element);
  2566. if (compare != 0) this.addNewRoot(new SplayTreeSetNode(element), compare);
  2567. return this;
  2568. }
  2569. addAndReturn(element) {
  2570. const compare = this.splay(element);
  2571. if (compare != 0) this.addNewRoot(new SplayTreeSetNode(element), compare);
  2572. return this.root.key;
  2573. }
  2574. addAll(elements) {
  2575. for (const element of elements) {
  2576. this.add(element);
  2577. }
  2578. }
  2579. isEmpty() {
  2580. return this.root == null;
  2581. }
  2582. isNotEmpty() {
  2583. return this.root != null;
  2584. }
  2585. single() {
  2586. if (this.size == 0) throw "Bad state: No element";
  2587. if (this.size > 1) throw "Bad state: Too many element";
  2588. return this.root.key;
  2589. }
  2590. first() {
  2591. if (this.size == 0) throw "Bad state: No element";
  2592. return this._first().key;
  2593. }
  2594. last() {
  2595. if (this.size == 0) throw "Bad state: No element";
  2596. return this._last().key;
  2597. }
  2598. lastBefore(element) {
  2599. if (element == null) throw "Invalid arguments(s)";
  2600. if (this.root == null) return null;
  2601. const comp = this.splay(element);
  2602. if (comp < 0) return this.root.key;
  2603. let node = this.root.left;
  2604. if (node == null) return null;
  2605. let nodeRight = node.right;
  2606. while (nodeRight != null) {
  2607. node = nodeRight;
  2608. nodeRight = node.right;
  2609. }
  2610. return node.key;
  2611. }
  2612. firstAfter(element) {
  2613. if (element == null) throw "Invalid arguments(s)";
  2614. if (this.root == null) return null;
  2615. const comp = this.splay(element);
  2616. if (comp > 0) return this.root.key;
  2617. let node = this.root.right;
  2618. if (node == null) return null;
  2619. let nodeLeft = node.left;
  2620. while (nodeLeft != null) {
  2621. node = nodeLeft;
  2622. nodeLeft = node.left;
  2623. }
  2624. return node.key;
  2625. }
  2626. retainAll(elements) {
  2627. const retainSet = new _SplayTreeSet(this.compare, this.validKey);
  2628. const modificationCount = this.modificationCount;
  2629. for (const object of elements) {
  2630. if (modificationCount != this.modificationCount) {
  2631. throw "Concurrent modification during iteration.";
  2632. }
  2633. if (this.validKey(object) && this.splay(object) == 0) {
  2634. retainSet.add(this.root.key);
  2635. }
  2636. }
  2637. if (retainSet.size != this.size) {
  2638. this.root = retainSet.root;
  2639. this.size = retainSet.size;
  2640. this.modificationCount++;
  2641. }
  2642. }
  2643. lookup(object) {
  2644. if (!this.validKey(object)) return null;
  2645. const comp = this.splay(object);
  2646. if (comp != 0) return null;
  2647. return this.root.key;
  2648. }
  2649. intersection(other) {
  2650. const result = new _SplayTreeSet(this.compare, this.validKey);
  2651. for (const element of this) {
  2652. if (other.has(element)) result.add(element);
  2653. }
  2654. return result;
  2655. }
  2656. difference(other) {
  2657. const result = new _SplayTreeSet(this.compare, this.validKey);
  2658. for (const element of this) {
  2659. if (!other.has(element)) result.add(element);
  2660. }
  2661. return result;
  2662. }
  2663. union(other) {
  2664. const u = this.clone();
  2665. u.addAll(other);
  2666. return u;
  2667. }
  2668. clone() {
  2669. const set = new _SplayTreeSet(this.compare, this.validKey);
  2670. set.size = this.size;
  2671. set.root = this.copyNode(this.root);
  2672. return set;
  2673. }
  2674. copyNode(node) {
  2675. if (node == null) return null;
  2676. function copyChildren(node2, dest) {
  2677. let left;
  2678. let right;
  2679. do {
  2680. left = node2.left;
  2681. right = node2.right;
  2682. if (left != null) {
  2683. const newLeft = new SplayTreeSetNode(left.key);
  2684. dest.left = newLeft;
  2685. copyChildren(left, newLeft);
  2686. }
  2687. if (right != null) {
  2688. const newRight = new SplayTreeSetNode(right.key);
  2689. dest.right = newRight;
  2690. node2 = right;
  2691. dest = newRight;
  2692. }
  2693. } while (right != null);
  2694. }
  2695. const result = new SplayTreeSetNode(node.key);
  2696. copyChildren(node, result);
  2697. return result;
  2698. }
  2699. toSet() {
  2700. return this.clone();
  2701. }
  2702. entries() {
  2703. return new SplayTreeSetEntryIterableIterator(this.wrap());
  2704. }
  2705. keys() {
  2706. return this[Symbol.iterator]();
  2707. }
  2708. values() {
  2709. return this[Symbol.iterator]();
  2710. }
  2711. [Symbol.iterator]() {
  2712. return new SplayTreeKeyIterableIterator(this.wrap());
  2713. }
  2714. [Symbol.toStringTag] = "[object Set]";
  2715. };
  2716. var SplayTreeIterableIterator = class {
  2717. tree;
  2718. path = new Array();
  2719. modificationCount = null;
  2720. splayCount;
  2721. constructor(tree) {
  2722. this.tree = tree;
  2723. this.splayCount = tree.getSplayCount();
  2724. }
  2725. [Symbol.iterator]() {
  2726. return this;
  2727. }
  2728. next() {
  2729. if (this.moveNext()) return { done: false, value: this.current() };
  2730. return { done: true, value: null };
  2731. }
  2732. current() {
  2733. if (!this.path.length) return null;
  2734. const node = this.path[this.path.length - 1];
  2735. return this.getValue(node);
  2736. }
  2737. rebuildPath(key) {
  2738. this.path.splice(0, this.path.length);
  2739. this.tree.splay(key);
  2740. this.path.push(this.tree.getRoot());
  2741. this.splayCount = this.tree.getSplayCount();
  2742. }
  2743. findLeftMostDescendent(node) {
  2744. while (node != null) {
  2745. this.path.push(node);
  2746. node = node.left;
  2747. }
  2748. }
  2749. moveNext() {
  2750. if (this.modificationCount != this.tree.getModificationCount()) {
  2751. if (this.modificationCount == null) {
  2752. this.modificationCount = this.tree.getModificationCount();
  2753. let node2 = this.tree.getRoot();
  2754. while (node2 != null) {
  2755. this.path.push(node2);
  2756. node2 = node2.left;
  2757. }
  2758. return this.path.length > 0;
  2759. }
  2760. throw "Concurrent modification during iteration.";
  2761. }
  2762. if (!this.path.length) return false;
  2763. if (this.splayCount != this.tree.getSplayCount()) {
  2764. this.rebuildPath(this.path[this.path.length - 1].key);
  2765. }
  2766. let node = this.path[this.path.length - 1];
  2767. let next = node.right;
  2768. if (next != null) {
  2769. while (next != null) {
  2770. this.path.push(next);
  2771. next = next.left;
  2772. }
  2773. return true;
  2774. }
  2775. this.path.pop();
  2776. while (this.path.length && this.path[this.path.length - 1].right === node) {
  2777. node = this.path.pop();
  2778. }
  2779. return this.path.length > 0;
  2780. }
  2781. };
  2782. var SplayTreeKeyIterableIterator = class extends SplayTreeIterableIterator {
  2783. getValue(node) {
  2784. return node.key;
  2785. }
  2786. };
  2787. var SplayTreeSetEntryIterableIterator = class extends SplayTreeIterableIterator {
  2788. getValue(node) {
  2789. return [node.key, node.key];
  2790. }
  2791. };
  2792. var identity = (x) => {
  2793. return x;
  2794. };
  2795. var snap = (eps) => {
  2796. if (eps) {
  2797. const xTree = new SplayTreeSet(compare$1(eps));
  2798. const yTree = new SplayTreeSet(compare$1(eps));
  2799. const snapCoord = (coord, tree) => {
  2800. return tree.addAndReturn(coord);
  2801. };
  2802. const snap = (v) => {
  2803. return {
  2804. x: snapCoord(v.x, xTree),
  2805. y: snapCoord(v.y, yTree),
  2806. };
  2807. };
  2808. snap({ x: new BigNumber(0), y: new BigNumber(0) });
  2809. return snap;
  2810. }
  2811. return identity;
  2812. };
  2813. const set = (eps) => {
  2814. return {
  2815. set: (eps) => { precision = set(eps); },
  2816. reset: () => set(eps),
  2817. compare: compare$1(eps),
  2818. snap: snap(eps),
  2819. orient: orient(eps)
  2820. };
  2821. };
  2822. let precision = set();
  2823. /**
  2824. * A bounding box has the format:
  2825. *
  2826. * { ll: { x: xmin, y: ymin }, ur: { x: xmax, y: ymax } }
  2827. *
  2828. */
  2829. const isInBbox = (bbox, point) => {
  2830. return (bbox.ll.x.isLessThanOrEqualTo(point.x) &&
  2831. point.x.isLessThanOrEqualTo(bbox.ur.x) &&
  2832. bbox.ll.y.isLessThanOrEqualTo(point.y) &&
  2833. point.y.isLessThanOrEqualTo(bbox.ur.y));
  2834. };
  2835. /* Returns either null, or a bbox (aka an ordered pair of points)
  2836. * If there is only one point of overlap, a bbox with identical points
  2837. * will be returned */
  2838. const getBboxOverlap = (b1, b2) => {
  2839. // check if the bboxes overlap at all
  2840. if (b2.ur.x.isLessThan(b1.ll.x) ||
  2841. b1.ur.x.isLessThan(b2.ll.x) ||
  2842. b2.ur.y.isLessThan(b1.ll.y) ||
  2843. b1.ur.y.isLessThan(b2.ll.y))
  2844. return null;
  2845. // find the middle two X values
  2846. const lowerX = b1.ll.x.isLessThan(b2.ll.x) ? b2.ll.x : b1.ll.x;
  2847. const upperX = b1.ur.x.isLessThan(b2.ur.x) ? b1.ur.x : b2.ur.x;
  2848. // find the middle two Y values
  2849. const lowerY = b1.ll.y.isLessThan(b2.ll.y) ? b2.ll.y : b1.ll.y;
  2850. const upperY = b1.ur.y.isLessThan(b2.ur.y) ? b1.ur.y : b2.ur.y;
  2851. // put those middle values together to get the overlap
  2852. return { ll: { x: lowerX, y: lowerY }, ur: { x: upperX, y: upperY } };
  2853. };
  2854. /* Cross Product of two vectors with first point at origin */
  2855. const crossProduct = (a, b) => a.x.times(b.y).minus(a.y.times(b.x));
  2856. /* Dot Product of two vectors with first point at origin */
  2857. const dotProduct = (a, b) => a.x.times(b.x).plus(a.y.times(b.y));
  2858. const length = (v) => dotProduct(v, v).sqrt();
  2859. /* Get the sine of the angle from pShared -> pAngle to pShaed -> pBase */
  2860. const sineOfAngle = (pShared, pBase, pAngle) => {
  2861. const vBase = { x: pBase.x.minus(pShared.x), y: pBase.y.minus(pShared.y) };
  2862. const vAngle = { x: pAngle.x.minus(pShared.x), y: pAngle.y.minus(pShared.y) };
  2863. return crossProduct(vAngle, vBase).div(length(vAngle)).div(length(vBase));
  2864. };
  2865. /* Get the cosine of the angle from pShared -> pAngle to pShaed -> pBase */
  2866. const cosineOfAngle = (pShared, pBase, pAngle) => {
  2867. const vBase = { x: pBase.x.minus(pShared.x), y: pBase.y.minus(pShared.y) };
  2868. const vAngle = { x: pAngle.x.minus(pShared.x), y: pAngle.y.minus(pShared.y) };
  2869. return dotProduct(vAngle, vBase).div(length(vAngle)).div(length(vBase));
  2870. };
  2871. /* Get the x coordinate where the given line (defined by a point and vector)
  2872. * crosses the horizontal line with the given y coordiante.
  2873. * In the case of parrallel lines (including overlapping ones) returns null. */
  2874. const horizontalIntersection = (pt, v, y) => {
  2875. if (v.y.isZero())
  2876. return null;
  2877. return { x: pt.x.plus((v.x.div(v.y)).times(y.minus(pt.y))), y: y };
  2878. };
  2879. /* Get the y coordinate where the given line (defined by a point and vector)
  2880. * crosses the vertical line with the given x coordiante.
  2881. * In the case of parrallel lines (including overlapping ones) returns null. */
  2882. const verticalIntersection = (pt, v, x) => {
  2883. if (v.x.isZero())
  2884. return null;
  2885. return { x: x, y: pt.y.plus((v.y.div(v.x)).times(x.minus(pt.x))) };
  2886. };
  2887. /* Get the intersection of two lines, each defined by a base point and a vector.
  2888. * In the case of parrallel lines (including overlapping ones) returns null. */
  2889. const intersection$1 = (pt1, v1, pt2, v2) => {
  2890. // take some shortcuts for vertical and horizontal lines
  2891. // this also ensures we don't calculate an intersection and then discover
  2892. // it's actually outside the bounding box of the line
  2893. if (v1.x.isZero())
  2894. return verticalIntersection(pt2, v2, pt1.x);
  2895. if (v2.x.isZero())
  2896. return verticalIntersection(pt1, v1, pt2.x);
  2897. if (v1.y.isZero())
  2898. return horizontalIntersection(pt2, v2, pt1.y);
  2899. if (v2.y.isZero())
  2900. return horizontalIntersection(pt1, v1, pt2.y);
  2901. // General case for non-overlapping segments.
  2902. // This algorithm is based on Schneider and Eberly.
  2903. // http://www.cimec.org.ar/~ncalvo/Schneider_Eberly.pdf - pg 244
  2904. const kross = crossProduct(v1, v2);
  2905. if (kross.isZero())
  2906. return null;
  2907. const ve = { x: pt2.x.minus(pt1.x), y: pt2.y.minus(pt1.y) };
  2908. const d1 = crossProduct(ve, v1).div(kross);
  2909. const d2 = crossProduct(ve, v2).div(kross);
  2910. // take the average of the two calculations to minimize rounding error
  2911. const x1 = pt1.x.plus(d2.times(v1.x)), x2 = pt2.x.plus(d1.times(v2.x));
  2912. const y1 = pt1.y.plus(d2.times(v1.y)), y2 = pt2.y.plus(d1.times(v2.y));
  2913. const x = x1.plus(x2).div(2);
  2914. const y = y1.plus(y2).div(2);
  2915. return { x: x, y: y };
  2916. };
  2917. class SweepEvent {
  2918. point;
  2919. isLeft;
  2920. segment;
  2921. otherSE;
  2922. consumedBy;
  2923. // for ordering sweep events in the sweep event queue
  2924. static compare(a, b) {
  2925. // favor event with a point that the sweep line hits first
  2926. const ptCmp = SweepEvent.comparePoints(a.point, b.point);
  2927. if (ptCmp !== 0)
  2928. return ptCmp;
  2929. // the points are the same, so link them if needed
  2930. if (a.point !== b.point)
  2931. a.link(b);
  2932. // favor right events over left
  2933. if (a.isLeft !== b.isLeft)
  2934. return a.isLeft ? 1 : -1;
  2935. // we have two matching left or right endpoints
  2936. // ordering of this case is the same as for their segments
  2937. return Segment.compare(a.segment, b.segment);
  2938. }
  2939. // for ordering points in sweep line order
  2940. static comparePoints(aPt, bPt) {
  2941. if (aPt.x.isLessThan(bPt.x))
  2942. return -1;
  2943. if (aPt.x.isGreaterThan(bPt.x))
  2944. return 1;
  2945. if (aPt.y.isLessThan(bPt.y))
  2946. return -1;
  2947. if (aPt.y.isGreaterThan(bPt.y))
  2948. return 1;
  2949. return 0;
  2950. }
  2951. // Warning: 'point' input will be modified and re-used (for performance)
  2952. constructor(point, isLeft) {
  2953. if (point.events === undefined)
  2954. point.events = [this];
  2955. else
  2956. point.events.push(this);
  2957. this.point = point;
  2958. this.isLeft = isLeft;
  2959. // this.segment, this.otherSE set by factory
  2960. }
  2961. link(other) {
  2962. if (other.point === this.point) {
  2963. throw new Error("Tried to link already linked events");
  2964. }
  2965. const otherEvents = other.point.events;
  2966. for (let i = 0, iMax = otherEvents.length; i < iMax; i++) {
  2967. const evt = otherEvents[i];
  2968. this.point.events.push(evt);
  2969. evt.point = this.point;
  2970. }
  2971. this.checkForConsuming();
  2972. }
  2973. /* Do a pass over our linked events and check to see if any pair
  2974. * of segments match, and should be consumed. */
  2975. checkForConsuming() {
  2976. // FIXME: The loops in this method run O(n^2) => no good.
  2977. // Maintain little ordered sweep event trees?
  2978. // Can we maintaining an ordering that avoids the need
  2979. // for the re-sorting with getLeftmostComparator in geom-out?
  2980. // Compare each pair of events to see if other events also match
  2981. const numEvents = this.point.events.length;
  2982. for (let i = 0; i < numEvents; i++) {
  2983. const evt1 = this.point.events[i];
  2984. if (evt1.segment.consumedBy !== undefined)
  2985. continue;
  2986. for (let j = i + 1; j < numEvents; j++) {
  2987. const evt2 = this.point.events[j];
  2988. if (evt2.consumedBy !== undefined)
  2989. continue;
  2990. if (evt1.otherSE.point.events !== evt2.otherSE.point.events)
  2991. continue;
  2992. evt1.segment.consume(evt2.segment);
  2993. }
  2994. }
  2995. }
  2996. getAvailableLinkedEvents() {
  2997. // point.events is always of length 2 or greater
  2998. const events = [];
  2999. for (let i = 0, iMax = this.point.events.length; i < iMax; i++) {
  3000. const evt = this.point.events[i];
  3001. if (evt !== this && !evt.segment.ringOut && evt.segment.isInResult()) {
  3002. events.push(evt);
  3003. }
  3004. }
  3005. return events;
  3006. }
  3007. /**
  3008. * Returns a comparator function for sorting linked events that will
  3009. * favor the event that will give us the smallest left-side angle.
  3010. * All ring construction starts as low as possible heading to the right,
  3011. * so by always turning left as sharp as possible we'll get polygons
  3012. * without uncessary loops & holes.
  3013. *
  3014. * The comparator function has a compute cache such that it avoids
  3015. * re-computing already-computed values.
  3016. */
  3017. getLeftmostComparator(baseEvent) {
  3018. const cache = new Map();
  3019. const fillCache = (linkedEvent) => {
  3020. const nextEvent = linkedEvent.otherSE;
  3021. cache.set(linkedEvent, {
  3022. sine: sineOfAngle(this.point, baseEvent.point, nextEvent.point),
  3023. cosine: cosineOfAngle(this.point, baseEvent.point, nextEvent.point),
  3024. });
  3025. };
  3026. return (a, b) => {
  3027. if (!cache.has(a))
  3028. fillCache(a);
  3029. if (!cache.has(b))
  3030. fillCache(b);
  3031. const { sine: asine, cosine: acosine } = cache.get(a);
  3032. const { sine: bsine, cosine: bcosine } = cache.get(b);
  3033. // both on or above x-axis
  3034. if (asine.isGreaterThanOrEqualTo(0) && bsine.isGreaterThanOrEqualTo(0)) {
  3035. if (acosine.isLessThan(bcosine))
  3036. return 1;
  3037. if (acosine.isGreaterThan(bcosine))
  3038. return -1;
  3039. return 0;
  3040. }
  3041. // both below x-axis
  3042. if (asine.isLessThan(0) && bsine.isLessThan(0)) {
  3043. if (acosine.isLessThan(bcosine))
  3044. return -1;
  3045. if (acosine.isGreaterThan(bcosine))
  3046. return 1;
  3047. return 0;
  3048. }
  3049. // one above x-axis, one below
  3050. if (bsine.isLessThan(asine))
  3051. return -1;
  3052. if (bsine.isGreaterThan(asine))
  3053. return 1;
  3054. return 0;
  3055. };
  3056. }
  3057. }
  3058. // Give segments unique ID's to get consistent sorting of
  3059. // segments and sweep events when all else is identical
  3060. let segmentId = 0;
  3061. class Segment {
  3062. id;
  3063. leftSE;
  3064. rightSE;
  3065. rings;
  3066. windings;
  3067. ringOut;
  3068. consumedBy;
  3069. prev;
  3070. _prevInResult;
  3071. _beforeState;
  3072. _afterState;
  3073. _isInResult;
  3074. /* This compare() function is for ordering segments in the sweep
  3075. * line tree, and does so according to the following criteria:
  3076. *
  3077. * Consider the vertical line that lies an infinestimal step to the
  3078. * right of the right-more of the two left endpoints of the input
  3079. * segments. Imagine slowly moving a point up from negative infinity
  3080. * in the increasing y direction. Which of the two segments will that
  3081. * point intersect first? That segment comes 'before' the other one.
  3082. *
  3083. * If neither segment would be intersected by such a line, (if one
  3084. * or more of the segments are vertical) then the line to be considered
  3085. * is directly on the right-more of the two left inputs.
  3086. */
  3087. static compare(a, b) {
  3088. const alx = a.leftSE.point.x;
  3089. const blx = b.leftSE.point.x;
  3090. const arx = a.rightSE.point.x;
  3091. const brx = b.rightSE.point.x;
  3092. // check if they're even in the same vertical plane
  3093. if (brx.isLessThan(alx))
  3094. return 1;
  3095. if (arx.isLessThan(blx))
  3096. return -1;
  3097. const aly = a.leftSE.point.y;
  3098. const bly = b.leftSE.point.y;
  3099. const ary = a.rightSE.point.y;
  3100. const bry = b.rightSE.point.y;
  3101. // is left endpoint of segment B the right-more?
  3102. if (alx.isLessThan(blx)) {
  3103. // are the two segments in the same horizontal plane?
  3104. if (bly.isLessThan(aly) && bly.isLessThan(ary))
  3105. return 1;
  3106. if (bly.isGreaterThan(aly) && bly.isGreaterThan(ary))
  3107. return -1;
  3108. // is the B left endpoint colinear to segment A?
  3109. const aCmpBLeft = a.comparePoint(b.leftSE.point);
  3110. if (aCmpBLeft < 0)
  3111. return 1;
  3112. if (aCmpBLeft > 0)
  3113. return -1;
  3114. // is the A right endpoint colinear to segment B ?
  3115. const bCmpARight = b.comparePoint(a.rightSE.point);
  3116. if (bCmpARight !== 0)
  3117. return bCmpARight;
  3118. // colinear segments, consider the one with left-more
  3119. // left endpoint to be first (arbitrary?)
  3120. return -1;
  3121. }
  3122. // is left endpoint of segment A the right-more?
  3123. if (alx.isGreaterThan(blx)) {
  3124. if (aly.isLessThan(bly) && aly.isLessThan(bry))
  3125. return -1;
  3126. if (aly.isGreaterThan(bly) && aly.isGreaterThan(bry))
  3127. return 1;
  3128. // is the A left endpoint colinear to segment B?
  3129. const bCmpALeft = b.comparePoint(a.leftSE.point);
  3130. if (bCmpALeft !== 0)
  3131. return bCmpALeft;
  3132. // is the B right endpoint colinear to segment A?
  3133. const aCmpBRight = a.comparePoint(b.rightSE.point);
  3134. if (aCmpBRight < 0)
  3135. return 1;
  3136. if (aCmpBRight > 0)
  3137. return -1;
  3138. // colinear segments, consider the one with left-more
  3139. // left endpoint to be first (arbitrary?)
  3140. return 1;
  3141. }
  3142. // if we get here, the two left endpoints are in the same
  3143. // vertical plane, ie alx === blx
  3144. // consider the lower left-endpoint to come first
  3145. if (aly.isLessThan(bly))
  3146. return -1;
  3147. if (aly.isGreaterThan(bly))
  3148. return 1;
  3149. // left endpoints are identical
  3150. // check for colinearity by using the left-more right endpoint
  3151. // is the A right endpoint more left-more?
  3152. if (arx.isLessThan(brx)) {
  3153. const bCmpARight = b.comparePoint(a.rightSE.point);
  3154. if (bCmpARight !== 0)
  3155. return bCmpARight;
  3156. }
  3157. // is the B right endpoint more left-more?
  3158. if (arx.isGreaterThan(brx)) {
  3159. const aCmpBRight = a.comparePoint(b.rightSE.point);
  3160. if (aCmpBRight < 0)
  3161. return 1;
  3162. if (aCmpBRight > 0)
  3163. return -1;
  3164. }
  3165. if (!arx.eq(brx)) {
  3166. // are these two [almost] vertical segments with opposite orientation?
  3167. // if so, the one with the lower right endpoint comes first
  3168. const ay = ary.minus(aly);
  3169. const ax = arx.minus(alx);
  3170. const by = bry.minus(bly);
  3171. const bx = brx.minus(blx);
  3172. if (ay.isGreaterThan(ax) && by.isLessThan(bx))
  3173. return 1;
  3174. if (ay.isLessThan(ax) && by.isGreaterThan(bx))
  3175. return -1;
  3176. }
  3177. // we have colinear segments with matching orientation
  3178. // consider the one with more left-more right endpoint to be first
  3179. if (arx.isGreaterThan(brx))
  3180. return 1;
  3181. if (arx.isLessThan(brx))
  3182. return -1;
  3183. // if we get here, two two right endpoints are in the same
  3184. // vertical plane, ie arx === brx
  3185. // consider the lower right-endpoint to come first
  3186. if (ary.isLessThan(bry))
  3187. return -1;
  3188. if (ary.isGreaterThan(bry))
  3189. return 1;
  3190. // right endpoints identical as well, so the segments are idential
  3191. // fall back on creation order as consistent tie-breaker
  3192. if (a.id < b.id)
  3193. return -1;
  3194. if (a.id > b.id)
  3195. return 1;
  3196. // identical segment, ie a === b
  3197. return 0;
  3198. }
  3199. /* Warning: a reference to ringWindings input will be stored,
  3200. * and possibly will be later modified */
  3201. constructor(leftSE, rightSE, rings, windings) {
  3202. this.id = ++segmentId;
  3203. this.leftSE = leftSE;
  3204. leftSE.segment = this;
  3205. leftSE.otherSE = rightSE;
  3206. this.rightSE = rightSE;
  3207. rightSE.segment = this;
  3208. rightSE.otherSE = leftSE;
  3209. this.rings = rings;
  3210. this.windings = windings;
  3211. // left unset for performance, set later in algorithm
  3212. // this.ringOut, this.consumedBy, this.prev
  3213. }
  3214. static fromRing(pt1, pt2, ring) {
  3215. let leftPt, rightPt, winding;
  3216. // ordering the two points according to sweep line ordering
  3217. const cmpPts = SweepEvent.comparePoints(pt1, pt2);
  3218. if (cmpPts < 0) {
  3219. leftPt = pt1;
  3220. rightPt = pt2;
  3221. winding = 1;
  3222. }
  3223. else if (cmpPts > 0) {
  3224. leftPt = pt2;
  3225. rightPt = pt1;
  3226. winding = -1;
  3227. }
  3228. else
  3229. throw new Error(`Tried to create degenerate segment at [${pt1.x}, ${pt1.y}]`);
  3230. const leftSE = new SweepEvent(leftPt, true);
  3231. const rightSE = new SweepEvent(rightPt, false);
  3232. return new Segment(leftSE, rightSE, [ring], [winding]);
  3233. }
  3234. /* When a segment is split, the rightSE is replaced with a new sweep event */
  3235. replaceRightSE(newRightSE) {
  3236. this.rightSE = newRightSE;
  3237. this.rightSE.segment = this;
  3238. this.rightSE.otherSE = this.leftSE;
  3239. this.leftSE.otherSE = this.rightSE;
  3240. }
  3241. bbox() {
  3242. const y1 = this.leftSE.point.y;
  3243. const y2 = this.rightSE.point.y;
  3244. return {
  3245. ll: { x: this.leftSE.point.x, y: y1.isLessThan(y2) ? y1 : y2 },
  3246. ur: { x: this.rightSE.point.x, y: y1.isGreaterThan(y2) ? y1 : y2 },
  3247. };
  3248. }
  3249. /* A vector from the left point to the right */
  3250. vector() {
  3251. return {
  3252. x: this.rightSE.point.x.minus(this.leftSE.point.x),
  3253. y: this.rightSE.point.y.minus(this.leftSE.point.y),
  3254. };
  3255. }
  3256. isAnEndpoint(pt) {
  3257. return ((pt.x.eq(this.leftSE.point.x) && pt.y.eq(this.leftSE.point.y)) ||
  3258. (pt.x.eq(this.rightSE.point.x) && pt.y.eq(this.rightSE.point.y)));
  3259. }
  3260. /* Compare this segment with a point.
  3261. *
  3262. * A point P is considered to be colinear to a segment if there
  3263. * exists a distance D such that if we travel along the segment
  3264. * from one * endpoint towards the other a distance D, we find
  3265. * ourselves at point P.
  3266. *
  3267. * Return value indicates:
  3268. *
  3269. * 1: point lies above the segment (to the left of vertical)
  3270. * 0: point is colinear to segment
  3271. * -1: point lies below the segment (to the right of vertical)
  3272. */
  3273. comparePoint(point) {
  3274. return precision.orient(this.leftSE.point, point, this.rightSE.point);
  3275. }
  3276. /**
  3277. * Given another segment, returns the first non-trivial intersection
  3278. * between the two segments (in terms of sweep line ordering), if it exists.
  3279. *
  3280. * A 'non-trivial' intersection is one that will cause one or both of the
  3281. * segments to be split(). As such, 'trivial' vs. 'non-trivial' intersection:
  3282. *
  3283. * * endpoint of segA with endpoint of segB --> trivial
  3284. * * endpoint of segA with point along segB --> non-trivial
  3285. * * endpoint of segB with point along segA --> non-trivial
  3286. * * point along segA with point along segB --> non-trivial
  3287. *
  3288. * If no non-trivial intersection exists, return null
  3289. * Else, return null.
  3290. */
  3291. getIntersection(other) {
  3292. // If bboxes don't overlap, there can't be any intersections
  3293. const tBbox = this.bbox();
  3294. const oBbox = other.bbox();
  3295. const bboxOverlap = getBboxOverlap(tBbox, oBbox);
  3296. if (bboxOverlap === null)
  3297. return null;
  3298. // We first check to see if the endpoints can be considered intersections.
  3299. // This will 'snap' intersections to endpoints if possible, and will
  3300. // handle cases of colinearity.
  3301. const tlp = this.leftSE.point;
  3302. const trp = this.rightSE.point;
  3303. const olp = other.leftSE.point;
  3304. const orp = other.rightSE.point;
  3305. // does each endpoint touch the other segment?
  3306. // note that we restrict the 'touching' definition to only allow segments
  3307. // to touch endpoints that lie forward from where we are in the sweep line pass
  3308. const touchesOtherLSE = isInBbox(tBbox, olp) && this.comparePoint(olp) === 0;
  3309. const touchesThisLSE = isInBbox(oBbox, tlp) && other.comparePoint(tlp) === 0;
  3310. const touchesOtherRSE = isInBbox(tBbox, orp) && this.comparePoint(orp) === 0;
  3311. const touchesThisRSE = isInBbox(oBbox, trp) && other.comparePoint(trp) === 0;
  3312. // do left endpoints match?
  3313. if (touchesThisLSE && touchesOtherLSE) {
  3314. // these two cases are for colinear segments with matching left
  3315. // endpoints, and one segment being longer than the other
  3316. if (touchesThisRSE && !touchesOtherRSE)
  3317. return trp;
  3318. if (!touchesThisRSE && touchesOtherRSE)
  3319. return orp;
  3320. // either the two segments match exactly (two trival intersections)
  3321. // or just on their left endpoint (one trivial intersection
  3322. return null;
  3323. }
  3324. // does this left endpoint matches (other doesn't)
  3325. if (touchesThisLSE) {
  3326. // check for segments that just intersect on opposing endpoints
  3327. if (touchesOtherRSE) {
  3328. if (tlp.x.eq(orp.x) && tlp.y.eq(orp.y))
  3329. return null;
  3330. }
  3331. // t-intersection on left endpoint
  3332. return tlp;
  3333. }
  3334. // does other left endpoint matches (this doesn't)
  3335. if (touchesOtherLSE) {
  3336. // check for segments that just intersect on opposing endpoints
  3337. if (touchesThisRSE) {
  3338. if (trp.x.eq(olp.x) && trp.y.eq(olp.y))
  3339. return null;
  3340. }
  3341. // t-intersection on left endpoint
  3342. return olp;
  3343. }
  3344. // trivial intersection on right endpoints
  3345. if (touchesThisRSE && touchesOtherRSE)
  3346. return null;
  3347. // t-intersections on just one right endpoint
  3348. if (touchesThisRSE)
  3349. return trp;
  3350. if (touchesOtherRSE)
  3351. return orp;
  3352. // None of our endpoints intersect. Look for a general intersection between
  3353. // infinite lines laid over the segments
  3354. const pt = intersection$1(tlp, this.vector(), olp, other.vector());
  3355. // are the segments parrallel? Note that if they were colinear with overlap,
  3356. // they would have an endpoint intersection and that case was already handled above
  3357. if (pt === null)
  3358. return null;
  3359. // is the intersection found between the lines not on the segments?
  3360. if (!isInBbox(bboxOverlap, pt))
  3361. return null;
  3362. // round the the computed point if needed
  3363. return precision.snap(pt);
  3364. }
  3365. /**
  3366. * Split the given segment into multiple segments on the given points.
  3367. * * Each existing segment will retain its leftSE and a new rightSE will be
  3368. * generated for it.
  3369. * * A new segment will be generated which will adopt the original segment's
  3370. * rightSE, and a new leftSE will be generated for it.
  3371. * * If there are more than two points given to split on, new segments
  3372. * in the middle will be generated with new leftSE and rightSE's.
  3373. * * An array of the newly generated SweepEvents will be returned.
  3374. *
  3375. * Warning: input array of points is modified
  3376. */
  3377. split(point) {
  3378. const newEvents = [];
  3379. const alreadyLinked = point.events !== undefined;
  3380. const newLeftSE = new SweepEvent(point, true);
  3381. const newRightSE = new SweepEvent(point, false);
  3382. const oldRightSE = this.rightSE;
  3383. this.replaceRightSE(newRightSE);
  3384. newEvents.push(newRightSE);
  3385. newEvents.push(newLeftSE);
  3386. const newSeg = new Segment(newLeftSE, oldRightSE, this.rings.slice(), this.windings.slice());
  3387. // when splitting a nearly vertical downward-facing segment,
  3388. // sometimes one of the resulting new segments is vertical, in which
  3389. // case its left and right events may need to be swapped
  3390. if (SweepEvent.comparePoints(newSeg.leftSE.point, newSeg.rightSE.point) > 0) {
  3391. newSeg.swapEvents();
  3392. }
  3393. if (SweepEvent.comparePoints(this.leftSE.point, this.rightSE.point) > 0) {
  3394. this.swapEvents();
  3395. }
  3396. // in the point we just used to create new sweep events with was already
  3397. // linked to other events, we need to check if either of the affected
  3398. // segments should be consumed
  3399. if (alreadyLinked) {
  3400. newLeftSE.checkForConsuming();
  3401. newRightSE.checkForConsuming();
  3402. }
  3403. return newEvents;
  3404. }
  3405. /* Swap which event is left and right */
  3406. swapEvents() {
  3407. const tmpEvt = this.rightSE;
  3408. this.rightSE = this.leftSE;
  3409. this.leftSE = tmpEvt;
  3410. this.leftSE.isLeft = true;
  3411. this.rightSE.isLeft = false;
  3412. for (let i = 0, iMax = this.windings.length; i < iMax; i++) {
  3413. this.windings[i] *= -1;
  3414. }
  3415. }
  3416. /* Consume another segment. We take their rings under our wing
  3417. * and mark them as consumed. Use for perfectly overlapping segments */
  3418. consume(other) {
  3419. let consumer = this;
  3420. let consumee = other;
  3421. while (consumer.consumedBy)
  3422. consumer = consumer.consumedBy;
  3423. while (consumee.consumedBy)
  3424. consumee = consumee.consumedBy;
  3425. const cmp = Segment.compare(consumer, consumee);
  3426. if (cmp === 0)
  3427. return; // already consumed
  3428. // the winner of the consumption is the earlier segment
  3429. // according to sweep line ordering
  3430. if (cmp > 0) {
  3431. const tmp = consumer;
  3432. consumer = consumee;
  3433. consumee = tmp;
  3434. }
  3435. // make sure a segment doesn't consume it's prev
  3436. if (consumer.prev === consumee) {
  3437. const tmp = consumer;
  3438. consumer = consumee;
  3439. consumee = tmp;
  3440. }
  3441. for (let i = 0, iMax = consumee.rings.length; i < iMax; i++) {
  3442. const ring = consumee.rings[i];
  3443. const winding = consumee.windings[i];
  3444. const index = consumer.rings.indexOf(ring);
  3445. if (index === -1) {
  3446. consumer.rings.push(ring);
  3447. consumer.windings.push(winding);
  3448. }
  3449. else
  3450. consumer.windings[index] += winding;
  3451. }
  3452. consumee.rings = null;
  3453. consumee.windings = null;
  3454. consumee.consumedBy = consumer;
  3455. // mark sweep events consumed as to maintain ordering in sweep event queue
  3456. consumee.leftSE.consumedBy = consumer.leftSE;
  3457. consumee.rightSE.consumedBy = consumer.rightSE;
  3458. }
  3459. /* The first segment previous segment chain that is in the result */
  3460. prevInResult() {
  3461. if (this._prevInResult !== undefined)
  3462. return this._prevInResult;
  3463. if (!this.prev)
  3464. this._prevInResult = null;
  3465. else if (this.prev.isInResult())
  3466. this._prevInResult = this.prev;
  3467. else
  3468. this._prevInResult = this.prev.prevInResult();
  3469. return this._prevInResult;
  3470. }
  3471. beforeState() {
  3472. if (this._beforeState !== undefined)
  3473. return this._beforeState;
  3474. if (!this.prev)
  3475. this._beforeState = {
  3476. rings: [],
  3477. windings: [],
  3478. multiPolys: [],
  3479. };
  3480. else {
  3481. const seg = this.prev.consumedBy || this.prev;
  3482. this._beforeState = seg.afterState();
  3483. }
  3484. return this._beforeState;
  3485. }
  3486. afterState() {
  3487. if (this._afterState !== undefined)
  3488. return this._afterState;
  3489. const beforeState = this.beforeState();
  3490. this._afterState = {
  3491. rings: beforeState.rings.slice(0),
  3492. windings: beforeState.windings.slice(0),
  3493. multiPolys: [],
  3494. };
  3495. const ringsAfter = this._afterState.rings;
  3496. const windingsAfter = this._afterState.windings;
  3497. const mpsAfter = this._afterState.multiPolys;
  3498. // calculate ringsAfter, windingsAfter
  3499. for (let i = 0, iMax = this.rings.length; i < iMax; i++) {
  3500. const ring = this.rings[i];
  3501. const winding = this.windings[i];
  3502. const index = ringsAfter.indexOf(ring);
  3503. if (index === -1) {
  3504. ringsAfter.push(ring);
  3505. windingsAfter.push(winding);
  3506. }
  3507. else
  3508. windingsAfter[index] += winding;
  3509. }
  3510. // calcualte polysAfter
  3511. const polysAfter = [];
  3512. const polysExclude = [];
  3513. for (let i = 0, iMax = ringsAfter.length; i < iMax; i++) {
  3514. if (windingsAfter[i] === 0)
  3515. continue; // non-zero rule
  3516. const ring = ringsAfter[i];
  3517. const poly = ring.poly;
  3518. if (polysExclude.indexOf(poly) !== -1)
  3519. continue;
  3520. if (ring.isExterior)
  3521. polysAfter.push(poly);
  3522. else {
  3523. if (polysExclude.indexOf(poly) === -1)
  3524. polysExclude.push(poly);
  3525. const index = polysAfter.indexOf(ring.poly);
  3526. if (index !== -1)
  3527. polysAfter.splice(index, 1);
  3528. }
  3529. }
  3530. // calculate multiPolysAfter
  3531. for (let i = 0, iMax = polysAfter.length; i < iMax; i++) {
  3532. const mp = polysAfter[i].multiPoly;
  3533. if (mpsAfter.indexOf(mp) === -1)
  3534. mpsAfter.push(mp);
  3535. }
  3536. return this._afterState;
  3537. }
  3538. /* Is this segment part of the final result? */
  3539. isInResult() {
  3540. // if we've been consumed, we're not in the result
  3541. if (this.consumedBy)
  3542. return false;
  3543. if (this._isInResult !== undefined)
  3544. return this._isInResult;
  3545. const mpsBefore = this.beforeState().multiPolys;
  3546. const mpsAfter = this.afterState().multiPolys;
  3547. switch (operation.type) {
  3548. case "union": {
  3549. // UNION - included iff:
  3550. // * On one side of us there is 0 poly interiors AND
  3551. // * On the other side there is 1 or more.
  3552. const noBefores = mpsBefore.length === 0;
  3553. const noAfters = mpsAfter.length === 0;
  3554. this._isInResult = noBefores !== noAfters;
  3555. break;
  3556. }
  3557. case "intersection": {
  3558. // INTERSECTION - included iff:
  3559. // * on one side of us all multipolys are rep. with poly interiors AND
  3560. // * on the other side of us, not all multipolys are repsented
  3561. // with poly interiors
  3562. let least;
  3563. let most;
  3564. if (mpsBefore.length < mpsAfter.length) {
  3565. least = mpsBefore.length;
  3566. most = mpsAfter.length;
  3567. }
  3568. else {
  3569. least = mpsAfter.length;
  3570. most = mpsBefore.length;
  3571. }
  3572. this._isInResult = most === operation.numMultiPolys && least < most;
  3573. break;
  3574. }
  3575. case "xor": {
  3576. // XOR - included iff:
  3577. // * the difference between the number of multipolys represented
  3578. // with poly interiors on our two sides is an odd number
  3579. const diff = Math.abs(mpsBefore.length - mpsAfter.length);
  3580. this._isInResult = diff % 2 === 1;
  3581. break;
  3582. }
  3583. case "difference": {
  3584. // DIFFERENCE included iff:
  3585. // * on exactly one side, we have just the subject
  3586. const isJustSubject = (mps) => mps.length === 1 && mps[0].isSubject;
  3587. this._isInResult = isJustSubject(mpsBefore) !== isJustSubject(mpsAfter);
  3588. break;
  3589. }
  3590. }
  3591. return this._isInResult;
  3592. }
  3593. }
  3594. class RingIn {
  3595. poly;
  3596. isExterior;
  3597. segments;
  3598. bbox;
  3599. constructor(geomRing, poly, isExterior) {
  3600. if (!Array.isArray(geomRing) || geomRing.length === 0) {
  3601. throw new Error("Input geometry is not a valid Polygon or MultiPolygon");
  3602. }
  3603. this.poly = poly;
  3604. this.isExterior = isExterior;
  3605. this.segments = [];
  3606. if (typeof geomRing[0][0] !== "number" ||
  3607. typeof geomRing[0][1] !== "number") {
  3608. throw new Error("Input geometry is not a valid Polygon or MultiPolygon");
  3609. }
  3610. const firstPoint = precision.snap({ x: new BigNumber(geomRing[0][0]), y: new BigNumber(geomRing[0][1]) });
  3611. this.bbox = {
  3612. ll: { x: firstPoint.x, y: firstPoint.y },
  3613. ur: { x: firstPoint.x, y: firstPoint.y },
  3614. };
  3615. let prevPoint = firstPoint;
  3616. for (let i = 1, iMax = geomRing.length; i < iMax; i++) {
  3617. if (typeof geomRing[i][0] !== "number" ||
  3618. typeof geomRing[i][1] !== "number") {
  3619. throw new Error("Input geometry is not a valid Polygon or MultiPolygon");
  3620. }
  3621. const point = precision.snap({ x: new BigNumber(geomRing[i][0]), y: new BigNumber(geomRing[i][1]) });
  3622. // skip repeated points
  3623. if (point.x.eq(prevPoint.x) && point.y.eq(prevPoint.y))
  3624. continue;
  3625. this.segments.push(Segment.fromRing(prevPoint, point, this));
  3626. if (point.x.isLessThan(this.bbox.ll.x))
  3627. this.bbox.ll.x = point.x;
  3628. if (point.y.isLessThan(this.bbox.ll.y))
  3629. this.bbox.ll.y = point.y;
  3630. if (point.x.isGreaterThan(this.bbox.ur.x))
  3631. this.bbox.ur.x = point.x;
  3632. if (point.y.isGreaterThan(this.bbox.ur.y))
  3633. this.bbox.ur.y = point.y;
  3634. prevPoint = point;
  3635. }
  3636. // add segment from last to first if last is not the same as first
  3637. if (!firstPoint.x.eq(prevPoint.x) || !firstPoint.y.eq(prevPoint.y)) {
  3638. this.segments.push(Segment.fromRing(prevPoint, firstPoint, this));
  3639. }
  3640. }
  3641. getSweepEvents() {
  3642. const sweepEvents = [];
  3643. for (let i = 0, iMax = this.segments.length; i < iMax; i++) {
  3644. const segment = this.segments[i];
  3645. sweepEvents.push(segment.leftSE);
  3646. sweepEvents.push(segment.rightSE);
  3647. }
  3648. return sweepEvents;
  3649. }
  3650. }
  3651. class PolyIn {
  3652. multiPoly;
  3653. exteriorRing;
  3654. interiorRings;
  3655. bbox;
  3656. constructor(geomPoly, multiPoly) {
  3657. if (!Array.isArray(geomPoly)) {
  3658. throw new Error("Input geometry is not a valid Polygon or MultiPolygon");
  3659. }
  3660. this.exteriorRing = new RingIn(geomPoly[0], this, true);
  3661. // copy by value
  3662. this.bbox = {
  3663. ll: { x: this.exteriorRing.bbox.ll.x, y: this.exteriorRing.bbox.ll.y },
  3664. ur: { x: this.exteriorRing.bbox.ur.x, y: this.exteriorRing.bbox.ur.y },
  3665. };
  3666. this.interiorRings = [];
  3667. for (let i = 1, iMax = geomPoly.length; i < iMax; i++) {
  3668. const ring = new RingIn(geomPoly[i], this, false);
  3669. if (ring.bbox.ll.x.isLessThan(this.bbox.ll.x))
  3670. this.bbox.ll.x = ring.bbox.ll.x;
  3671. if (ring.bbox.ll.y.isLessThan(this.bbox.ll.y))
  3672. this.bbox.ll.y = ring.bbox.ll.y;
  3673. if (ring.bbox.ur.x.isGreaterThan(this.bbox.ur.x))
  3674. this.bbox.ur.x = ring.bbox.ur.x;
  3675. if (ring.bbox.ur.y.isGreaterThan(this.bbox.ur.y))
  3676. this.bbox.ur.y = ring.bbox.ur.y;
  3677. this.interiorRings.push(ring);
  3678. }
  3679. this.multiPoly = multiPoly;
  3680. }
  3681. getSweepEvents() {
  3682. const sweepEvents = this.exteriorRing.getSweepEvents();
  3683. for (let i = 0, iMax = this.interiorRings.length; i < iMax; i++) {
  3684. const ringSweepEvents = this.interiorRings[i].getSweepEvents();
  3685. for (let j = 0, jMax = ringSweepEvents.length; j < jMax; j++) {
  3686. sweepEvents.push(ringSweepEvents[j]);
  3687. }
  3688. }
  3689. return sweepEvents;
  3690. }
  3691. }
  3692. class MultiPolyIn {
  3693. isSubject;
  3694. polys;
  3695. bbox;
  3696. constructor(geom, isSubject) {
  3697. if (!Array.isArray(geom)) {
  3698. throw new Error("Input geometry is not a valid Polygon or MultiPolygon");
  3699. }
  3700. try {
  3701. // if the input looks like a polygon, convert it to a multipolygon
  3702. if (typeof geom[0][0][0] === "number")
  3703. geom = [geom];
  3704. }
  3705. catch (ex) {
  3706. // The input is either malformed or has empty arrays.
  3707. // In either case, it will be handled later on.
  3708. }
  3709. this.polys = [];
  3710. this.bbox = {
  3711. ll: { x: new BigNumber(Number.POSITIVE_INFINITY), y: new BigNumber(Number.POSITIVE_INFINITY) },
  3712. ur: { x: new BigNumber(Number.NEGATIVE_INFINITY), y: new BigNumber(Number.NEGATIVE_INFINITY) },
  3713. };
  3714. for (let i = 0, iMax = geom.length; i < iMax; i++) {
  3715. const poly = new PolyIn(geom[i], this);
  3716. if (poly.bbox.ll.x.isLessThan(this.bbox.ll.x))
  3717. this.bbox.ll.x = poly.bbox.ll.x;
  3718. if (poly.bbox.ll.y.isLessThan(this.bbox.ll.y))
  3719. this.bbox.ll.y = poly.bbox.ll.y;
  3720. if (poly.bbox.ur.x.isGreaterThan(this.bbox.ur.x))
  3721. this.bbox.ur.x = poly.bbox.ur.x;
  3722. if (poly.bbox.ur.y.isGreaterThan(this.bbox.ur.y))
  3723. this.bbox.ur.y = poly.bbox.ur.y;
  3724. this.polys.push(poly);
  3725. }
  3726. this.isSubject = isSubject;
  3727. }
  3728. getSweepEvents() {
  3729. const sweepEvents = [];
  3730. for (let i = 0, iMax = this.polys.length; i < iMax; i++) {
  3731. const polySweepEvents = this.polys[i].getSweepEvents();
  3732. for (let j = 0, jMax = polySweepEvents.length; j < jMax; j++) {
  3733. sweepEvents.push(polySweepEvents[j]);
  3734. }
  3735. }
  3736. return sweepEvents;
  3737. }
  3738. }
  3739. class RingOut {
  3740. events;
  3741. poly;
  3742. _isExteriorRing;
  3743. _enclosingRing;
  3744. /* Given the segments from the sweep line pass, compute & return a series
  3745. * of closed rings from all the segments marked to be part of the result */
  3746. static factory(allSegments) {
  3747. const ringsOut = [];
  3748. for (let i = 0, iMax = allSegments.length; i < iMax; i++) {
  3749. const segment = allSegments[i];
  3750. if (!segment.isInResult() || segment.ringOut)
  3751. continue;
  3752. let prevEvent = null;
  3753. let event = segment.leftSE;
  3754. let nextEvent = segment.rightSE;
  3755. const events = [event];
  3756. const startingPoint = event.point;
  3757. const intersectionLEs = [];
  3758. /* Walk the chain of linked events to form a closed ring */
  3759. while (true) {
  3760. prevEvent = event;
  3761. event = nextEvent;
  3762. events.push(event);
  3763. /* Is the ring complete? */
  3764. if (event.point === startingPoint)
  3765. break;
  3766. while (true) {
  3767. const availableLEs = event.getAvailableLinkedEvents();
  3768. /* Did we hit a dead end? This shouldn't happen. Indicates some earlier
  3769. * part of the algorithm malfunctioned... please file a bug report. */
  3770. if (availableLEs.length === 0) {
  3771. const firstPt = events[0].point;
  3772. const lastPt = events[events.length - 1].point;
  3773. throw new Error(`Unable to complete output ring starting at [${firstPt.x},` +
  3774. ` ${firstPt.y}]. Last matching segment found ends at` +
  3775. ` [${lastPt.x}, ${lastPt.y}].`);
  3776. }
  3777. /* Only one way to go, so cotinue on the path */
  3778. if (availableLEs.length === 1) {
  3779. nextEvent = availableLEs[0].otherSE;
  3780. break;
  3781. }
  3782. /* We must have an intersection. Check for a completed loop */
  3783. let indexLE = null;
  3784. for (let j = 0, jMax = intersectionLEs.length; j < jMax; j++) {
  3785. if (intersectionLEs[j].point === event.point) {
  3786. indexLE = j;
  3787. break;
  3788. }
  3789. }
  3790. /* Found a completed loop. Cut that off and make a ring */
  3791. if (indexLE !== null) {
  3792. const intersectionLE = intersectionLEs.splice(indexLE)[0];
  3793. const ringEvents = events.splice(intersectionLE.index);
  3794. ringEvents.unshift(ringEvents[0].otherSE);
  3795. ringsOut.push(new RingOut(ringEvents.reverse()));
  3796. continue;
  3797. }
  3798. /* register the intersection */
  3799. intersectionLEs.push({
  3800. index: events.length,
  3801. point: event.point,
  3802. });
  3803. /* Choose the left-most option to continue the walk */
  3804. const comparator = event.getLeftmostComparator(prevEvent);
  3805. nextEvent = availableLEs.sort(comparator)[0].otherSE;
  3806. break;
  3807. }
  3808. }
  3809. ringsOut.push(new RingOut(events));
  3810. }
  3811. return ringsOut;
  3812. }
  3813. constructor(events) {
  3814. this.events = events;
  3815. for (let i = 0, iMax = events.length; i < iMax; i++) {
  3816. events[i].segment.ringOut = this;
  3817. }
  3818. this.poly = null;
  3819. }
  3820. getGeom() {
  3821. // Remove superfluous points (ie extra points along a straight line),
  3822. let prevPt = this.events[0].point;
  3823. const points = [prevPt];
  3824. for (let i = 1, iMax = this.events.length - 1; i < iMax; i++) {
  3825. const pt = this.events[i].point;
  3826. const nextPt = this.events[i + 1].point;
  3827. if (precision.orient(pt, prevPt, nextPt) === 0)
  3828. continue;
  3829. points.push(pt);
  3830. prevPt = pt;
  3831. }
  3832. // ring was all (within rounding error of angle calc) colinear points
  3833. if (points.length === 1)
  3834. return null;
  3835. // check if the starting point is necessary
  3836. const pt = points[0];
  3837. const nextPt = points[1];
  3838. if (precision.orient(pt, prevPt, nextPt) === 0)
  3839. points.shift();
  3840. points.push(points[0]);
  3841. const step = this.isExteriorRing() ? 1 : -1;
  3842. const iStart = this.isExteriorRing() ? 0 : points.length - 1;
  3843. const iEnd = this.isExteriorRing() ? points.length : -1;
  3844. const orderedPoints = [];
  3845. for (let i = iStart; i != iEnd; i += step)
  3846. orderedPoints.push([points[i].x.toNumber(), points[i].y.toNumber()]);
  3847. return orderedPoints;
  3848. }
  3849. isExteriorRing() {
  3850. if (this._isExteriorRing === undefined) {
  3851. const enclosing = this.enclosingRing();
  3852. this._isExteriorRing = enclosing ? !enclosing.isExteriorRing() : true;
  3853. }
  3854. return this._isExteriorRing;
  3855. }
  3856. enclosingRing() {
  3857. if (this._enclosingRing === undefined) {
  3858. this._enclosingRing = this._calcEnclosingRing();
  3859. }
  3860. return this._enclosingRing;
  3861. }
  3862. /* Returns the ring that encloses this one, if any */
  3863. _calcEnclosingRing() {
  3864. // start with the ealier sweep line event so that the prevSeg
  3865. // chain doesn't lead us inside of a loop of ours
  3866. let leftMostEvt = this.events[0];
  3867. for (let i = 1, iMax = this.events.length; i < iMax; i++) {
  3868. const evt = this.events[i];
  3869. if (SweepEvent.compare(leftMostEvt, evt) > 0)
  3870. leftMostEvt = evt;
  3871. }
  3872. let prevSeg = leftMostEvt.segment.prevInResult();
  3873. let prevPrevSeg = prevSeg ? prevSeg.prevInResult() : null;
  3874. while (true) {
  3875. // no segment found, thus no ring can enclose us
  3876. if (!prevSeg)
  3877. return null;
  3878. // no segments below prev segment found, thus the ring of the prev
  3879. // segment must loop back around and enclose us
  3880. if (!prevPrevSeg)
  3881. return prevSeg.ringOut;
  3882. // if the two segments are of different rings, the ring of the prev
  3883. // segment must either loop around us or the ring of the prev prev
  3884. // seg, which would make us and the ring of the prev peers
  3885. if (prevPrevSeg.ringOut !== prevSeg.ringOut) {
  3886. if (prevPrevSeg.ringOut?.enclosingRing() !== prevSeg.ringOut) {
  3887. return prevSeg.ringOut;
  3888. }
  3889. else
  3890. return prevSeg.ringOut?.enclosingRing();
  3891. }
  3892. // two segments are from the same ring, so this was a penisula
  3893. // of that ring. iterate downward, keep searching
  3894. prevSeg = prevPrevSeg.prevInResult();
  3895. prevPrevSeg = prevSeg ? prevSeg.prevInResult() : null;
  3896. }
  3897. }
  3898. }
  3899. class PolyOut {
  3900. exteriorRing;
  3901. interiorRings;
  3902. constructor(exteriorRing) {
  3903. this.exteriorRing = exteriorRing;
  3904. exteriorRing.poly = this;
  3905. this.interiorRings = [];
  3906. }
  3907. addInterior(ring) {
  3908. this.interiorRings.push(ring);
  3909. ring.poly = this;
  3910. }
  3911. getGeom() {
  3912. const geom0 = this.exteriorRing.getGeom();
  3913. // exterior ring was all (within rounding error of angle calc) colinear points
  3914. if (geom0 === null)
  3915. return null;
  3916. const geom = [geom0];
  3917. for (let i = 0, iMax = this.interiorRings.length; i < iMax; i++) {
  3918. const ringGeom = this.interiorRings[i].getGeom();
  3919. // interior ring was all (within rounding error of angle calc) colinear points
  3920. if (ringGeom === null)
  3921. continue;
  3922. geom.push(ringGeom);
  3923. }
  3924. return geom;
  3925. }
  3926. }
  3927. class MultiPolyOut {
  3928. rings;
  3929. polys;
  3930. constructor(rings) {
  3931. this.rings = rings;
  3932. this.polys = this._composePolys(rings);
  3933. }
  3934. getGeom() {
  3935. const geom = [];
  3936. for (let i = 0, iMax = this.polys.length; i < iMax; i++) {
  3937. const polyGeom = this.polys[i].getGeom();
  3938. // exterior ring was all (within rounding error of angle calc) colinear points
  3939. if (polyGeom === null)
  3940. continue;
  3941. geom.push(polyGeom);
  3942. }
  3943. return geom;
  3944. }
  3945. _composePolys(rings) {
  3946. const polys = [];
  3947. for (let i = 0, iMax = rings.length; i < iMax; i++) {
  3948. const ring = rings[i];
  3949. if (ring.poly)
  3950. continue;
  3951. if (ring.isExteriorRing())
  3952. polys.push(new PolyOut(ring));
  3953. else {
  3954. const enclosingRing = ring.enclosingRing();
  3955. if (!enclosingRing?.poly)
  3956. polys.push(new PolyOut(enclosingRing));
  3957. enclosingRing?.poly?.addInterior(ring);
  3958. }
  3959. }
  3960. return polys;
  3961. }
  3962. }
  3963. /**
  3964. * NOTE: We must be careful not to change any segments while
  3965. * they are in the SplayTree. AFAIK, there's no way to tell
  3966. * the tree to rebalance itself - thus before splitting
  3967. * a segment that's in the tree, we remove it from the tree,
  3968. * do the split, then re-insert it. (Even though splitting a
  3969. * segment *shouldn't* change its correct position in the
  3970. * sweep line tree, the reality is because of rounding errors,
  3971. * it sometimes does.)
  3972. */
  3973. class SweepLine {
  3974. queue;
  3975. tree;
  3976. segments;
  3977. constructor(queue, comparator = Segment.compare) {
  3978. this.queue = queue;
  3979. this.tree = new SplayTreeSet(comparator);
  3980. this.segments = [];
  3981. }
  3982. process(event) {
  3983. const segment = event.segment;
  3984. const newEvents = [];
  3985. // if we've already been consumed by another segment,
  3986. // clean up our body parts and get out
  3987. if (event.consumedBy) {
  3988. if (event.isLeft)
  3989. this.queue.delete(event.otherSE);
  3990. else
  3991. this.tree.delete(segment);
  3992. return newEvents;
  3993. }
  3994. if (event.isLeft)
  3995. this.tree.add(segment);
  3996. let prevSeg = segment;
  3997. let nextSeg = segment;
  3998. // skip consumed segments still in tree
  3999. do {
  4000. prevSeg = this.tree.lastBefore(prevSeg);
  4001. } while (prevSeg != null && prevSeg.consumedBy != undefined);
  4002. // skip consumed segments still in tree
  4003. do {
  4004. nextSeg = this.tree.firstAfter(nextSeg);
  4005. } while (nextSeg != null && nextSeg.consumedBy != undefined);
  4006. if (event.isLeft) {
  4007. // Check for intersections against the previous segment in the sweep line
  4008. let prevMySplitter = null;
  4009. if (prevSeg) {
  4010. const prevInter = prevSeg.getIntersection(segment);
  4011. if (prevInter !== null) {
  4012. if (!segment.isAnEndpoint(prevInter))
  4013. prevMySplitter = prevInter;
  4014. if (!prevSeg.isAnEndpoint(prevInter)) {
  4015. const newEventsFromSplit = this._splitSafely(prevSeg, prevInter);
  4016. for (let i = 0, iMax = newEventsFromSplit.length; i < iMax; i++) {
  4017. newEvents.push(newEventsFromSplit[i]);
  4018. }
  4019. }
  4020. }
  4021. }
  4022. // Check for intersections against the next segment in the sweep line
  4023. let nextMySplitter = null;
  4024. if (nextSeg) {
  4025. const nextInter = nextSeg.getIntersection(segment);
  4026. if (nextInter !== null) {
  4027. if (!segment.isAnEndpoint(nextInter))
  4028. nextMySplitter = nextInter;
  4029. if (!nextSeg.isAnEndpoint(nextInter)) {
  4030. const newEventsFromSplit = this._splitSafely(nextSeg, nextInter);
  4031. for (let i = 0, iMax = newEventsFromSplit.length; i < iMax; i++) {
  4032. newEvents.push(newEventsFromSplit[i]);
  4033. }
  4034. }
  4035. }
  4036. }
  4037. // For simplicity, even if we find more than one intersection we only
  4038. // spilt on the 'earliest' (sweep-line style) of the intersections.
  4039. // The other intersection will be handled in a future process().
  4040. if (prevMySplitter !== null || nextMySplitter !== null) {
  4041. let mySplitter = null;
  4042. if (prevMySplitter === null)
  4043. mySplitter = nextMySplitter;
  4044. else if (nextMySplitter === null)
  4045. mySplitter = prevMySplitter;
  4046. else {
  4047. const cmpSplitters = SweepEvent.comparePoints(prevMySplitter, nextMySplitter);
  4048. mySplitter = cmpSplitters <= 0 ? prevMySplitter : nextMySplitter;
  4049. }
  4050. // Rounding errors can cause changes in ordering,
  4051. // so remove afected segments and right sweep events before splitting
  4052. this.queue.delete(segment.rightSE);
  4053. newEvents.push(segment.rightSE);
  4054. const newEventsFromSplit = segment.split(mySplitter);
  4055. for (let i = 0, iMax = newEventsFromSplit.length; i < iMax; i++) {
  4056. newEvents.push(newEventsFromSplit[i]);
  4057. }
  4058. }
  4059. if (newEvents.length > 0) {
  4060. // We found some intersections, so re-do the current event to
  4061. // make sure sweep line ordering is totally consistent for later
  4062. // use with the segment 'prev' pointers
  4063. this.tree.delete(segment);
  4064. newEvents.push(event);
  4065. }
  4066. else {
  4067. // done with left event
  4068. this.segments.push(segment);
  4069. segment.prev = prevSeg;
  4070. }
  4071. }
  4072. else {
  4073. // event.isRight
  4074. // since we're about to be removed from the sweep line, check for
  4075. // intersections between our previous and next segments
  4076. if (prevSeg && nextSeg) {
  4077. const inter = prevSeg.getIntersection(nextSeg);
  4078. if (inter !== null) {
  4079. if (!prevSeg.isAnEndpoint(inter)) {
  4080. const newEventsFromSplit = this._splitSafely(prevSeg, inter);
  4081. for (let i = 0, iMax = newEventsFromSplit.length; i < iMax; i++) {
  4082. newEvents.push(newEventsFromSplit[i]);
  4083. }
  4084. }
  4085. if (!nextSeg.isAnEndpoint(inter)) {
  4086. const newEventsFromSplit = this._splitSafely(nextSeg, inter);
  4087. for (let i = 0, iMax = newEventsFromSplit.length; i < iMax; i++) {
  4088. newEvents.push(newEventsFromSplit[i]);
  4089. }
  4090. }
  4091. }
  4092. }
  4093. this.tree.delete(segment);
  4094. }
  4095. return newEvents;
  4096. }
  4097. /* Safely split a segment that is currently in the datastructures
  4098. * IE - a segment other than the one that is currently being processed. */
  4099. _splitSafely(seg, pt) {
  4100. // Rounding errors can cause changes in ordering,
  4101. // so remove afected segments and right sweep events before splitting
  4102. // removeNode() doesn't work, so have re-find the seg
  4103. // https://github.com/w8r/splay-tree/pull/5
  4104. this.tree.delete(seg);
  4105. const rightSE = seg.rightSE;
  4106. this.queue.delete(rightSE);
  4107. const newEvents = seg.split(pt);
  4108. newEvents.push(rightSE);
  4109. // splitting can trigger consumption
  4110. if (seg.consumedBy === undefined)
  4111. this.tree.add(seg);
  4112. return newEvents;
  4113. }
  4114. }
  4115. class Operation {
  4116. type;
  4117. numMultiPolys;
  4118. run(type, geom, moreGeoms) {
  4119. operation.type = type;
  4120. /* Convert inputs to MultiPoly objects */
  4121. const multipolys = [new MultiPolyIn(geom, true)];
  4122. for (let i = 0, iMax = moreGeoms.length; i < iMax; i++) {
  4123. multipolys.push(new MultiPolyIn(moreGeoms[i], false));
  4124. }
  4125. operation.numMultiPolys = multipolys.length;
  4126. /* BBox optimization for difference operation
  4127. * If the bbox of a multipolygon that's part of the clipping doesn't
  4128. * intersect the bbox of the subject at all, we can just drop that
  4129. * multiploygon. */
  4130. if (operation.type === "difference") {
  4131. // in place removal
  4132. const subject = multipolys[0];
  4133. let i = 1;
  4134. while (i < multipolys.length) {
  4135. if (getBboxOverlap(multipolys[i].bbox, subject.bbox) !== null)
  4136. i++;
  4137. else
  4138. multipolys.splice(i, 1);
  4139. }
  4140. }
  4141. /* BBox optimization for intersection operation
  4142. * If we can find any pair of multipolygons whose bbox does not overlap,
  4143. * then the result will be empty. */
  4144. if (operation.type === "intersection") {
  4145. // TODO: this is O(n^2) in number of polygons. By sorting the bboxes,
  4146. // it could be optimized to O(n * ln(n))
  4147. for (let i = 0, iMax = multipolys.length; i < iMax; i++) {
  4148. const mpA = multipolys[i];
  4149. for (let j = i + 1, jMax = multipolys.length; j < jMax; j++) {
  4150. if (getBboxOverlap(mpA.bbox, multipolys[j].bbox) === null)
  4151. return [];
  4152. }
  4153. }
  4154. }
  4155. /* Put segment endpoints in a priority queue */
  4156. const queue = new SplayTreeSet(SweepEvent.compare);
  4157. for (let i = 0, iMax = multipolys.length; i < iMax; i++) {
  4158. const sweepEvents = multipolys[i].getSweepEvents();
  4159. for (let j = 0, jMax = sweepEvents.length; j < jMax; j++) {
  4160. queue.add(sweepEvents[j]);
  4161. }
  4162. }
  4163. /* Pass the sweep line over those endpoints */
  4164. const sweepLine = new SweepLine(queue);
  4165. let evt = null;
  4166. if (queue.size != 0) {
  4167. evt = queue.first();
  4168. queue.delete(evt);
  4169. }
  4170. while (evt) {
  4171. const newEvents = sweepLine.process(evt);
  4172. for (let i = 0, iMax = newEvents.length; i < iMax; i++) {
  4173. const evt = newEvents[i];
  4174. if (evt.consumedBy === undefined)
  4175. queue.add(evt);
  4176. }
  4177. if (queue.size != 0) {
  4178. evt = queue.first();
  4179. queue.delete(evt);
  4180. }
  4181. else {
  4182. evt = null;
  4183. }
  4184. }
  4185. // free some memory we don't need anymore
  4186. precision.reset();
  4187. /* Collect and compile segments we're keeping into a multipolygon */
  4188. const ringsOut = RingOut.factory(sweepLine.segments);
  4189. const result = new MultiPolyOut(ringsOut);
  4190. return result.getGeom();
  4191. }
  4192. }
  4193. // singleton available by import
  4194. const operation = new Operation();
  4195. const union = (geom, ...moreGeoms) => operation.run("union", geom, moreGeoms);
  4196. const intersection = (geom, ...moreGeoms) => operation.run("intersection", geom, moreGeoms);
  4197. const xor = (geom, ...moreGeoms) => operation.run("xor", geom, moreGeoms);
  4198. const difference = (geom, ...moreGeoms) => operation.run("difference", geom, moreGeoms);
  4199. const setPrecision = precision.set;
  4200. exports.difference = difference;
  4201. exports.intersection = intersection;
  4202. exports.setPrecision = setPrecision;
  4203. exports.union = union;
  4204. exports.version = version;
  4205. exports.xor = xor;
  4206. Object.defineProperty(exports, '__esModule', { value: true });
  4207. }));