PHP and Javascript implementations of a simple markdown parser
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970
  1. /**
  2. * Base spreadsheet calculation error class.
  3. */
  4. class CellException extends Error {
  5. /**
  6. * Brief symbol to show in the cell to signify an error occurred during
  7. * evaluation.
  8. *
  9. * @type {string}
  10. */
  11. errorSymbol;
  12. /**
  13. * @param {string} message - error message
  14. * @param {string} errorSymbol - symbol to show in the cell to indicate an error
  15. */
  16. constructor(message, errorSymbol='#ERROR') {
  17. super(message);
  18. this.errorSymbol = errorSymbol;
  19. }
  20. }
  21. /**
  22. * Exception thrown when a spreadsheet expression is invalid.
  23. */
  24. class CellSyntaxException extends CellException {
  25. constructor(message, errorSymbol='#SYNTAX') {
  26. super(message, errorSymbol);
  27. }
  28. }
  29. /**
  30. * Exception thrown when a problem occurrs during evaluation.
  31. */
  32. class CellEvaluationException extends CellException {}
  33. /**
  34. * Exception thrown when cell dependencies cannot be resolved.
  35. */
  36. class CellDependencyException extends CellException {
  37. constructor(message, errorSymbol='#REF') {
  38. super(message, errorSymbol);
  39. }
  40. }
  41. /**
  42. * Expression parsing token types.
  43. */
  44. class CellExpressionTokenType {
  45. static Name = new this('Name');
  46. static Address = new this('Address');
  47. static NameOrAddress = new this('NameOrAddress');
  48. static String = new this('String');
  49. static Number = new this('Number');
  50. static OpenParen = new this('OpenParen');
  51. static CloseParen = new this('CloseParen');
  52. static Colon = new this('Colon');
  53. static Plus = new this('Plus');
  54. static Minus = new this('Minus');
  55. static Multiply = new this('Multiply');
  56. static Divide = new this('Divide');
  57. static Comma = new this('Comma');
  58. static Semicolon = new this('Semicolon');
  59. static Ampersand = new this('Ampersand');
  60. static LessThan = new this('LessThan');
  61. static LessThanEqual = new this('LessThanEqual');
  62. static GreaterThan = new this('GreaterThan');
  63. static GreaterThanEqual = new this('GreaterThanEqual');
  64. static Equal = new this('Equal');
  65. static Unequal = new this('Unequal');
  66. static Not = new this('Not');
  67. /** @type {string} */
  68. name;
  69. constructor(name) {
  70. this.name = name;
  71. }
  72. /**
  73. * @returns {boolean}
  74. */
  75. isPotentialName() {
  76. return this === CellExpressionTokenType.Name || this === CellExpressionTokenType.NameOrAddress;
  77. }
  78. /**
  79. * @returns {boolean}
  80. */
  81. isPotentialAddress() {
  82. return this === CellExpressionTokenType.Address || this === CellExpressionTokenType.NameOrAddress;
  83. }
  84. toString() {
  85. return this.name;
  86. }
  87. equals(other) {
  88. if (!(other instanceof CellExpressionTokenType)) return false;
  89. return other.name === this.name;
  90. }
  91. }
  92. /**
  93. * Type of operation for a `CellExpression`. Named functions all fall under
  94. * `Function`.
  95. */
  96. class CellExpressionOperation {
  97. /** Arg is `number` */
  98. static Number = new this('Number');
  99. /** Arg is `string` without quotes */
  100. static String = new this('String');
  101. /** Arg is `boolean` */
  102. static Boolean = new this('Boolean');
  103. /** Arg is `CellAddress` */
  104. static Reference = new this('Reference');
  105. /** Args are start and end `CellAddress`es (e.g. "A5", "C7") */
  106. static Range = new this('Range');
  107. /** Args are two operand `CellExpression`s. */
  108. static Add = new this('Add');
  109. /** Args are two operand `CellExpression`s */
  110. static Subtract = new this('Subtract');
  111. /** Args are two operand `CellExpression`s */
  112. static Multiply = new this('Multiply');
  113. /** Args are two operand `CellExpression`s */
  114. static Divide = new this('Divide');
  115. /** Args are two operand `CellExpression`s. */
  116. static Concatenate = new this('Concatenate');
  117. /** Arg is operand `CellExpression` */
  118. static UnaryMinus = new this('UnaryMinus');
  119. /** Args are two operand `CellExpression`s. */
  120. static GreaterThan = new this('GreaterThan');
  121. /** Args are two operand `CellExpression`s. */
  122. static GreaterThanEqual = new this('GreaterThanEqual');
  123. /** Args are two operand `CellExpression`s. */
  124. static LessThan = new this('LessThan');
  125. /** Args are two operand `CellExpression`s. */
  126. static LessThanEqual = new this('LessThanEqual');
  127. /** Args are two operand `CellExpression`s. */
  128. static Equal = new this('Equal');
  129. /** Args are two operand `CellExpression`s. */
  130. static Unequal = new this('Unequal');
  131. /** Arg is operand `CellExpression`. */
  132. static UnaryNot = new this('UnaryNot');
  133. /** Args are 0+ `CellExpression`s */
  134. static Function = new this('Function');
  135. /** @type {string} */
  136. name;
  137. constructor(name) {
  138. this.name = name;
  139. }
  140. toString() {
  141. return `${this.constructor.name}.${this.name}`;
  142. }
  143. equals(other) {
  144. if (!(other instanceof CellExpressionOperation)) return false;
  145. return other.name == this.name;
  146. }
  147. }
  148. /**
  149. * Collection of all calculated cells in a table. Evaluates formulas.
  150. */
  151. class CellExpressionSet {
  152. /** @type {SpreadsheetGrid} */
  153. #grid;
  154. /**
  155. * @param {SpreadsheetGrid} grid
  156. */
  157. constructor(grid) {
  158. this.#grid = grid;
  159. }
  160. /**
  161. * Populates the `outputValue` fields of every cell in the table. Cells
  162. * with formulas will attempt to be calculated or populated with error
  163. * values.
  164. */
  165. calculateCells() {
  166. const rowCount = this.#grid.rowCount;
  167. const colCount = this.#grid.columnCount;
  168. // Make queue of cell addresses with expressions in them
  169. /** @type {CellAddress[]} */
  170. var expressionAddressQueue = [];
  171. var range = new CellAddressRange(new CellAddress(0, 0), new CellAddress(colCount - 1, rowCount - 1));
  172. for (const address of range.cellsIn(this.#grid)) {
  173. const cell = this.#grid.cellAt(address);
  174. const value = cell.originalValue;
  175. if (value.type != CellValue.TYPE_FORMULA) {
  176. cell.outputValue = value;
  177. cell.isCalculated = false;
  178. continue;
  179. }
  180. try {
  181. const expression = CellExpression.parse(value.formattedValue, address);
  182. if (!expression) {
  183. throw new CellSyntaxException("Invalid expression");
  184. }
  185. cell.parsedExpression = expression;
  186. cell.isCalculated = true;
  187. expressionAddressQueue.push(address);
  188. this.#enqueueFilledBlanks(expression, expressionAddressQueue);
  189. } catch (e) {
  190. if (e instanceof CellSyntaxException || e instanceof CellEvaluationException) {
  191. cell.outputValue = CellValue.fromValue(e);
  192. } else {
  193. throw e;
  194. }
  195. }
  196. }
  197. // Try to evaluate each cell. If one depends on cells not yet calculated,
  198. // move it to the back of the queue and try again later.
  199. this.#processExpressionQueue(expressionAddressQueue);
  200. // Anything left in the queue is a circular reference.
  201. this.#processCircularReferences(expressionAddressQueue);
  202. }
  203. /**
  204. * Attempts to evaluate expressions at the given `addresses`. If an
  205. * expression has unevaluated references, the expression is moved to the
  206. * end of the queue and tried again later. When this method returns, any
  207. * elements left in `addresses` can be considered circular references.
  208. *
  209. * @param {CellAddress[]} addresses - mutable queue of formula addresses
  210. */
  211. #processExpressionQueue(addresses) {
  212. var requeueCount = 0;
  213. while (addresses.length > 0 && requeueCount < addresses.length) {
  214. const address = addresses[0];
  215. addresses.splice(0, 1);
  216. const cell = this.#grid.cellAt(address);
  217. try {
  218. const result = this.#evaluate(cell.parsedExpression, address);
  219. cell.isCalculated = true;
  220. if (result instanceof CellValue) {
  221. cell.outputValue = result;
  222. requeueCount = 0;
  223. } else if (Array.isArray(result)) {
  224. if (result.length == 1) {
  225. cell.outputValue = result[0];
  226. requeueCount = 0;
  227. } else {
  228. throw new CellEvaluationException(`Expression resolved to ${result.length} values, single value expected`);
  229. }
  230. } else {
  231. throw new CellEvaluationException(`Expression resolved to ${result && result.constructor ? result.constructor.name : typeof result}, expected CellValue`);
  232. }
  233. } catch (e) {
  234. if (e instanceof CellDependencyException) {
  235. // Depends on a value that hasn't been calculated yet
  236. addresses.push(address);
  237. requeueCount++;
  238. } else if (e instanceof CellSyntaxException || e instanceof CellEvaluationException) {
  239. cell.outputValue = CellValue.fromValue(e);
  240. requeueCount = 0;
  241. } else {
  242. throw e;
  243. }
  244. }
  245. }
  246. }
  247. /**
  248. * Autofills a formula, transposing the formula to each affected cell and
  249. * stored in `parsedExpression`, and each address is queued in `addresses`
  250. * for evaluation.
  251. *
  252. * @param {CellExpression} expression - autofilled formula
  253. * @param {CellAddress[]} addresses - mutable address queue
  254. */
  255. #enqueueFilledBlanks(expression, addresses) {
  256. for (const range of expression.fillRanges ?? []) {
  257. for (const filledAddress of range.cellsIn(this.#grid)) {
  258. const filledCell = this.#grid.cellAt(filledAddress);
  259. if (filledCell.originalValue.type == CellValue.TYPE_BLANK &&
  260. (!filledCell.outputValue ||
  261. filledCell.outputValue.type == CellValue.TYPE_BLANK)) {
  262. filledCell.parsedExpression = expression.transpose(expression.location, filledAddress);
  263. filledCell.isCalculated = true;
  264. addresses.push(filledAddress);
  265. }
  266. }
  267. }
  268. }
  269. /**
  270. * Marks all cells at the given addresses as circular references.
  271. *
  272. * @param {CellAddress[]} addresses - mutable address queue
  273. */
  274. #processCircularReferences(addresses) {
  275. for (const address of addresses) {
  276. const cell = this.#grid.cellAt(address);
  277. cell.outputValue = CellValue.fromValue(new CellDependencyException(`Circular reference at ${address.name}`));
  278. }
  279. }
  280. /**
  281. * Evaluates an expression if possible.
  282. *
  283. * @param {CellExpression} expr - expression to evaluate
  284. * @param {CellAddress} address - location of expression
  285. * @returns {CellValue|CellValue[]} - results
  286. */
  287. #evaluate(expr, address) {
  288. const result = this.#preevaluate(expr, address);
  289. if (result instanceof CellValue) {
  290. // Expression included formatting override. Apply it to value.
  291. if (expr.outputType !== null) {
  292. return CellValue.fromValue(result.value, expr.outputType ?? result.type, expr.outputDecimals);
  293. }
  294. }
  295. return result;
  296. }
  297. /**
  298. * Evaluates an expression if possible. No custom formatting is applied to
  299. * result.
  300. *
  301. * @param {CellExpression} expr - expression to evaluate
  302. * @param {CellAddress} address - location of expression
  303. * @returns {CellValue|CellValue[]} - results
  304. * @throws {CellException} if evaluation fails for any reason
  305. */
  306. #preevaluate(expr, address) {
  307. switch (expr.op) {
  308. case CellExpressionOperation.Number:
  309. case CellExpressionOperation.String:
  310. case CellExpressionOperation.Boolean:
  311. return expr.arguments[0];
  312. case CellExpressionOperation.Reference: {
  313. const refAddress = expr.arguments[0];
  314. const cell = this.#grid.cellAt(refAddress);
  315. if (cell === null) {
  316. throw new CellEvaluationException(`No cell at ${refAddress.name}`, '#REF');
  317. }
  318. if (cell.outputValue === null) {
  319. throw new CellDependencyException(`Need calculated value for ${refAddress} to evaluate`);
  320. }
  321. return cell.outputValue;
  322. }
  323. case CellExpressionOperation.Range: {
  324. const range = expr.arguments[0];
  325. var values = [];
  326. for (const rAddress of range.cellsIn(this.#grid)) {
  327. const cell = this.#grid.cellAt(rAddress);
  328. if (rAddress.equals(address)) continue;
  329. const val = this.#grid.outputValueAt(rAddress);
  330. if (val === null) {
  331. throw new CellDependencyException(`Need calculated value for ${rAddress.name} to evaluate`);
  332. }
  333. values.push(val);
  334. }
  335. return values;
  336. }
  337. case CellExpressionOperation.Add: {
  338. const op1 = this.#evaluate(expr.arguments[0], address);
  339. const op2 = this.#evaluate(expr.arguments[1], address);
  340. return op1.add(op2);
  341. }
  342. case CellExpressionOperation.Subtract: {
  343. const op1 = this.#evaluate(expr.arguments[0], address);
  344. const op2 = this.#evaluate(expr.arguments[1], address);
  345. return op1.subtract(op2);
  346. }
  347. case CellExpressionOperation.Multiply: {
  348. const op1 = this.#evaluate(expr.arguments[0], address);
  349. const op2 = this.#evaluate(expr.arguments[1], address);
  350. return op1.multiply(op2);
  351. }
  352. case CellExpressionOperation.Divide: {
  353. const op1 = this.#evaluate(expr.arguments[0], address);
  354. const op2 = this.#evaluate(expr.arguments[1], address);
  355. return op1.divide(op2);
  356. }
  357. case CellExpressionOperation.UnaryMinus: {
  358. const op = this.#evaluate(expr.arguments[0], address);
  359. return CellValue.fromValue(0).subtract(op);
  360. }
  361. case CellExpressionOperation.GreaterThan: {
  362. const op1 = this.#evaluate(expr.arguments[0], address);
  363. const op2 = this.#evaluate(expr.arguments[1], address);
  364. return op1.gt(op2);
  365. }
  366. case CellExpressionOperation.GreaterThanEqual: {
  367. const op1 = this.#evaluate(expr.arguments[0], address);
  368. const op2 = this.#evaluate(expr.arguments[1], address);
  369. return op1.gte(op2);
  370. }
  371. case CellExpressionOperation.LessThan: {
  372. const op1 = this.#evaluate(expr.arguments[0], address);
  373. const op2 = this.#evaluate(expr.arguments[1], address);
  374. return op1.lt(op2);
  375. }
  376. case CellExpressionOperation.LessThanEqual: {
  377. const op1 = this.#evaluate(expr.arguments[0], address);
  378. const op2 = this.#evaluate(expr.arguments[1], address);
  379. return op1.lte(op2);
  380. }
  381. case CellExpressionOperation.Equal: {
  382. const op1 = this.#evaluate(expr.arguments[0], address);
  383. const op2 = this.#evaluate(expr.arguments[1], address);
  384. return op1.eq(op2);
  385. }
  386. case CellExpressionOperation.Unequal: {
  387. const op1 = this.#evaluate(expr.arguments[0], address);
  388. const op2 = this.#evaluate(expr.arguments[1], address);
  389. return op1.neq(op2);
  390. }
  391. case CellExpressionOperation.UnaryNot: {
  392. const op = this.#evaluate(expr.arguments[0], address);
  393. return op.not();
  394. }
  395. case CellExpressionOperation.Concatenate: {
  396. const op1 = this.#evaluate(expr.arguments[0], address);
  397. const op2 = this.#evaluate(expr.arguments[1], address);
  398. return op1.concatenate(op2);
  399. }
  400. case CellExpressionOperation.Function:
  401. return this.#callFunction(expr.qualifier, expr.arguments, address);
  402. }
  403. throw new CellSyntaxException(`Unhandled operation ${expr.op.name}`);
  404. }
  405. /**
  406. * Evaluates a named function, e.g. `ABS`, `SUM`, etc.
  407. *
  408. * @param {string} functionName - function name
  409. * @param {Array} args - raw arguments
  410. * @param {CellAddress} address - location of the expression
  411. * @returns {CellValue} - result
  412. * @throws {CellException} if evaluation fails for any reason
  413. */
  414. #callFunction(functionName, args, address) {
  415. switch (functionName.toUpperCase()) {
  416. case 'ABS': return this.#funcAbs(args, address);
  417. case 'AND': return this.#funcAnd(args, address);
  418. case 'AVERAGE': return this.#funcAverage(args, address);
  419. case 'CEILING': return this.#funcCeiling(args, address);
  420. case 'EXP': return this.#funcExp(args, address);
  421. case 'FLOOR': return this.#funcFloor(args, address);
  422. case 'IF': return this.#funcIf(args, address);
  423. case 'IFS': return this.#funcIfs(args, address);
  424. case 'LN': return this.#funcLn(args, address);
  425. case 'LOG': return this.#funcLog(args, address);
  426. case 'LOWER': return this.#funcLower(args, address);
  427. case 'MAX': return this.#funcMax(args, address);
  428. case 'MIN': return this.#funcMin(args, address);
  429. case 'MOD': return this.#funcMod(args, address);
  430. case 'NOT': return this.#funcNot(args, address);
  431. case 'OR': return this.#funcOr(args, address);
  432. case 'POWER': return this.#funcPower(args, address);
  433. case 'ROUND': return this.#funcRound(args, address);
  434. case 'SQRT': return this.#funcSqrt(args, address);
  435. case 'SUBSTITUTE': return this.#funcSubstitute(args, address);
  436. case 'SUM': return this.#funcSum(args, address);
  437. case 'UPPER': return this.#funcUpper(args, address);
  438. case 'XOR': return this.#funcXor(args, address);
  439. default:
  440. throw new CellSyntaxException(`Unknown function "${functionName}"`);
  441. }
  442. }
  443. /**
  444. * Checks and evaluates arguments for a numeric function. If successful,
  445. * an array of `CellValue`s with numeric values is returned.
  446. *
  447. * @param {string} functionName - name of the function (for debugging)
  448. * @param {number} minArgs - minimum required arguments
  449. * @param {number} maxArgs - maximum required arguments
  450. * @param {Array} args - raw arguments
  451. * @param {CellAddress} address - address of the formula
  452. * @returns {CellValue[]} numeric arguments
  453. * @throws {CellSyntaxException} if wrong number of arguments is passed
  454. * @throws {CellEvaluationException} if an argument does not resolve to a numeric value
  455. */
  456. #assertNumericArguments(functionName, minArgs, maxArgs, args, address) {
  457. const argCount = args.length;
  458. if (argCount < minArgs || argCount > maxArgs) {
  459. if (minArgs == maxArgs) {
  460. throw new CellSyntaxException(`${functionName}() expects ${minArgs} arguments, got ${argCount}`);
  461. }
  462. throw new CellSyntaxException(`${functionName}() expects between ${minArgs} and ${maxArgs} arguments, got ${argCount}`);
  463. }
  464. var out = [];
  465. for (const argument of args) {
  466. const evaled = this.#evaluate(argument, address);
  467. if (!(evaled instanceof CellValue) || !evaled.isNumeric()) {
  468. throw new CellEvaluationException(`${functionName}() expects numeric arguments`);
  469. }
  470. out.push(evaled);
  471. }
  472. return out;
  473. }
  474. /**
  475. * Evaluates and flattens numeric arguments. For functions that can take
  476. * arbitrary numbers of values including whole cell ranges.
  477. *
  478. * @param {string} functionName - function name (for debugging)
  479. * @param {Array} args - raw arguments
  480. * @param {CellAddress} address - location of expression
  481. * @param {boolean} errorOnNonnumeric - whether to throw an exception if
  482. * non-numeric arguments are encountered, otherwise they're skipped silently
  483. * @returns {CellValue[]} flattened array of numeric values
  484. */
  485. #flattenedNumericArguments(functionName, args, address, errorOnNonnumeric=true) {
  486. var flattened = [];
  487. for (const argument of args) {
  488. const evaled = this.#evaluate(argument, address);
  489. if (evaled instanceof CellValue) {
  490. if (!evaled.isNumeric()) {
  491. if (errorOnNonnumeric) {
  492. throw new CellEvaluationException(`${functionName} requires numeric arguments`);
  493. }
  494. continue;
  495. }
  496. flattened.push(evaled);
  497. } else if (Array.isArray(evaled)) {
  498. const arr = evaled;
  499. for (const arrayArgument of arr) {
  500. if (arrayArgument instanceof CellValue) {
  501. if (!arrayArgument.isNumeric()) {
  502. if (errorOnNonnumeric) {
  503. throw new CellEvaluationException(`${functionName} requires numeric arguments`);
  504. }
  505. continue;
  506. }
  507. flattened.push(arrayArgument);
  508. }
  509. }
  510. }
  511. }
  512. return flattened;
  513. }
  514. /**
  515. * `ABS(value)` - absolute value of a numeric argument
  516. *
  517. * @param {Array} args - raw arguments
  518. * @param {CellAddress} address - expression location
  519. * @returns {CellValue} - result
  520. */
  521. #funcAbs(args, address) {
  522. const arg = this.#assertNumericArguments('ABS', 1, 1, args, address)[0];
  523. if (arg.value < 0.0) {
  524. return CellValue.fromValue(0).subtract(arg);
  525. }
  526. return arg;
  527. }
  528. /**
  529. * `AND(arg, arg, ..., arg)` - Boolean AND of any number of Boolean arguments
  530. *
  531. * @param {Array} args - raw arguments
  532. * @param {CellAddress} address - expression location
  533. * @returns {CellValue} - result
  534. */
  535. #funcAnd(args, address) {
  536. if (args.length == 0) {
  537. throw new CellEvaluationException("AND requires one or more arguments");
  538. }
  539. const values = args.map((arg) => this.#evaluate(arg, address));
  540. for (const value of values) {
  541. const result = value.booleanValue();
  542. if (result === null) {
  543. throw new CellEvaluationException("AND requires boolean arguments");
  544. }
  545. if (!result) return CellValue.fromValue(false);
  546. }
  547. return CellValue.fromValue(true);
  548. }
  549. /**
  550. * `AVERAGE(arg, arg, ..., arg)` - Averages values. Non-numeric values are
  551. * omitted from the calculation.
  552. *
  553. * @param {Array} args - raw arguments
  554. * @param {CellAddress} address - expression location
  555. * @returns {CellValue} - result
  556. */
  557. #funcAverage(args, address) {
  558. var sum = CellValue.fromValue(0);
  559. var count = 0;
  560. for (const arg of args) {
  561. const val = this.#evaluate(arg, address);
  562. if (Array.isArray(val)) {
  563. for (const elem of val) {
  564. if (!elem.isNumeric()) continue;
  565. sum = sum.add(elem);
  566. count++;
  567. }
  568. } else if (val.isNumeric()) {
  569. sum = sum.add(val);
  570. count++;
  571. }
  572. }
  573. return (count > 0) ? sum.divide(CellValue.fromValue(count)) : CellValue.fromValue(0);
  574. }
  575. /**
  576. * `CEILING(value)` - Ceiling of a numeric value.
  577. *
  578. * @param {Array} args - raw arguments
  579. * @param {CellAddress} address - expression location
  580. * @returns {CellValue} - result
  581. */
  582. #funcCeiling(args, address) {
  583. const arg = this.#assertNumericArguments('CEILING', 1, 1, args, address)[0];
  584. const newValue = Math.ceil(arg.value);
  585. return CellValue.fromValue(newValue, arg.type);
  586. }
  587. /**
  588. * `EXP(value)` - Computes _e_ raised to the given exponent.
  589. *
  590. * @param {Array} args - raw arguments
  591. * @param {CellAddress} address - expression location
  592. * @returns {CellValue} - result
  593. */
  594. #funcExp(args, address) {
  595. const arg = this.#assertNumericArguments('EXP', 1, 1, args, address)[0];
  596. const newValue = Math.exp(arg.value);
  597. return CellValue.fromValue(newValue, arg.type);
  598. }
  599. /**
  600. * `FLOOR(value)` - Numeric value rounded down.
  601. *
  602. * @param {Array} args - raw arguments
  603. * @param {CellAddress} address - expression location
  604. * @returns {CellValue} - result
  605. */
  606. #funcFloor(args, address) {
  607. const arg = this.#assertNumericArguments('FLOOR', 1, 1, args, address)[0];
  608. const newValue = Math.floor(arg.value);
  609. return CellValue.fromValue(newValue, arg.type);
  610. }
  611. /**
  612. * `IF(test, trueVal, falseVal)` - Conditional test.
  613. *
  614. * @param {Array} args - raw arguments
  615. * @param {CellAddress} address - expression location
  616. * @returns {CellValue} - result
  617. */
  618. #funcIf(args, address) {
  619. if (args.length != 3) {
  620. throw new CellEvaluationException("IF expects three arguments");
  621. }
  622. const evaled = args.map((arg) => this.#evaluate(arg, address));
  623. const test = evaled[0].booleanValue();
  624. if (test === null) {
  625. throw new CellEvaluationException("IF expects a boolean for the first argument");
  626. }
  627. if (test) {
  628. return evaled[1];
  629. } else {
  630. return evaled[2];
  631. }
  632. }
  633. /**
  634. * `IFS(test1, result1, test2, result2, ..., fallbackResult)` - Multiple if
  635. * statement. Takes 3 or more arguments of an odd number consisting of pairs
  636. * of a Boolean test followed by the value to return if true. The very last
  637. * value is the fallback value to return if none of the Boolean tests are true.
  638. *
  639. * @param {Array} args - raw arguments
  640. * @param {CellAddress} address - expression location
  641. * @returns {CellValue} - result
  642. */
  643. #funcIfs(args, address) {
  644. if (args.length < 3) {
  645. throw new CellEvaluationException("IFS expects at least 3 arguments");
  646. }
  647. if ((args.length % 2) != 1) {
  648. throw new CellEvaluationException("IFS expects an odd number of arguments");
  649. }
  650. const evaled = args.map((arg) => this.#evaluate(arg, address));
  651. for (var i = 0; i < evaled.length - 1; i += 2) {
  652. const test = evaled[i].booleanValue();
  653. if (test === null) {
  654. throw new CellEvaluationException(`IFS expects a boolean for argument ${i + 1}`);
  655. }
  656. if (test) {
  657. return evaled[i + 1];
  658. }
  659. }
  660. return evaled[evaled.length - 1];
  661. }
  662. /**
  663. * `LN(value)` - Natural log.
  664. *
  665. * @param {Array} args - raw arguments
  666. * @param {CellAddress} address - expression location
  667. * @returns {CellValue} - result
  668. */
  669. #funcLn(args, address) {
  670. const arg = this.#assertNumericArguments('LN', 1, 1, args, address)[0];
  671. const newValue = Math.log(arg.value);
  672. return CellValue.fromValue(newValue, arg.type);
  673. }
  674. /**
  675. * `LOG(value, [base])` - Logarithm. Base is 10 if not provided.
  676. *
  677. * @param {Array} args - raw arguments
  678. * @param {CellAddress} address - expression location
  679. * @returns {CellValue} - result
  680. */
  681. #funcLog(args, address) {
  682. const evaled = this.#assertNumericArguments('LOG', 1, 2, args, address);
  683. const exponent = evaled[0];
  684. const base = (evaled.length > 1) ? evaled[1].value : 10.0;
  685. const newValue = Math.log(exponent.value) / Math.log(base);
  686. return CellValue.fromValue(newValue, exponent.type);
  687. }
  688. /**
  689. * `LOWER(text)` - Lowercase version of a string.
  690. *
  691. * @param {Array} args - raw arguments
  692. * @param {CellAddress} address - expression location
  693. * @returns {CellValue} - result
  694. */
  695. #funcLower(args, address) {
  696. if (args.length != 1) {
  697. throw new CellEvaluationException("LOWER requires one argument");
  698. }
  699. const evaled = args.map((arg) => this.#evaluate(arg, address));
  700. const s = evaled[0].stringValue(true);
  701. if (s === null) {
  702. throw new CellEvaluationException("LOWER requires one string argument");
  703. }
  704. return CellValue.fromValue(s.toLowerCase());
  705. }
  706. /**
  707. * `MAX(arg, arg, ... arg)` - Returns the maximum numeric value.
  708. *
  709. * @param {Array} args - raw arguments
  710. * @param {CellAddress} address - expression location
  711. * @returns {CellValue} - result
  712. */
  713. #funcMax(args, address) {
  714. var maxValue = null;
  715. const flattened = this.#flattenedNumericArguments('MAX', args, address);
  716. if (flattened.length == 0) {
  717. throw new CellEvaluationException("MAX requires at least one numeric argument");
  718. }
  719. for (const argument of flattened) {
  720. if (maxValue === null || argument.value > maxValue.value) {
  721. maxValue = argument;
  722. }
  723. }
  724. return maxValue ?? CellValue.fromValue(0);
  725. }
  726. /**
  727. * `MIN(arg, arg, ... arg)` - Returns the minimum numeric value.
  728. *
  729. * @param {Array} args - raw arguments
  730. * @param {CellAddress} address - expression location
  731. * @returns {CellValue} - result
  732. */
  733. #funcMin(args, address) {
  734. var minValue = null;
  735. const flattened = this.#flattenedNumericArguments('MIN', args, address);
  736. if (flattened.length == 0) {
  737. throw new CellEvaluationException("MIN requires at least one numeric argument");
  738. }
  739. for (const argument of flattened) {
  740. if (minValue === null || argument.value < minValue.value) {
  741. minValue = argument;
  742. }
  743. }
  744. return minValue ?? CellValue.fromValue(0);
  745. }
  746. /**
  747. * `MOD(value, divisor)` - Returns the remainder after a division.
  748. *
  749. * @param {Array} args - raw arguments
  750. * @param {CellAddress} address - expression location
  751. * @returns {CellValue} - result
  752. */
  753. #funcMod(args, address) {
  754. if (args.length != 2) {
  755. throw new CellEvaluationException("MOD requires two numeric arguments");
  756. }
  757. const values = args.map((arg) => this.#evaluate(arg, address));
  758. return values[0].modulo(values[1]);
  759. }
  760. /**
  761. * `NOT(value)` - Boolean NOT of a Boolean value.
  762. *
  763. * @param {Array} args - raw arguments
  764. * @param {CellAddress} address - expression location
  765. * @returns {CellValue} - result
  766. */
  767. #funcNot(args, address) {
  768. if (args.length != 1) {
  769. throw new CellEvaluationException("NOT expects one argument");
  770. }
  771. const evaled = args.map((arg) => this.#evaluate(arg, address));
  772. const b = evaled[0].booleanValue();
  773. if (b === null) {
  774. throw new CellEvaluationException("NOT expects boolean argument");
  775. }
  776. return CellValue.fromValue(!b);
  777. }
  778. /**
  779. * `OR(arg, arg, ... arg)` - Boolean OR of one or more Boolean arguments.
  780. *
  781. * @param {Array} args - raw arguments
  782. * @param {CellAddress} address - expression location
  783. * @returns {CellValue} - result
  784. */
  785. #funcOr(args, address) {
  786. if (args.length == 0) {
  787. throw new CellEvaluationException("OR requires one or more arguments");
  788. }
  789. const values = args.map((arg) => this.#evaluate(arg, address));
  790. for (const value of values) {
  791. const result = value.booleanValue();
  792. if (result === null) {
  793. throw new CellEvaluationException("OR requires boolean arguments");
  794. }
  795. if (result) return CellValue.fromValue(true);
  796. }
  797. return CellValue.fromValue(false);
  798. }
  799. /**
  800. * `POWER(base, exponent)` - Raises a base to an exponent.
  801. *
  802. * @param {Array} args - raw arguments
  803. * @param {CellAddress} address - expression location
  804. * @returns {CellValue} - result
  805. */
  806. #funcPower(args, address) {
  807. const evaled = this.#assertNumericArguments('POWER', 2, 2, args, address);
  808. const base = evaled[0];
  809. const exp = evaled[1];
  810. const val = Math.pow(base.value, exp.value);
  811. return CellValue.fromValue(val, base.type);
  812. }
  813. /**
  814. * `ROUND(value, [places])` - Rounds a number, optionally to the given number
  815. * of digits after the decimal place. Negative places round to the nearest
  816. * 10, 100, 1000, etc.
  817. *
  818. * @param {Array} args - raw arguments
  819. * @param {CellAddress} address - expression location
  820. * @returns {CellValue} - result
  821. */
  822. #funcRound(args, address) {
  823. const evaled = this.#assertNumericArguments('ROUND', 1, 2, args, address);
  824. const val = evaled[0];
  825. const places = evaled.length > 1 ? evaled[1].value : 0;
  826. const divider = Math.pow(10.0, places);
  827. const newValue = Math.round(val.value * divider) / divider;
  828. return CellValue.fromValue(newValue, val.type);
  829. }
  830. /**
  831. * `SQRT(value)` - Square root.
  832. *
  833. * @param {Array} args - raw arguments
  834. * @param {CellAddress} address - expression location
  835. * @returns {CellValue} - result
  836. */
  837. #funcSqrt(args, address) {
  838. const arg = this.#assertNumericArguments('SQRT', 1, 1, args, address)[0];
  839. const val = arg.numericValue();
  840. return CellValue.fromValue(Math.sqrt(val));
  841. }
  842. /**
  843. * `SUBSTITUTE(text, pattern, replacement)` - Substitutes all occurrences of
  844. * `pattern` within `text` with `replacement`.
  845. *
  846. * @param {Array} args - raw arguments
  847. * @param {CellAddress} address - expression location
  848. * @returns {CellValue} - result
  849. */
  850. #funcSubstitute(args, address) {
  851. if (args.length != 3) {
  852. throw new CellEvaluationException("SUBSTITUTE expects 3 string arguments");
  853. }
  854. const values = args.map((arg) => this.#evaluate(arg, address));
  855. const text = values[0].stringValue();
  856. const search = values[1].stringValue();
  857. const replace = values[2].stringValue();
  858. if (text === null || search === null || replace === null) {
  859. throw new CellEvaluationException("SUBSTITUTE expects 3 string arguments");
  860. }
  861. const result = text.replace(new RegExp(MDUtils.escapeRegex(search), 'gi'), replace);
  862. return CellValue.fromValue(result);
  863. }
  864. /**
  865. * `SUM(arg, arg, ... arg)` - Calculates the sum of numeric arguments.
  866. *
  867. * @param {Array} args - raw arguments
  868. * @param {CellAddress} address - expression location
  869. * @returns {CellValue} - result
  870. */
  871. #funcSum(args, address) {
  872. var sum = CellValue.fromValue(0);
  873. for (const arg of args) {
  874. const val = this.#evaluate(arg, address);
  875. if (Array.isArray(val)) {
  876. for (const elem of val) {
  877. if (elem.isNumeric()) sum = sum.add(elem);
  878. }
  879. } else if (val.isNumeric()) {
  880. sum = sum.add(val);
  881. }
  882. }
  883. return sum;
  884. }
  885. /**
  886. * `UPPER(text)` - Uppercase of a text argument.
  887. *
  888. * @param {Array} args - raw arguments
  889. * @param {CellAddress} address - expression location
  890. * @returns {CellValue} - result
  891. */
  892. #funcUpper(args, address) {
  893. if (args.length != 1) {
  894. throw new CellEvaluationException("UPPER requires one argument");
  895. }
  896. const evaled = args.map((arg) => this.#evaluate(arg, address));
  897. const s = evaled[0].stringValue(true);
  898. if (s === null) {
  899. throw new CellEvaluationException("UPPER requires one string argument");
  900. }
  901. return CellValue.fromValue(s.toUpperCase());
  902. }
  903. /**
  904. * `XOR(arg, arg, ... arg)` - Boolean XOR of one or more Boolean arguments.
  905. *
  906. * @param {Array} args - raw arguments
  907. * @param {CellAddress} address - expression location
  908. * @returns {CellValue} - result
  909. */
  910. #funcXor(args, address) {
  911. if (args.length == 0) {
  912. throw new CellEvaluationException("XOR requires one or more arguments");
  913. }
  914. const values = args.map((arg) => this.#evaluate(arg, address));
  915. var result = null;
  916. for (const value of values) {
  917. const b = value.booleanValue();
  918. if (b === null) {
  919. throw new CellEvaluationException("XOR requires boolean arguments");
  920. }
  921. result = (result === null) ? b : (result ^ b);
  922. }
  923. return CellValue.fromValue(result != 0);
  924. }
  925. }
  926. /**
  927. * A spreadsheet formula expression. Evaluation is done by `CellExpressionSet`.
  928. */
  929. class CellExpression {
  930. /**
  931. * Operation.
  932. * @type {CellExpressionOperation}
  933. */
  934. op;
  935. /**
  936. * Mixed array of `CellValue`, `CellAddress`, `CellAddressRange`,
  937. * `CellExpression`, perhaps more.
  938. * @type {Array}
  939. */
  940. arguments;
  941. /**
  942. * For `Function`, the function name.
  943. * @type {string|null}
  944. */
  945. qualifier;
  946. /**
  947. * Optional format override. One of `number`, `currency`, `percent`.
  948. * @type {string|null}
  949. */
  950. outputType = null;
  951. /**
  952. * Optional decimal place formatting override.
  953. * @type {number|null}
  954. */
  955. outputDecimals = null;
  956. /**
  957. * Address ranges to copy this expression into for any blank cells. Used
  958. * by formulas with the `FILL` modifier.
  959. * @type {CellAddressRange[]|null} fillRanges
  960. */
  961. fillRanges = null;
  962. /**
  963. * Source address of the formula.
  964. * @type {CellAddress|null}
  965. */
  966. location = null;
  967. /**
  968. * @param {CellExpressionOperation} op
  969. * @param {Array} args
  970. * @param {string|null} qualifier
  971. */
  972. constructor(op, args, qualifier = null) {
  973. this.op = op;
  974. this.arguments = args;
  975. this.qualifier = qualifier;
  976. }
  977. /**
  978. * Attempts to parse a formula expression.
  979. *
  980. * @param {string} expression - formula string, including leading `=`
  981. * @param {CellAddress} address - location of the formula
  982. * @returns {CellExpression|null} - parsed expression, or `null` if it failed
  983. */
  984. static parse(expression, address) {
  985. const tokens = this.expressionToTokens(expression);
  986. if (tokens.length == 0) return null;
  987. const expr = this.expressionFromTokens(tokens, address);
  988. expr.location = address;
  989. return expr;
  990. }
  991. /**
  992. * Writes an expression tree to console.error for debugging purposes.
  993. *
  994. * @param {CellExpression} expression
  995. * @param {string} indent
  996. */
  997. static dumpExpression(expression, indent = '') {
  998. if (expression.arguments.length == 0) {
  999. console.error(indent + "expr " + expression.op.name + '()');
  1000. } else {
  1001. console.error(indent + expression.op.name + '(');
  1002. for (const argument of expression.arguments) {
  1003. if (typeof argument == 'number') {
  1004. console.error(indent + `\t${argument}`);
  1005. } else if (typeof argument == 'string') {
  1006. console.error(indent + `\t"${argument}"`);
  1007. } else if (typeof argument == 'boolean') {
  1008. console.error(indent + "\t" + (argument ? "true" : "false"));
  1009. } else if (argument instanceof CellAddress) {
  1010. console.error(indent + "\t" + argument.name);
  1011. } else if (argument instanceof CellAddressRange) {
  1012. console.error(indent + "\t" + argument.name);
  1013. } else if (argument instanceof CellValue) {
  1014. console.error(indent + "\t" + argument.type + " " + argument.formattedValue);
  1015. } else if (argument instanceof CellExpression) {
  1016. this.dumpExpression(argument, indent + "\t");
  1017. } else {
  1018. console.error(indent + "\t" + typeof argument);
  1019. }
  1020. }
  1021. console.error(indent + ')');
  1022. }
  1023. }
  1024. #clone() {
  1025. const cp = new CellExpression();
  1026. cp.op = this.op;
  1027. cp.arguments = this.arguments.slice();
  1028. cp.qualifier = this.qualifier;
  1029. cp.outputType = this.outputType;
  1030. cp.outputDecimals = this.outputDecimals;
  1031. cp.fillRanges = this.fillRanges !== null ? this.fillRanges.slice() : null;
  1032. cp.location = this.location;
  1033. return cp;
  1034. }
  1035. /**
  1036. * Returns a copy of this expression with cell references transposed by
  1037. * the delta between `start` and `end` addresses. Used for repeating an
  1038. * autofilled formula into blank cells.
  1039. *
  1040. * @param {CellAddress} start
  1041. * @param {CellAddress} end
  1042. * @returns {CellExpression|null}
  1043. */
  1044. transpose(start, end) {
  1045. var transposed = this.#clone(); // structuredClone makes a mess of typing
  1046. transposed.arguments = [];
  1047. for (const argument of this.arguments) {
  1048. if (argument instanceof CellExpression) {
  1049. transposed.arguments.push(argument.transpose(start, end));
  1050. } else if (argument instanceof CellAddress) {
  1051. transposed.arguments.push(argument.transpose(start, end));
  1052. } else if (argument instanceof CellAddressRange) {
  1053. transposed.arguments.push(argument.transpose(start, end));
  1054. } else {
  1055. transposed.arguments.push(argument);
  1056. }
  1057. }
  1058. return transposed;
  1059. }
  1060. // -- Tokenizing --------------------------------------------------------
  1061. /**
  1062. * Converts an expression into an array of tokens.
  1063. * @param {string} text - expression
  1064. * @returns {CellExpressionToken[]} tokens
  1065. */
  1066. static expressionToTokens(text) {
  1067. var tokens = [];
  1068. var pos = [0];
  1069. this.#skipWhitespace(text, pos);
  1070. if (text.substring(pos[0], pos[0] + 1) == '=') {
  1071. // Ignore equals
  1072. pos[0]++;
  1073. }
  1074. this.#skipWhitespace(text, pos);
  1075. var l = text.length;
  1076. while (pos[0] < l) {
  1077. tokens.push(this.#readNextToken(text, pos));
  1078. this.#skipWhitespace(text, pos);
  1079. }
  1080. return tokens;
  1081. }
  1082. /**
  1083. * @param {string} text
  1084. * @param {number[]} pos
  1085. * @returns {CellExpressionToken}
  1086. */
  1087. static #readNextToken(text, pos) {
  1088. // Single char tokens
  1089. var token;
  1090. if (token = this.#readNextSimpleToken(text, pos, '==', CellExpressionTokenType.Equal)) return token;
  1091. if (token = this.#readNextSimpleToken(text, pos, '!=', CellExpressionTokenType.Unequal)) return token;
  1092. if (token = this.#readNextSimpleToken(text, pos, '<=', CellExpressionTokenType.LessThanEqual)) return token;
  1093. if (token = this.#readNextSimpleToken(text, pos, '>=', CellExpressionTokenType.GreaterThanEqual)) return token;
  1094. if (token = this.#readNextSimpleToken(text, pos, '<', CellExpressionTokenType.LessThan)) return token;
  1095. if (token = this.#readNextSimpleToken(text, pos, '>', CellExpressionTokenType.GreaterThan)) return token;
  1096. if (token = this.#readNextSimpleToken(text, pos, '!', CellExpressionTokenType.Not)) return token;
  1097. if (token = this.#readNextSimpleToken(text, pos, '+', CellExpressionTokenType.Plus)) return token;
  1098. if (token = this.#readNextSimpleToken(text, pos, '-', CellExpressionTokenType.Minus)) return token;
  1099. if (token = this.#readNextSimpleToken(text, pos, '*', CellExpressionTokenType.Multiply)) return token;
  1100. if (token = this.#readNextSimpleToken(text, pos, '/', CellExpressionTokenType.Divide)) return token;
  1101. if (token = this.#readNextSimpleToken(text, pos, ',', CellExpressionTokenType.Comma)) return token;
  1102. if (token = this.#readNextSimpleToken(text, pos, '(', CellExpressionTokenType.OpenParen)) return token;
  1103. if (token = this.#readNextSimpleToken(text, pos, ')', CellExpressionTokenType.CloseParen)) return token;
  1104. if (token = this.#readNextSimpleToken(text, pos, ':', CellExpressionTokenType.Colon)) return token;
  1105. if (token = this.#readNextSimpleToken(text, pos, ';', CellExpressionTokenType.Semicolon)) return token;
  1106. if (token = this.#readNextSimpleToken(text, pos, '&', CellExpressionTokenType.Ampersand)) return token;
  1107. // Other tokens
  1108. if (token = this.#readNextAddressToken(text, pos)) return token;
  1109. if (token = this.#readNextNameToken(text, pos)) return token;
  1110. if (token = this.#readNextNumberToken(text, pos)) return token;
  1111. if (token = this.#readNextStringToken(text, pos)) return token;
  1112. throw new CellSyntaxException(`Unexpected character "${text.substring(pos[0], pos[0] + 1)}" at ${pos[0]}`);
  1113. }
  1114. /**
  1115. * @param {string} text
  1116. * @param {number[]} pos
  1117. */
  1118. static #skipWhitespace(text, pos) {
  1119. const l = text.length;
  1120. while (pos[0] < l) {
  1121. const ch = text.substring(pos[0], pos[0] + 1);
  1122. if (ch == ' ' || ch == "\t" || ch == "\n" || ch == "\r") {
  1123. pos[0]++;
  1124. } else {
  1125. return;
  1126. }
  1127. }
  1128. }
  1129. /**
  1130. * @param {string} text
  1131. * @param {number[]} pos
  1132. * @param {string} target
  1133. * @param {CellExpressionTokenType} type
  1134. * @returns {CellExpressionToken|null}
  1135. */
  1136. static #readNextSimpleToken(text, pos, target, type) {
  1137. const remaining = text.length - pos[0];
  1138. const l = target.length;
  1139. if (l > remaining) return null;
  1140. const test = text.substring(pos[0], pos[0] + l);
  1141. if (test.toUpperCase() != target.toUpperCase()) return null;
  1142. pos[0] += l;
  1143. return new CellExpressionToken(type, test);
  1144. }
  1145. /**
  1146. * @param {string} text
  1147. * @param {number[]} pos
  1148. * @returns {CellExpressionToken|null}
  1149. */
  1150. static #readNextAddressToken(text, pos) {
  1151. var p = [ pos[0] ];
  1152. var ch = text.substring(p[0], p[0] + 1);
  1153. var address = '';
  1154. var isName = true;
  1155. if (ch == '$') {
  1156. address += ch;
  1157. isName = false;
  1158. p[0]++;
  1159. }
  1160. var col = this.#readChars(text, p, (s) => this.#isLetter(s), 1, 2);
  1161. if (col === null) return null;
  1162. address += col;
  1163. ch = text.substring(p[0], p[0] + 1);
  1164. if (ch == '$') {
  1165. address += ch;
  1166. isName = false;
  1167. p[0]++;
  1168. const row = this.#readChars(text, p, this.#isDigit, 1);
  1169. if (row === null) return null;
  1170. address += row;
  1171. } else {
  1172. const row = this.#readChars(text, p, this.#isDigit, 0);
  1173. if (row === null) return null;
  1174. address += row;
  1175. }
  1176. pos[0] = p[0];
  1177. return new CellExpressionToken(
  1178. isName ? CellExpressionTokenType.NameOrAddress : CellExpressionTokenType.Address,
  1179. address);
  1180. }
  1181. /**
  1182. * @param {string} text
  1183. * @param {number[]} pos
  1184. * @returns {CellExpressionToken|null}
  1185. */
  1186. static #readNextNameToken(text, pos) {
  1187. var p = [ pos[0] ];
  1188. const name = this.#readChars(text, p, (s) => this.#isLetter(s), 1);
  1189. if (name === null) return null;
  1190. pos[0] = p[0];
  1191. if (CellAddress.isAddress(name)) {
  1192. return new CellExpressionToken(CellExpressionTokenType.NameOrAddress, name);
  1193. }
  1194. return new CellExpressionToken(CellExpressionTokenType.Name, name);
  1195. }
  1196. /**
  1197. * @param {string} text
  1198. * @param {number[]} pos
  1199. * @returns {CellExpressionToken|null}
  1200. */
  1201. static #readNextNumberToken(text, pos) {
  1202. var ch = text.substring(pos[0], pos[0] + 1);
  1203. if (!this.#isDigit(ch)) return null;
  1204. const l = text.length;
  1205. var numStr = ch;
  1206. pos[0]++;
  1207. while (pos[0] < l) {
  1208. ch = text.substring(pos[0], pos[0] + 1);
  1209. if (this.#isDigit(ch)) {
  1210. pos[0]++;
  1211. numStr += ch;
  1212. } else {
  1213. break;
  1214. }
  1215. }
  1216. if (pos[0] < l) {
  1217. ch = text.substring(pos[0], pos[0] + 1);
  1218. if (ch == '.') {
  1219. numStr += ch;
  1220. pos[0]++;
  1221. while (pos[0] < l) {
  1222. ch = text.substring(pos[0], pos[0] + 1);
  1223. if (this.#isDigit(ch)) {
  1224. pos[0]++;
  1225. numStr += ch;
  1226. } else {
  1227. break;
  1228. }
  1229. }
  1230. }
  1231. }
  1232. return new CellExpressionToken(CellExpressionTokenType.Number, numStr);
  1233. }
  1234. /**
  1235. * @param {string} text
  1236. * @param {number[]} pos
  1237. * @returns {CellExpressionToken|null}
  1238. */
  1239. static #readNextStringToken(text, pos) {
  1240. var ch = text.substring(pos[0], pos[0] + 1);
  1241. if (ch !== '"') return null;
  1242. var str = '';
  1243. pos[0]++;
  1244. const l = text.length;
  1245. var inEscape = false;
  1246. while (pos[0] < l) {
  1247. ch = text.substring(pos[0], pos[0] + 1);
  1248. pos[0]++;
  1249. if (inEscape) {
  1250. inEscape = false;
  1251. if (ch == '\\' || ch == '"') {
  1252. str += ch;
  1253. } else {
  1254. throw new CellSyntaxException(`Bad string escape sequence "\\${ch}"`);
  1255. }
  1256. } else if (ch == '\\') {
  1257. inEscape = true;
  1258. } else if (ch == '"') {
  1259. return new CellExpressionToken(CellExpressionTokenType.String, str);
  1260. } else {
  1261. str += ch;
  1262. }
  1263. }
  1264. throw new CellSyntaxException('Unterminated string');
  1265. }
  1266. /**
  1267. * Reads the next chars that pass a test function and returns the result.
  1268. * @param {string} text
  1269. * @param {number[]} pos
  1270. * @param {function} charTest
  1271. * @param {number|null} minimumLength
  1272. * @param {number|null} maximumLength
  1273. * @returns {string|null}
  1274. */
  1275. static #readChars(text, pos, charTest, minimumLength = null, maximumLength = null) {
  1276. var p = pos[0];
  1277. const l = text.length;
  1278. var s = '';
  1279. var sl = 0;
  1280. while (p < l && (maximumLength === null || sl < maximumLength)) {
  1281. const ch = text.substring(p, p + 1);
  1282. if (!charTest(ch)) break;
  1283. s += ch;
  1284. sl++;
  1285. p++;
  1286. }
  1287. if (p < l && charTest(text.substring(p, p + 1))) {
  1288. return null;
  1289. }
  1290. if (minimumLength !== null && sl < minimumLength) {
  1291. return null;
  1292. }
  1293. pos[0] = p;
  1294. return s;
  1295. }
  1296. /**
  1297. * @param {string} ch
  1298. * @returns {boolean}
  1299. */
  1300. static #isLetter(ch) {
  1301. const ord = ch.codePointAt(0);
  1302. return (ord >= 65 && ord <= 90) || (ord >= 97 && ord <= 122);
  1303. }
  1304. /**
  1305. * @param {string} ch
  1306. * @returns {boolean}
  1307. */
  1308. static #isDigit(ch) {
  1309. const ord = ch.codePointAt(0);
  1310. return (ord >= 48 && ord <= 57);
  1311. }
  1312. // -- Parsing -----------------------------------------------------------
  1313. /**
  1314. * @param {Array} tokens
  1315. * @param {CellAddress} address
  1316. * @returns {CellExpression|null}
  1317. */
  1318. static expressionFromTokens(tokens, address) {
  1319. var expr;
  1320. if (expr = this.#tryExpressionAndFormat(tokens, 0, tokens.length - 1, address)) return expr;
  1321. if (expr = this.#tryExpressionAndFill(tokens, 0, tokens.length - 1, address)) return expr;
  1322. if (expr = this.#tryExpression(tokens, 0, tokens.length - 1, address)) return expr;
  1323. return null;
  1324. }
  1325. /**
  1326. * @param {Array} tokens
  1327. * @param {number} start
  1328. * @param {number} end
  1329. * @param {CellAddress} address
  1330. * @returns {CellExpression|null}
  1331. */
  1332. static #tryExpressionAndFormat(tokens, start, end, address) {
  1333. for (var t = start + 1; t < end; t++) {
  1334. if (tokens[t].type == CellExpressionTokenType.Semicolon) {
  1335. const expr = this.#tryExpressionAndFill(tokens, start, t - 1, address) ??
  1336. this.#tryExpression(tokens, start, t - 1, address);
  1337. if (expr === null) return null;
  1338. const format = this.#tryFormat(tokens, t + 1, end, address);
  1339. if (format === null) return null;
  1340. [ expr.outputType, expr.outputDecimals ] = format;
  1341. return expr;
  1342. }
  1343. }
  1344. return null;
  1345. }
  1346. /**
  1347. * @param {CellExpressionToken[]} tokens
  1348. * @param {number} start
  1349. * @param {number} end
  1350. * @param {CellAddress} address
  1351. * @returns {CellExpression|null}
  1352. */
  1353. static #tryExpressionAndFill(tokens, start, end, address) {
  1354. var count = end - start + 1;
  1355. if (count < 2) return null;
  1356. if (!tokens[end].type.isPotentialName()) return null;
  1357. var name = tokens[end].content.toUpperCase();
  1358. if (name != 'FILL') return null;
  1359. const exp = this.#tryExpression(tokens, start, end - 1, address);
  1360. const columnIndex = address.columnIndex;
  1361. exp.fillRanges = [
  1362. new CellAddressRange(new CellAddress(columnIndex, -1), new CellAddress(columnIndex, -1)),
  1363. ];
  1364. return exp;
  1365. }
  1366. /**
  1367. * Tries to parse a format suffix after a semicolon. Examples:
  1368. *
  1369. * ; number
  1370. * ; number 3
  1371. * ; currency 2
  1372. * ; percent 0
  1373. * @param {CellExpressionToken[]} tokens
  1374. * @param {number} start
  1375. * @param {number} end
  1376. * @param {CellAddress} address
  1377. * @return {any[]} CellValue type and decimal places
  1378. */
  1379. static #tryFormat(tokens, start, end, address) {
  1380. const count = end - start + 1;
  1381. if (count < 0 || count > 2) return null;
  1382. if (!tokens[start].type.isPotentialName()) return null;
  1383. const type = tokens[start].content.toLowerCase();
  1384. if (!CellValue.isTypeNumeric(type)) return null;
  1385. var decimals;
  1386. if (count > 1) {
  1387. if (tokens[start + 1].type != CellExpressionTokenType.Number) return null;
  1388. decimals = parseInt(tokens[start + 1].content);
  1389. } else {
  1390. decimals = null;
  1391. }
  1392. return [ type, decimals ];
  1393. }
  1394. /**
  1395. * @param {CellExpressionToken[]} tokens
  1396. * @param {number} start
  1397. * @param {number} end
  1398. * @param {CellAddress} address
  1399. * @returns {CellExpression}
  1400. */
  1401. static #tryExpression(tokens, start, end, address) {
  1402. var expr;
  1403. if (expr = this.#tryParenExpression(tokens, start, end, address)) return expr;
  1404. if (expr = this.#tryNumber(tokens, start, end, address)) return expr;
  1405. if (expr = this.#tryString(tokens, start, end, address)) return expr;
  1406. if (expr = this.#tryBoolean(tokens, start, end, address)) return expr;
  1407. if (expr = this.#tryFunction(tokens, start, end, address)) return expr;
  1408. if (expr = this.#tryRange(tokens, start, end, address)) return expr;
  1409. if (expr = this.#tryReference(tokens, start, end, address)) return expr;
  1410. if (expr = this.#tryInfix(tokens, start, end, address)) return expr;
  1411. if (expr = this.#tryUnary(tokens, start, end, address)) return expr;
  1412. throw new CellSyntaxException("Invalid expression");
  1413. }
  1414. /**
  1415. * @param {CellExpressionToken[]} tokens
  1416. * @param {number} start
  1417. * @param {number} end
  1418. * @param {CellAddress} address
  1419. * @returns {CellExpression|null}
  1420. */
  1421. static #tryParenExpression(tokens, start, end, address) {
  1422. if (tokens[start].type != CellExpressionTokenType.OpenParen) return null;
  1423. if (tokens[end].type != CellExpressionTokenType.CloseParen) return null;
  1424. var parenLevel = 0;
  1425. for (var t = start + 1; t < end; t++) {
  1426. if (tokens[t].type == CellExpressionTokenType.OpenParen) {
  1427. parenLevel++;
  1428. } else if (tokens[t].type == CellExpressionTokenType.CloseParen) {
  1429. parenLevel--;
  1430. }
  1431. if (parenLevel < 0) return null;
  1432. }
  1433. if (parenLevel != 0) return null;
  1434. return this.#tryExpression(tokens, start + 1, end - 1, address);
  1435. }
  1436. /**
  1437. * @param {CellExpressionToken[]} tokens
  1438. * @param {number} start
  1439. * @param {number} end
  1440. * @param {CellAddress} address
  1441. * @returns {CellExpression|null}
  1442. */
  1443. static #tryNumber(tokens, start, end, address) {
  1444. if (tokens[end].type != CellExpressionTokenType.Number) return null;
  1445. if (end > start + 1) return null;
  1446. const val = CellValue.fromCellString(tokens[end].content);
  1447. if (end > start) {
  1448. if (tokens[start].type != CellExpressionTokenType.Minus) return null;
  1449. val.value = -val.value;
  1450. }
  1451. return new CellExpression(CellExpressionOperation.Number, [ val ]);
  1452. }
  1453. /**
  1454. * @param {CellExpressionToken[]} tokens
  1455. * @param {number} start
  1456. * @param {number} end
  1457. * @param {CellAddress} address
  1458. * @returns {CellExpression|null}
  1459. */
  1460. static #tryString(tokens, start, end, address) {
  1461. if (start != end) return null;
  1462. if (tokens[start].type != CellExpressionTokenType.String) return null;
  1463. const str = tokens[start].content;
  1464. return new CellExpression(CellExpressionOperation.String, [ new CellValue(str, str, CellValue.TYPE_STRING, 0) ]);
  1465. }
  1466. /**
  1467. * @param {CellExpressionToken[]} tokens
  1468. * @param {number} start
  1469. * @param {number} end
  1470. * @param {CellAddress} address
  1471. * @returns {CellExpression|null}
  1472. */
  1473. static #tryBoolean(tokens, start, end, address) {
  1474. if (start != end) return null;
  1475. if (!tokens[start].type.isPotentialName()) return null;
  1476. const str = tokens[start].content.toUpperCase();
  1477. if (str != 'TRUE' && str != 'FALSE') return null;
  1478. return new CellExpression(CellExpressionOperation.Boolean, [ new CellValue(str, str == 'TRUE', CellValue.TYPE_BOOLEAN) ]);
  1479. }
  1480. /**
  1481. * @param {CellExpressionToken[]} tokens
  1482. * @param {number} start
  1483. * @param {number} end
  1484. * @param {CellAddress} address
  1485. * @returns {CellExpression|null}
  1486. */
  1487. static #tryFunction(tokens, start, end, address) {
  1488. const count = end - start + 1;
  1489. if (count < 3) return null;
  1490. if (!tokens[start].type.isPotentialName()) return null;
  1491. const qualifier = tokens[start].content;
  1492. if (tokens[start + 1].type != CellExpressionTokenType.OpenParen) return null;
  1493. if (tokens[end].type != CellExpressionTokenType.CloseParen) return null;
  1494. const argList = this.#tryArgumentList(tokens, start + 2, end - 1, address);
  1495. if (argList === null) return null;
  1496. return new CellExpression(CellExpressionOperation.Function, argList, qualifier);
  1497. }
  1498. /**
  1499. * @param {CellExpressionToken[]} tokens
  1500. * @param {number} start
  1501. * @param {number} end
  1502. * @param {CellAddress} address
  1503. * @returns {CellExpression[]|null}
  1504. */
  1505. static #tryArgumentList(tokens, start, end, address) {
  1506. const count = end - start + 1;
  1507. if (count == 0) return [];
  1508. var parenDepth = 0;
  1509. const argCount = 1;
  1510. // Populate argTokens with tuples of start and end token indices for each arg.
  1511. /** @type {int[][]} */
  1512. var argTokens = []; // argindex -> [ start, end ]
  1513. var exprStartToken = start;
  1514. for (var i = start; i <= end; i++) {
  1515. if (tokens[i].type == CellExpressionTokenType.OpenParen) {
  1516. parenDepth++;
  1517. } else if (tokens[i].type == CellExpressionTokenType.CloseParen) {
  1518. parenDepth--;
  1519. } else if (tokens[i].type == CellExpressionTokenType.Comma && parenDepth == 0) {
  1520. const exprEndToken = i - 1;
  1521. argTokens.push([ exprStartToken, exprEndToken ]);
  1522. exprStartToken = i + 1;
  1523. }
  1524. }
  1525. argTokens.push([ exprStartToken, end ]);
  1526. // Convert token ranges to expressions
  1527. var args = [];
  1528. for (const argToken of argTokens) {
  1529. const arg = this.#tryExpression(tokens, argToken[0], argToken[1], address);
  1530. if (arg === null) return null;
  1531. args.push(arg);
  1532. }
  1533. return args;
  1534. }
  1535. /**
  1536. * @param {CellExpressionToken[]} tokens
  1537. * @param {number} start
  1538. * @param {number} end
  1539. * @param {CellAddress} address
  1540. * @returns {CellExpression|null}
  1541. */
  1542. static #tryRange(tokens, start, end, address) {
  1543. const count = end - start + 1;
  1544. if (count != 3) return null;
  1545. if (!tokens[start].type.isPotentialAddress()) return null;
  1546. const first = tokens[start].content.toUpperCase();
  1547. if (tokens[start + 1].type != CellExpressionTokenType.Colon) return null;
  1548. if (!tokens[end].type.isPotentialAddress()) return null;
  1549. const last = tokens[end].content.toUpperCase();
  1550. const firstAddress = new CellAddress(first);
  1551. const lastAddress = new CellAddress(last);
  1552. const range = new CellAddressRange(firstAddress, lastAddress);
  1553. return new CellExpression(CellExpressionOperation.Range, [ range ]);
  1554. }
  1555. /**
  1556. * @param {CellExpressionToken[]} tokens
  1557. * @param {number} start
  1558. * @param {number} end
  1559. * @param {CellAddress} address
  1560. * @returns {CellExpression|null}
  1561. */
  1562. static #tryReference(tokens, start, end, address) {
  1563. if (start != end) return null;
  1564. if (!tokens[start].type.isPotentialAddress()) return null;
  1565. const ref = tokens[start].content.toUpperCase();
  1566. const refAddress = CellAddress.fromString(ref, address, true);
  1567. return new CellExpression(CellExpressionOperation.Reference, [ refAddress ]);
  1568. }
  1569. /**
  1570. * @param {CellExpressionToken[]} tokens
  1571. * @param {number} start
  1572. * @param {number} end
  1573. * @param {CellAddress} address
  1574. * @returns {CellExpression|null}
  1575. */
  1576. static #tryInfix(tokens, start, end, address) {
  1577. const count = end - start + 1;
  1578. if (count < 3) return null;
  1579. const opPriorities = {}
  1580. opPriorities[CellExpressionTokenType.Multiply.name] = 4;
  1581. opPriorities[CellExpressionTokenType.Divide.name] = 3;
  1582. opPriorities[CellExpressionTokenType.Plus.name] = 2;
  1583. opPriorities[CellExpressionTokenType.Minus.name] = 1;
  1584. opPriorities[CellExpressionTokenType.Ampersand.name] = 10;
  1585. opPriorities[CellExpressionTokenType.GreaterThan.name] = 20;
  1586. opPriorities[CellExpressionTokenType.GreaterThanEqual.name] = 20;
  1587. opPriorities[CellExpressionTokenType.LessThan.name] = 20;
  1588. opPriorities[CellExpressionTokenType.LessThanEqual.name] = 20;
  1589. opPriorities[CellExpressionTokenType.Equal.name] = 20;
  1590. opPriorities[CellExpressionTokenType.Unequal.name] = 20;
  1591. var candidates = [];
  1592. var parenLevel = 0;
  1593. var i;
  1594. for (i = start; i <= end; i++) {
  1595. if (tokens[i].type == CellExpressionTokenType.OpenParen) {
  1596. parenLevel++;
  1597. } else if (tokens[i].type == CellExpressionTokenType.CloseParen) {
  1598. parenLevel--;
  1599. } else if (parenLevel == 0 && i > start && i < end) {
  1600. const op = tokens[i].type.name;
  1601. const priority = opPriorities[op] ?? false;
  1602. if (priority === false) continue;
  1603. //console.info(`Found infix candidate at ${i} for ${op} priority ${priority}`);
  1604. candidates.push({ priority: priority, i: i });
  1605. }
  1606. }
  1607. candidates.sort((a, b) => a.priority - b.priority);
  1608. var bestCandidate = null;
  1609. var operand1, operand2;
  1610. for (const candidate of candidates) {
  1611. try {
  1612. i = candidate.i;
  1613. operand1 = this.#tryExpression(tokens, start, i - 1, address);
  1614. if (operand1 === null) continue;
  1615. operand2 = this.#tryExpression(tokens, i + 1, end, address);
  1616. if (operand2 === null) continue;
  1617. bestCandidate = candidate;
  1618. break;
  1619. } catch (e) {
  1620. if (!(e instanceof CellSyntaxException)) {
  1621. throw e;
  1622. }
  1623. }
  1624. }
  1625. if (bestCandidate === null) {
  1626. //console.info("No best candidate found");
  1627. return null;
  1628. }
  1629. i = bestCandidate.i;
  1630. //console.info(`Best candidate at token ${i}, priority ${bestCandidate.priority}`);
  1631. switch (tokens[bestCandidate.i].type) {
  1632. case CellExpressionTokenType.Plus:
  1633. return new CellExpression(CellExpressionOperation.Add, [ operand1, operand2 ]);
  1634. case CellExpressionTokenType.Minus:
  1635. return new CellExpression(CellExpressionOperation.Subtract, [ operand1, operand2 ]);
  1636. case CellExpressionTokenType.Multiply:
  1637. return new CellExpression(CellExpressionOperation.Multiply, [ operand1, operand2 ]);
  1638. case CellExpressionTokenType.Divide:
  1639. return new CellExpression(CellExpressionOperation.Divide, [ operand1, operand2 ]);
  1640. case CellExpressionTokenType.GreaterThan:
  1641. return new CellExpression(CellExpressionOperation.GreaterThan, [ operand1, operand2 ]);
  1642. case CellExpressionTokenType.GreaterThanEqual:
  1643. return new CellExpression(CellExpressionOperation.GreaterThanEqual, [ operand1, operand2 ]);
  1644. case CellExpressionTokenType.LessThan:
  1645. return new CellExpression(CellExpressionOperation.LessThan, [ operand1, operand2 ]);
  1646. case CellExpressionTokenType.LessThanEqual:
  1647. return new CellExpression(CellExpressionOperation.LessThanEqual, [ operand1, operand2 ]);
  1648. case CellExpressionTokenType.Equal:
  1649. return new CellExpression(CellExpressionOperation.Equal, [ operand1, operand2 ]);
  1650. case CellExpressionTokenType.Unequal:
  1651. return new CellExpression(CellExpressionOperation.Unequal, [ operand1, operand2 ]);
  1652. case CellExpressionTokenType.Ampersand:
  1653. return new CellExpression(CellExpressionOperation.Concatenate, [ operand1, operand2 ]);
  1654. }
  1655. return null;
  1656. }
  1657. /**
  1658. * @param {CellExpressionToken[]} tokens
  1659. * @param {number} start
  1660. * @param {number} end
  1661. * @param {CellAddress} address
  1662. * @returns {CellExpression|null}
  1663. */
  1664. static #tryUnary(tokens, start, end, address) {
  1665. const count = end - start + 1;
  1666. if (count < 2) return null;
  1667. const ops = [
  1668. [ CellExpressionTokenType.Minus, CellExpressionOperation.UnaryMinus ],
  1669. [ CellExpressionTokenType.Not, CellExpressionOperation.UnaryNot ],
  1670. ];
  1671. for (const op of ops) {
  1672. if (tokens[start].type != op[0]) continue;
  1673. const operand = this.#tryExpression(tokens, start + 1, end, address);
  1674. if (operand === null) return null;
  1675. return new CellExpression(op[1], [ operand ]);
  1676. }
  1677. return null;
  1678. }
  1679. }
  1680. /**
  1681. * Parsing token for an expression.
  1682. */
  1683. class CellExpressionToken {
  1684. /** @type {CellExpressionTokenType} */
  1685. type;
  1686. /** @type {string} */
  1687. content;
  1688. /**
  1689. * @param {CellExpressionTokenType} type
  1690. * @param {string} content
  1691. */
  1692. constructor(type, content) {
  1693. this.type = type;
  1694. this.content = content;
  1695. }
  1696. }
  1697. /**
  1698. * The location of a cell in a table. If the address was specified without a
  1699. * row, the address is considered "unresolved" and needs more context to
  1700. * uniquely identify a cell.
  1701. */
  1702. class CellAddress {
  1703. #name;
  1704. /**
  1705. * @type {string}
  1706. */
  1707. get name() { return this.#name; }
  1708. #isColumnFixed = false;
  1709. /**
  1710. * Whether the column should remain unchanged when transposed. This is
  1711. * symbolized by prefixing the column name with a `$` (e.g. `$C3`).
  1712. * @type {boolean}
  1713. */
  1714. get isColumnFixed() { return this.#isColumnFixed; }
  1715. #columnIndex = -1;
  1716. /**
  1717. * Zero-based column index.
  1718. * @type {number}
  1719. */
  1720. get columnIndex() { return this.#columnIndex; };
  1721. /**
  1722. * Letter code for the column.
  1723. * @type {string}
  1724. */
  1725. get columnLetter() { return CellAddress.#columnIndexToLetters(this.#columnIndex); }
  1726. #isRowFixed = false;
  1727. /**
  1728. * Whether the row should remain unchanged when transposed. This is
  1729. * symbolized by prefixing the row number with a `$` (e.g. `C$3`).
  1730. * @type {boolean}
  1731. */
  1732. get isRowFixed() { return this.#isRowFixed; }
  1733. #rowIndex = -1;
  1734. /**
  1735. * Zero-based row index.
  1736. * @type {number}
  1737. */
  1738. get rowIndex() { return this.#rowIndex; }
  1739. /**
  1740. * One-based row number. This is the human-facing row number.
  1741. */
  1742. get rowNumber() { return this.#rowIndex + 1; }
  1743. /**
  1744. * Whether this address has both a definite column and row.
  1745. * @type {boolean}
  1746. */
  1747. get isResolved() { return this.columnIndex >= 0 && this.rowIndex >= 0; }
  1748. /**
  1749. * @param {number} columnIndex - 0-based column index
  1750. * @param {number} rowIndex - 0-based row index
  1751. * @param {boolean} isColumnFixed - whether the column name is fixed in
  1752. * place during transpositions. Denoted with a `$` in front of the column letters.
  1753. * @param {boolean} isRowFixed - whether the row number is fixed in place
  1754. * during transpositions. Denoted with a `$` in front of the row digits.
  1755. */
  1756. constructor(columnIndex, rowIndex, isColumnFixed=false, isRowFixed=false) {
  1757. if (typeof columnIndex != 'number') {
  1758. throw new Error(`columnIndex must be number, got ${typeof columnIndex}`);
  1759. }
  1760. if (typeof rowIndex != 'number') {
  1761. throw new Error(`rowIndex must be number, got ${typeof rowIndex}`);
  1762. }
  1763. this.#columnIndex = columnIndex;
  1764. this.#rowIndex = rowIndex;
  1765. this.#isColumnFixed = isColumnFixed;
  1766. this.#isRowFixed = isRowFixed;
  1767. this.#name = CellAddress.#formatAddress(columnIndex, rowIndex, isColumnFixed, isRowFixed);
  1768. }
  1769. /**
  1770. * Tests if a string is formatted like an address.
  1771. * @param {string} text
  1772. * @returns {boolean}
  1773. */
  1774. static isAddress(text) {
  1775. return this.fromString(text) != null;
  1776. }
  1777. /**
  1778. * Returns a converted form of this address reference in a formula that has
  1779. * been copied from its original location. In other words, if a formula
  1780. * refers to a cell one to the left and that formula is copied to the next
  1781. * cell down, that copy's reference should point to the cell on the next
  1782. * row as well. Addresses with an absolute column or row (e.g. "A5") will
  1783. * not be altered on that axis.
  1784. *
  1785. * Examples:
  1786. * - C6.transpose(A5, A9) = C10 (A9-A5 = +4 rows, C6 + 4 rows = C10)
  1787. * - C6.transpose(A5, B9) = D10 (B9-A5 = +4 rows +1 cols, C6 + 4 rows + 1 col = D10)
  1788. * - C$6.transpose(A5, A9) = C6 (A9-A5 = +4 rows, but row is fixed, so still C6)
  1789. * - B.transpose(A5, A9) = B9 (A9-A4 = +4 rows, B has no row so last row used = B9)
  1790. * - A1.transpose(C3, A1) = null (out of bounds)
  1791. *
  1792. * @param {CellAddress} relativeFrom - original address of the formula
  1793. * @param {CellAddress} relativeTo - address where the formula is being repeated
  1794. * @param {boolean} resolveToRow - whether to fill in a row number if this address
  1795. * doesn't have one
  1796. * @returns {CellAddress|null} - resolved address, or `null` if out of bounds
  1797. */
  1798. transpose(relativeFrom, relativeTo, resolveToRow = true) {
  1799. if (!relativeFrom.isResolved || !relativeTo.isResolved) {
  1800. throw new CellEvaluationException("Can only transpose to and from resolved addresses");
  1801. }
  1802. var newColumnIndex = this.columnIndex;
  1803. if (!this.isColumnFixed) {
  1804. const columnDelta = relativeTo.columnIndex - relativeFrom.columnIndex;
  1805. newColumnIndex += columnDelta;
  1806. }
  1807. var newRowIndex = this.rowIndex;
  1808. if (!this.isResolved && resolveToRow) {
  1809. newRowIndex = relativeFrom.rowIndex;
  1810. }
  1811. if (newRowIndex != -1 && !this.isRowAbsolute) {
  1812. const rowDelta = relativeTo.rowIndex - relativeFrom.rowIndex;
  1813. newRowIndex += rowDelta;
  1814. }
  1815. if (newColumnIndex < 0 || newRowIndex < 0) return null;
  1816. return new CellAddress(newColumnIndex, newRowIndex);
  1817. }
  1818. equals(other) {
  1819. if (!(other instanceof CellAddress)) return false;
  1820. return other.columnIndex == this.columnIndex && other.rowIndex == this.rowIndex;
  1821. }
  1822. exactlyEquals(other) {
  1823. if (!(other instanceof CellAddress)) return false;
  1824. return other.name == this.name;
  1825. }
  1826. toString() {
  1827. return this.name;
  1828. }
  1829. /**
  1830. * Converts column letters (e.g. `A`, `C`, `AA`) to a 0-based column index.
  1831. * Assumes a validated well-formed column letter or else behavior is undefined.
  1832. *
  1833. * @param {string} letters
  1834. * @returns {number} column index
  1835. */
  1836. static #lettersToColumnIndex(letters) {
  1837. const ACodepoint = 'A'.codePointAt(0);
  1838. var columnIndex = 0;
  1839. for (var i = letters.length - 1; i >= 0; i--) {
  1840. const letterIndex = letters.codePointAt(i) - ACodepoint;
  1841. columnIndex = columnIndex * 26 + letterIndex;
  1842. }
  1843. return columnIndex;
  1844. }
  1845. /**
  1846. * Converts a column index to column letters (e.g. index 0 = `A`).
  1847. *
  1848. * @param {number} columnIndex
  1849. * @returns {string}
  1850. */
  1851. static #columnIndexToLetters(columnIndex) {
  1852. var letters = '';
  1853. if (columnIndex >= 0) {
  1854. const ACodepoint = 'A'.codePointAt(0);
  1855. var remaining = columnIndex;
  1856. do {
  1857. letters = String.fromCodePoint(ACodepoint + (remaining % 26)) + letters;
  1858. remaining = Math.floor(remaining / 26);
  1859. } while (remaining > 0);
  1860. }
  1861. return letters;
  1862. }
  1863. static #formatAddress(columnIndex, rowIndex, isColumnFixed, isRowFixed) {
  1864. var addr = '';
  1865. if (isColumnFixed && columnIndex >= 0) addr += '$';
  1866. if (columnIndex >= 0) addr += this.#columnIndexToLetters(columnIndex);
  1867. if (isRowFixed && rowIndex >= 0) addr += '$';
  1868. if (rowIndex >= 0) addr += `${rowIndex + 1}`;
  1869. return addr;
  1870. }
  1871. /**
  1872. * Attempts to convert a cell address string to a `CellAddress`.
  1873. *
  1874. * @param {string} address - cell address string
  1875. * @param {CellAddress|null} relativeTo - address to resolve relative addresses against
  1876. * @param {boolean} throwIfInvalid - whether to throw an error if address is invalid
  1877. * @returns {CellAddress|null} address, if parsable
  1878. * @throws {CellEvaluationException} if the address is invalid and `throwIfInvalid`
  1879. * is `true`
  1880. */
  1881. static fromString(address, relativeTo=null, throwIfInvalid=false) {
  1882. const groups = /^(\$?)([A-Z]{1,2}?)((?:\$(?=[0-9]))?)([0-9]*)$/i.exec(address);
  1883. if (groups === null) {
  1884. if (throwIfInvalid) throw new CellEvaluationException(`Bad address "${address}"`, '#REF');
  1885. return null;
  1886. }
  1887. const isColumnFixed = groups[1] == '$';
  1888. const letters = groups[2].toUpperCase();
  1889. const isRowFixed = groups[3] == '$';
  1890. const numbers = groups[4];
  1891. var columnIndex = this.#lettersToColumnIndex(letters);
  1892. var rowIndex = (numbers.length == 0) ? -1 : parseInt(numbers) - 1;
  1893. if (columnIndex < 0 && relativeTo != null) columnIndex = relativeTo.columnIndex;
  1894. if (rowIndex < 0 && relativeTo != null) rowIndex = relativeTo.rowIndex;
  1895. return new CellAddress(columnIndex, rowIndex, isColumnFixed, isRowFixed);
  1896. }
  1897. }
  1898. /**
  1899. * Range of cells addresses. Can be iterated via `cellsIn`.
  1900. */
  1901. class CellAddressRange {
  1902. /** @type {boolean} */
  1903. isResolved;
  1904. /** @type {number} */
  1905. minColumnIndex;
  1906. /** @type {number} */
  1907. maxColumnIndex;
  1908. /** @type {number} */
  1909. minRowIndex;
  1910. /** @type {number} */
  1911. maxRowIndex;
  1912. /** @type {string} */
  1913. name;
  1914. /**
  1915. * Creates a rectangular range between two corner cells. They can be in
  1916. * any order. The given cells must either both be resolved or both unresolved.
  1917. *
  1918. * @param {CellAddress} fromCell
  1919. * @param {CellAddress} toCell
  1920. */
  1921. constructor(fromCell, toCell) {
  1922. if (fromCell.isResolved != toCell.isResolved) {
  1923. throw new CellEvaluationException(`Cannot mix resolved and unresolved cell addresses in range: ${fromCell.name} and ${toCell.name}`);
  1924. }
  1925. this.minColumnIndex = Math.min(fromCell.columnIndex, toCell.columnIndex);
  1926. this.maxColumnIndex = Math.max(fromCell.columnIndex, toCell.columnIndex);
  1927. this.minRowIndex = Math.min(fromCell.rowIndex, toCell.rowIndex);
  1928. this.maxRowIndex = Math.max(fromCell.rowIndex, toCell.rowIndex);
  1929. this.isResolved = fromCell.isResolved;
  1930. this.name = (new CellAddress(this.minColumnIndex, this.minRowIndex)).name +
  1931. ':' +
  1932. (new CellAddress(this.maxColumnIndex, this.maxRowIndex)).name;
  1933. }
  1934. /**
  1935. * Creates an iterator for every `CellAddress` in this range within the
  1936. * confines of the given grid's dimensions. Iterates each row in the first
  1937. * column, then each row in the second, etc. Iteration range is inclusive
  1938. * of the min and max extents.
  1939. *
  1940. * Example:
  1941. * ```
  1942. * for (const address of range.cellsIn(grid)) {
  1943. * ...
  1944. * }
  1945. * ```
  1946. *
  1947. * @param {SpreadsheetGrid} grid
  1948. * @returns {object} iterable object
  1949. */
  1950. cellsIn(grid) {
  1951. const minCol = this.minColumnIndex < 0 ? 0 : this.minColumnIndex;
  1952. const maxCol = this.maxColumnIndex < 0 ? grid.columnCount - 1 : Math.min(this.maxColumnIndex, grid.columnCount - 1);
  1953. const minRow = this.minRowIndex < 0 ? 0 : this.minRowIndex;
  1954. const maxRow = this.maxRowIndex < 0 ? grid.rowCount - 1 : Math.min(this.maxRowIndex, grid.rowCount - 1);
  1955. const iterable = {};
  1956. iterable[Symbol.iterator] = function() {
  1957. var currentCol = minCol;
  1958. var currentRow = minRow;
  1959. return {
  1960. next() {
  1961. const col = currentCol;
  1962. const row = currentRow++;
  1963. if (currentRow > maxRow) {
  1964. currentRow = minRow;
  1965. currentCol++;
  1966. }
  1967. return {
  1968. value: new CellAddress(col, row),
  1969. done: col > maxCol || row > maxRow,
  1970. };
  1971. }
  1972. };
  1973. };
  1974. return iterable;
  1975. }
  1976. }
  1977. /**
  1978. * A value in a spreadsheet or calculation.
  1979. */
  1980. class CellValue {
  1981. /**
  1982. * Blank cell. `value` is `null`.
  1983. */
  1984. static TYPE_BLANK = 'blank';
  1985. /**
  1986. * Currency value. `value` is `number`.
  1987. */
  1988. static TYPE_CURRENCY = 'currency';
  1989. /**
  1990. * Regular number value. `value` is `number`.
  1991. */
  1992. static TYPE_NUMBER = 'number';
  1993. /**
  1994. * Percentage. `value` is `number`, represented as a ratio (100% = 1.0).
  1995. */
  1996. static TYPE_PERCENT = 'percent';
  1997. /**
  1998. * Unaltered text value. `value` is `string`.
  1999. */
  2000. static TYPE_STRING = 'string';
  2001. /**
  2002. * Boolean. `value` is `boolean`.
  2003. */
  2004. static TYPE_BOOLEAN = 'boolean';
  2005. /**
  2006. * A formula that has resulted in an error during parsing or evaluation.
  2007. * `value` is `string` error message.
  2008. */
  2009. static TYPE_ERROR = 'error';
  2010. /**
  2011. * A formula expression. `value` is `string` and includes the leading `=`.
  2012. */
  2013. static TYPE_FORMULA = 'formula';
  2014. // -- Properties -----
  2015. /**
  2016. * A blank value.
  2017. * @type {CellValue}
  2018. */
  2019. static BLANK = new CellValue('', null, CellValue.TYPE_BLANK);
  2020. /**
  2021. * Type of value. One of the `TYPE_` constants.
  2022. * @type {string}
  2023. */
  2024. type = CellValue.TYPE_STRING;
  2025. /**
  2026. * Number of decimal places shown in the formatted value.
  2027. * @type {number}
  2028. */
  2029. decimals = 0;
  2030. /**
  2031. * The string shown in the table cell to the user.
  2032. * @type {string}
  2033. */
  2034. formattedValue = '';
  2035. /**
  2036. * The PHP data value. E.g. a `float` for currency values or an `Exception`
  2037. * for errors.
  2038. * @type {any}
  2039. */
  2040. value = null;
  2041. /**
  2042. * Constructs a cell value explicitly. Values are not validated. Consider
  2043. * using `.fromCellString()` or `.fromValue()` to populate values more
  2044. * intelligently and consistently.
  2045. *
  2046. * @param {string} formattedValue
  2047. * @param {any} value
  2048. * @param {string} type
  2049. * @param {number} decimals
  2050. */
  2051. constructor(
  2052. formattedValue,
  2053. value = null,
  2054. type = CellValue.TYPE_STRING,
  2055. decimals = 0
  2056. ) {
  2057. this.formattedValue = formattedValue;
  2058. this.value = value;
  2059. this.type = type;
  2060. this.decimals = decimals;
  2061. }
  2062. /**
  2063. * Returns whether this value is a numeric type.
  2064. * @returns {boolean}
  2065. */
  2066. isNumeric() {
  2067. return CellValue.isTypeNumeric(this.type);
  2068. }
  2069. /**
  2070. * Creates a CellValue from formatted table cell contents. Attempts to
  2071. * detect formatted numbers including currency and percentages.
  2072. *
  2073. * @param {string} cellString
  2074. * @returns {CellValue}
  2075. */
  2076. static fromCellString(cellString) {
  2077. const cv = new CellValue(cellString);
  2078. cv.#populateFromCellString(cellString);
  2079. return cv;
  2080. }
  2081. /**
  2082. * Creates a CellValue from a value. Based off datatype, not string
  2083. * formatting; use `fromCellString` to parse formatted numbers.
  2084. *
  2085. * @param {any} value
  2086. * @param {string|null} type - optional forced type
  2087. * @param {number|null} decimals - optional number of decimal places to format to
  2088. * @returns {CellValue}
  2089. * @throws {CellEvaluationException} if `value` is of an unsupported type
  2090. */
  2091. static fromValue(value, type = null, decimals = null) {
  2092. if (value === null) {
  2093. return new CellValue('', null, CellValue.TYPE_BLANK);
  2094. }
  2095. if (value instanceof Error) {
  2096. if (value instanceof CellException) {
  2097. return new CellValue(value.errorSymbol, value.message, CellValue.TYPE_ERROR);
  2098. }
  2099. return new CellValue('#ERROR', value.message, CellValue.TYPE_ERROR);
  2100. }
  2101. if (typeof value == 'boolean') {
  2102. const formatted = CellValue.formatType(value, CellValue.TYPE_BOOLEAN, 0);
  2103. return new CellValue(formatted, value, CellValue.TYPE_BOOLEAN);
  2104. }
  2105. if (typeof value == 'number') {
  2106. const resolvedType = type || CellValue.TYPE_NUMBER;
  2107. const resolvedDecimals = (decimals !== null) ? decimals :
  2108. (resolvedType == CellValue.TYPE_CURRENCY ? 2 : CellValue.#autodecimals(resolvedType == CellValue.TYPE_PERCENT ? value * 100.0 : value));
  2109. const formatted = CellValue.formatType(value, resolvedType, resolvedDecimals);
  2110. return new CellValue(formatted, value, resolvedType, resolvedDecimals);
  2111. }
  2112. if (typeof value != 'string') {
  2113. throw new CellEvaluationException(`Value of type ${typeof value} unsupported`);
  2114. }
  2115. const trimmed = value.trim();
  2116. if (trimmed.startsWith('=')) {
  2117. return new CellValue(trimmed, trimmed, CellValue.TYPE_FORMULA);
  2118. }
  2119. return new CellValue(trimmed, trimmed, CellValue.TYPE_STRING);
  2120. }
  2121. /**
  2122. * @param {string|null} cellString
  2123. */
  2124. #populateFromCellString(cellString) {
  2125. cellString = (cellString !== null) ? cellString.trim() : null;
  2126. this.formattedValue = cellString;
  2127. // blank
  2128. if (cellString === null || cellString == '') {
  2129. this.type = CellValue.TYPE_BLANK;
  2130. this.value = null;
  2131. return;
  2132. }
  2133. // 'literal
  2134. if (cellString.startsWith("'")) {
  2135. const stripped = cellString.substring(1).trim();
  2136. this.type = CellValue.TYPE_STRING;
  2137. this.formattedValue = stripped;
  2138. this.value = stripped;
  2139. return;
  2140. }
  2141. // =TRUE
  2142. const caps = cellString.toUpperCase();
  2143. if (caps == 'TRUE') {
  2144. this.type = CellValue.TYPE_BOOLEAN;
  2145. this.formattedValue = caps;
  2146. this.value = true;
  2147. this.formattedValue = 'TRUE';
  2148. return;
  2149. }
  2150. // =FALSE
  2151. if (caps == 'FALSE') {
  2152. this.type = CellValue.TYPE_BOOLEAN;
  2153. this.formattedValue = caps;
  2154. this.value = false;
  2155. this.formattedValue = 'FALSE';
  2156. return;
  2157. }
  2158. // =A*B
  2159. if (cellString.startsWith('=')) {
  2160. this.type = CellValue.TYPE_FORMULA;
  2161. this.value = cellString;
  2162. return;
  2163. }
  2164. // -$1,234.56
  2165. var groups;
  2166. if (groups = /^([-]?)\$(-?[0-9,]*\.)([0-9]+)$/.exec(cellString)) {
  2167. const sign = groups[1];
  2168. const dollars = groups[2].replace(/,/g, '');
  2169. const cents = groups[3];
  2170. this.type = CellValue.TYPE_CURRENCY;
  2171. this.decimals = 2;
  2172. this.value = parseFloat(sign + dollars + cents);
  2173. this.formattedValue = CellValue.#formatCurrency(this.value, this.decimals);
  2174. return;
  2175. }
  2176. // -$1,234
  2177. if (groups = /^([-]?)\$(-?[0-9,]+)$/.exec(cellString)) {
  2178. const sign = groups[1];
  2179. const dollars = groups[2].replace(/,/g, '');
  2180. this.type = CellValue.TYPE_CURRENCY;
  2181. this.decimals = 0;
  2182. this.value = parseFloat(sign + dollars);
  2183. this.formattedValue = CellValue.#formatCurrency(this.value, this.decimals);
  2184. return;
  2185. }
  2186. // -1,234.56%
  2187. if (groups = /^([-]?[0-9,]*\.)([0-9,]+)%$/.exec(cellString)) {
  2188. const wholes = groups[1].replace(/,/, '');
  2189. const decimals = groups[2];
  2190. this.type = CellValue.TYPE_PERCENT;
  2191. this.decimals = decimals.length;
  2192. this.value = parseFloat(wholes + decimals) / 100.0;
  2193. this.formattedValue = CellValue.#formatPercent(this.value, this.decimals);
  2194. return;
  2195. }
  2196. // -1,234%
  2197. if (groups = /^([-]?[0-9,]+)%$/.exec(cellString)) {
  2198. const wholes = groups[1].replace(/,/g, '');
  2199. this.type = CellValue.TYPE_PERCENT;
  2200. this.decimals = 0;
  2201. this.value = parseFloat(wholes) / 100.0;
  2202. this.formattedValue = CellValue.#formatPercent(this.value, this.decimals);
  2203. return;
  2204. }
  2205. // -1,234.56
  2206. if (groups = /^([-]?[0-9,]*\.)([0-9]+)$/.exec(cellString)) {
  2207. const wholes = groups[1].replace(/,/g, '');
  2208. const decimals = groups[2];
  2209. this.type = CellValue.TYPE_NUMBER;
  2210. this.decimals = decimals.length;
  2211. this.value = parseFloat(wholes + decimals);
  2212. this.formattedValue = CellValue.#formatNumber(this.value, this.decimals);
  2213. return;
  2214. }
  2215. // -1,234
  2216. if (groups = /^([-]?[0-9,]+)$/.exec(cellString)) {
  2217. const wholes = groups[1].replace(/,/g, '');
  2218. this.type = CellValue.TYPE_NUMBER;
  2219. this.decimals = 0;
  2220. this.value = parseFloat(wholes);
  2221. this.formattedValue = CellValue.#formatNumber(this.value, this.decimals);
  2222. return;
  2223. }
  2224. this.type = CellValue.TYPE_STRING;
  2225. this.value = cellString;
  2226. }
  2227. /**
  2228. * Returns the boolean equivalent of this value if possible.
  2229. * @returns {boolean|null}
  2230. */
  2231. booleanValue() {
  2232. switch (this.type) {
  2233. case CellValue.TYPE_BLANK:
  2234. return false;
  2235. case CellValue.TYPE_BOOLEAN:
  2236. return this.value;
  2237. case CellValue.TYPE_CURRENCY:
  2238. case CellValue.TYPE_NUMBER:
  2239. case CellValue.TYPE_PERCENT:
  2240. return this.value != 0;
  2241. case CellValue.TYPE_ERROR:
  2242. case CellValue.TYPE_FORMULA:
  2243. case CellValue.TYPE_STRING:
  2244. return null;
  2245. }
  2246. }
  2247. /**
  2248. * Returns the numeric value of this value if possible.
  2249. * @returns {number|null}
  2250. */
  2251. numericValue() {
  2252. switch (this.type) {
  2253. case CellValue.TYPE_BLANK:
  2254. return 0.0;
  2255. case CellValue.TYPE_BOOLEAN:
  2256. return this.value ? 1.0 : 0.0;
  2257. case CellValue.TYPE_CURRENCY:
  2258. case CellValue.TYPE_NUMBER:
  2259. case CellValue.TYPE_PERCENT:
  2260. return this.value;
  2261. case CellValue.TYPE_ERROR:
  2262. case CellValue.TYPE_FORMULA:
  2263. case CellValue.TYPE_STRING:
  2264. return null;
  2265. }
  2266. }
  2267. /**
  2268. * Returns the string value of this value if possible.
  2269. * @param {boolean} formatted
  2270. * @returns {string|null}
  2271. */
  2272. stringValue(formatted = false) {
  2273. switch (this.type) {
  2274. case CellValue.TYPE_BLANK:
  2275. return '';
  2276. case CellValue.TYPE_BOOLEAN:
  2277. return this.value ? 'TRUE' : 'FALSE';
  2278. case CellValue.TYPE_CURRENCY:
  2279. case CellValue.TYPE_NUMBER:
  2280. case CellValue.TYPE_PERCENT:
  2281. return formatted ? this.formattedValue : `${this.value}`;
  2282. case CellValue.TYPE_STRING:
  2283. return formatted ? this.formattedValue : this.value;
  2284. case CellValue.TYPE_ERROR:
  2285. case CellValue.TYPE_FORMULA:
  2286. return null;
  2287. }
  2288. }
  2289. // -- Operations --------------------------------------------------------
  2290. /**
  2291. * Returns the result of this value plus `b`.
  2292. *
  2293. * @param {CellValue} b
  2294. * @returns {CellValue} sum
  2295. */
  2296. add(b) {
  2297. return CellValue.#binaryNumericOperation(this, b, '+', (aVal, bVal) => aVal + bVal);
  2298. }
  2299. /**
  2300. * Returns the result of this value minus `b`.
  2301. *
  2302. * @param {CellValue} b
  2303. * @returns {CellValue} difference
  2304. */
  2305. subtract(b) {
  2306. return CellValue.#binaryNumericOperation(this, b, '-', (aVal, bVal) => aVal - bVal);
  2307. }
  2308. /**
  2309. * Returns the result of this value multiplied by `b`.
  2310. *
  2311. * @param {CellValue} b
  2312. * @returns {CellValue} product
  2313. */
  2314. multiply(b) {
  2315. return CellValue.#binaryNumericOperation(this, b, '*', (aVal, bVal) => aVal * bVal);
  2316. }
  2317. /**
  2318. * Returns the result of this value divided by `b`.
  2319. *
  2320. * @param {CellValue} b
  2321. * @returns {CellValue} quotient
  2322. * @throws {CellEvaluationException} on divide by zero
  2323. */
  2324. divide(b) {
  2325. return CellValue.#binaryNumericOperation(this, b, '/', (aVal, bVal) => {
  2326. if (bVal == 0) throw new CellEvaluationException("Division by zero", '#NAN');
  2327. return aVal / bVal
  2328. });
  2329. }
  2330. /**
  2331. * Returns the result of this value modulo by `b`.
  2332. *
  2333. * @param {CellValue} b
  2334. * @returns {CellValue} remainder
  2335. * @throws {CellEvaluationException} on divide by zero
  2336. */
  2337. modulo(b) {
  2338. return CellValue.#binaryNumericOperation(this, b, '%', (aVal, bVal) => {
  2339. if (bVal == 0) throw new CellEvaluationException("Division by zero", '#NAN');
  2340. return aVal % bVal
  2341. });
  2342. }
  2343. /**
  2344. * Returns the result of whether this value is greater than `b`.
  2345. *
  2346. * @param {CellValue} b
  2347. * @returns {CellValue}
  2348. */
  2349. gt(b) {
  2350. return CellValue.fromValue(CellValue.#compare(this, b) > 0);
  2351. }
  2352. /**
  2353. * Returns the result of whether tihs value is greater than or equal to `b`.
  2354. *
  2355. * @param {CellValue} b
  2356. * @returns {CellValue}
  2357. */
  2358. gte(b) {
  2359. return CellValue.fromValue(CellValue.#compare(this, b) >= 0);
  2360. }
  2361. /**
  2362. * Returns the result of whether this value is less than `b`.
  2363. *
  2364. * @param {CellValue} b
  2365. * @returns {CellValue}
  2366. */
  2367. lt(b) {
  2368. return CellValue.fromValue(CellValue.#compare(this, b) < 0);
  2369. }
  2370. /**
  2371. * Returns the result of whether this value is less than or equal to `b`.
  2372. *
  2373. * @param {CellValue} b
  2374. * @returns {CellValue}
  2375. */
  2376. lte(b) {
  2377. return CellValue.fromValue(CellValue.#compare(this, b) <= 0);
  2378. }
  2379. /**
  2380. * Returns the result of whether this value is equal to `b`.
  2381. *
  2382. * @param {CellValue} b
  2383. * @returns {CellValue}
  2384. */
  2385. eq(b) {
  2386. return CellValue.fromValue(CellValue.#compare(this, b) == 0);
  2387. }
  2388. /**
  2389. * Returns the result of whether this value is unequal to `b`.
  2390. *
  2391. * @param {CellValue} b
  2392. * @returns {CellValue}
  2393. */
  2394. neq(b) {
  2395. return CellValue.fromValue(CellValue.#compare(this, b) != 0);
  2396. }
  2397. /**
  2398. * Returns the boolean not of this value.
  2399. * @returns {CellValue}
  2400. */
  2401. not() {
  2402. switch (this.type) {
  2403. case CellValue.TYPE_BLANK:
  2404. return CellValue.fromValue(true);
  2405. case CellValue.TYPE_CURRENCY:
  2406. case CellValue.TYPE_NUMBER:
  2407. case CellValue.TYPE_PERCENT:
  2408. return CellValue.fromValue(this.value == 0);
  2409. case CellValue.TYPE_STRING:
  2410. throw new CellEvaluationException("Cannot perform NOT on string");
  2411. case CellValue.TYPE_BOOLEAN:
  2412. return CellValue.fromValue(!this.value);
  2413. case CellValue.TYPE_ERROR:
  2414. throw this.value;
  2415. case CellValue.TYPE_FORMULA:
  2416. throw new CellEvaluationException("Cannot perform NOT on expression");
  2417. }
  2418. }
  2419. /**
  2420. * @param {CellValue} b
  2421. * @returns {CellValue}
  2422. */
  2423. concatenate(b) {
  2424. const s1 = this.stringValue(true);
  2425. const s2 = b.stringValue(true);
  2426. if (s1 === null || s2 === null) {
  2427. throw new CellEvaluationException("Concatenation requires string arguments");
  2428. }
  2429. return CellValue.fromValue(`${s1}${s2}`);
  2430. }
  2431. /**
  2432. * @param {CellValue} a
  2433. * @param {CellValue} b
  2434. * @param {string} op
  2435. * @param {function} fn - takes two `number` arguments and returns a `number` result
  2436. * @returns {CellValue}
  2437. * @throws {CellEvaluationException}
  2438. */
  2439. static #binaryNumericOperation(a, b, op, fn) {
  2440. const ops = this.#resolveNumericOperands(a, b, op);
  2441. const aNum = ops[0];
  2442. const bNum = ops[1];
  2443. const type = ops[2];
  2444. const result = fn(aNum, bNum);
  2445. return CellValue.fromValue(result, type);
  2446. }
  2447. /**
  2448. * Determines what the result of a calculation with two operands should
  2449. * look like. Returns a tuple array of the A float value, the B float value,
  2450. * and the type of the result.
  2451. *
  2452. * @param {CellValue} a - operand A
  2453. * @param {CellValue} b - operand B
  2454. * @param {string} op - operator symbol
  2455. * @returns {Array} 3-element tuple array with A number value, B number value,
  2456. * and result type string
  2457. * @throws {CellEvaluationException} if types are incompatible for numeric operations
  2458. */
  2459. static #resolveNumericOperands(a, b, op) {
  2460. if (a.type == this.TYPE_ERROR) throw a.value;
  2461. if (b.type == this.TYPE_ERROR) throw b.value;
  2462. if (a.type == this.TYPE_STRING || b.type == this.TYPE_STRING) {
  2463. throw new CellEvaluationException("Cannot perform math on text values");
  2464. }
  2465. if (a.type == this.TYPE_BLANK) {
  2466. if (b.type == this.TYPE_BLANK) {
  2467. return [ 0, 0, this.TYPE_NUMBER, 0 ];
  2468. }
  2469. return [ 0, b.value, b.type ];
  2470. } else if (b.type == this.TYPE_BLANK) {
  2471. return [ a.value, 0, a.type ];
  2472. }
  2473. const isMultOrDiv = (op == '*' || op == '/' || op == '%');
  2474. if (a.type == b.type) {
  2475. return [ a.value, b.value, a.type ];
  2476. }
  2477. switch (a.type + b.type) {
  2478. case this.TYPE_CURRENCY + this.TYPE_NUMBER:
  2479. case this.TYPE_CURRENCY + this.TYPE_PERCENT:
  2480. return [ a.value, b.value, this.TYPE_CURRENCY ];
  2481. case this.TYPE_PERCENT + this.TYPE_CURRENCY:
  2482. return [ a.value, b.value,
  2483. isMultOrDiv ? this.TYPE_CURRENCY : this.TYPE_PERCENT ];
  2484. case this.TYPE_PERCENT + this.TYPE_NUMBER:
  2485. return [ a.value, b.value,
  2486. isMultOrDiv ? this.TYPE_NUMBER : this.TYPE_PERCENT ];
  2487. case this.TYPE_NUMBER + this.TYPE_CURRENCY:
  2488. return [ a.value, b.value, b.type ];
  2489. case this.TYPE_NUMBER + this.TYPE_PERCENT:
  2490. return [ a.value, b.value,
  2491. isMultOrDiv ? this.TYPE_NUMBER : b.type ];
  2492. case this.TYPE_BOOLEAN + this.TYPE_CURRENCY:
  2493. case this.TYPE_BOOLEAN + this.TYPE_NUMBER:
  2494. case this.TYPE_BOOLEAN + this.TYPE_PERCENT:
  2495. return [ a.value ? 1 : 0, b.value, b.type ];
  2496. case this.TYPE_CURRENCY + this.TYPE_BOOLEAN:
  2497. case this.TYPE_NUMBER + this.TYPE_BOOLEAN:
  2498. case this.TYPE_PERCENT + this.TYPE_BOOLEAN:
  2499. return [ a.value, b.value ? 1 : 0, a.type ];
  2500. }
  2501. throw new CellEvaluationException(`Unhandled operand types "${a.type}" and "${b.type}"`);
  2502. }
  2503. /**
  2504. * @param {CellValue} a
  2505. * @param {CellValue} b
  2506. * @returns {number}
  2507. */
  2508. static #compare(a, b) {
  2509. const args = CellValue.#resolveComparableArguments(a, b);
  2510. const valueA = args[0];
  2511. const valueB = args[1];
  2512. if (typeof valueA == 'string') {
  2513. return valueA.localeCompare(valueB, undefined, { sensitivity: 'accent' });
  2514. } else {
  2515. if (valueA < valueB) return -1;
  2516. if (valueA > valueB) return 1;
  2517. return 0;
  2518. }
  2519. }
  2520. /**
  2521. * @param {CellValue} a
  2522. * @param {CellValue} b
  2523. * @returns {Array}
  2524. */
  2525. static #resolveComparableArguments(a, b) {
  2526. if (a.type == CellValue.TYPE_ERROR) throw a.value;
  2527. if (b.type == CellValue.TYPE_ERROR) throw b.value;
  2528. if (a.type == CellValue.TYPE_FORMULA) throw new CellEvaluationException("Can't compare formula values");
  2529. if (b.type == CellValue.TYPE_FORMULA) throw new CellEvaluationException("Can't compare formula values");
  2530. const aNumValue = a.value;
  2531. const bNumValue = b.value;
  2532. const aStrValue = `${a.value}`;
  2533. const bStrValue = `${b.value}`;
  2534. switch (a.type) {
  2535. case CellValue.TYPE_BLANK:
  2536. aNumValue = 0;
  2537. aStrValue = '';
  2538. break;
  2539. case CellValue.TYPE_BOOLEAN:
  2540. aNumValue = (aNumValue) ? 1 : 0;
  2541. break;
  2542. }
  2543. switch (b.type) {
  2544. case CellValue.TYPE_BLANK:
  2545. bNumValue = 0;
  2546. bStrValue = '';
  2547. break;
  2548. case CellValue.TYPE_BOOLEAN:
  2549. bNumValue = (bNumValue) ? 1 : 0;
  2550. break;
  2551. }
  2552. if (a.type == CellValue.TYPE_STRING || b.type == CellValue.TYPE_STRING) {
  2553. return [ aStrValue, bStrValue ];
  2554. }
  2555. return [ aNumValue, bNumValue ];
  2556. }
  2557. /**
  2558. * Returns a formatted string for the given raw value, value type, and
  2559. * decimal places.
  2560. * @param {any} value
  2561. * @param {string} type
  2562. * @param {number} decimals
  2563. * @returns {string}
  2564. */
  2565. static formatType(value, type, decimals) {
  2566. switch (type) {
  2567. case CellValue.TYPE_BLANK: return '';
  2568. case CellValue.TYPE_CURRENCY: return CellValue.#formatCurrency(value, decimals);
  2569. case CellValue.TYPE_NUMBER: return CellValue.#formatNumber(value, decimals);
  2570. case CellValue.TYPE_PERCENT: return CellValue.#formatPercent(value, decimals);
  2571. case CellValue.TYPE_BOOLEAN: return value ? 'TRUE' : 'FALSE';
  2572. case CellValue.TYPE_STRING: return `${value}`;
  2573. case CellValue.TYPE_FORMULA: return `${value}`;
  2574. }
  2575. }
  2576. /**
  2577. * @param {number} value
  2578. * @param {number} decimals
  2579. * @returns {string}
  2580. */
  2581. static #formatNumber(value, decimals) {
  2582. return (value).toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
  2583. }
  2584. /**
  2585. * @param {number} dollars
  2586. * @param {number} decimals
  2587. * @returns {string}
  2588. */
  2589. static #formatCurrency(dollars, decimals) {
  2590. var s = (dollars).toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
  2591. if (s.startsWith('-')) {
  2592. return '-$' + s.substring(1);
  2593. }
  2594. return '$' + s;
  2595. }
  2596. /**
  2597. * @param {number} value
  2598. * @param {number} decimals
  2599. * @returns {string}
  2600. */
  2601. static #formatPercent(value, decimals) {
  2602. const dec = value * 100.0;
  2603. return (dec).toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals }) + '%';
  2604. }
  2605. /**
  2606. * Determines a good number of decimal places to format a value to.
  2607. * @param {any} value
  2608. * @param {number} maxDigits
  2609. * @returns {number}
  2610. */
  2611. static #autodecimals(value, maxDigits = 6) {
  2612. if (value instanceof CellValue) {
  2613. return CellValue.#autodecimals(value.value);
  2614. }
  2615. if (typeof value == 'number') {
  2616. var s = (value).toLocaleString(undefined, { maximumFractionDigits: maxDigits });
  2617. if (/\./.exec(s) === null) return 0;
  2618. var fraction = s.split('.')[1];
  2619. return Math.min(maxDigits, fraction.length);
  2620. }
  2621. return 0;
  2622. }
  2623. /**
  2624. * @param {string} type
  2625. * @returns {boolean}
  2626. */
  2627. static isTypeNumeric(type) {
  2628. return type == CellValue.TYPE_NUMBER ||
  2629. type == CellValue.TYPE_PERCENT ||
  2630. type == CellValue.TYPE_CURRENCY ||
  2631. type == CellValue.TYPE_BOOLEAN;
  2632. }
  2633. toString() {
  2634. return `[CellValue type=${this.type} value=${this.value} "${this.formattedValue}"]`;
  2635. }
  2636. }
  2637. /**
  2638. * A rectangular grid of `SpreadsheetCell`s representing a spreadsheet.
  2639. * Agnostic of presentation.
  2640. */
  2641. class SpreadsheetGrid {
  2642. /**
  2643. * Indexed by column then row.
  2644. * @type {SpreadsheetCell[][]}
  2645. */
  2646. cells;
  2647. /** @type {number} */
  2648. columnCount;
  2649. /** @type {number} */
  2650. rowCount;
  2651. /**
  2652. * @param {number} columnCount
  2653. * @param {number} rowCount
  2654. */
  2655. constructor(columnCount, rowCount) {
  2656. this.columnCount = columnCount;
  2657. this.rowCount = rowCount;
  2658. this.cells = new Array(columnCount);
  2659. for (var c = 0; c < columnCount; c++) {
  2660. this.cells[c] = new Array(rowCount);
  2661. for (var r = 0; r < rowCount; r++) {
  2662. this.cells[c][r] = new SpreadsheetCell();
  2663. }
  2664. }
  2665. }
  2666. /**
  2667. * @param {CellAddress} address
  2668. * @returns {SpreadsheetCell|null} cell, or `null` if no cell available
  2669. * @throws {CellEvaluationException} if the address it out of bounds
  2670. */
  2671. cellAt(address) {
  2672. const c = address.columnIndex, r = address.rowIndex;
  2673. if (c < 0 || c >= this.cells.length) throw new CellEvaluationException(`Unresolved cell address ${address.name}`, '#REF');
  2674. const row = this.cells[c];
  2675. if (r < 0 || r >= row.length) throw new CellEvaluationException(`Unresolved cell address ${address.name}`, '#REF');
  2676. return row[r];
  2677. }
  2678. /**
  2679. * Returns the original value at the given address.
  2680. * @param {CellAddress} address
  2681. */
  2682. valueAt(address) {
  2683. return this.cellAt(address)?.originalValue;
  2684. }
  2685. /**
  2686. * Returns the computed value at the given address.
  2687. * @param {CellAddress} address
  2688. * @returns {CellValue|null} computed value or `null`
  2689. */
  2690. outputValueAt(address) {
  2691. return this.cellAt(address)?.outputValue;
  2692. }
  2693. }
  2694. /**
  2695. * One cell in a spreadsheet grid. Has an `originalValue` to start and an
  2696. * evaluated `outputValue` after population by a `CellExpressionSet` computation.
  2697. */
  2698. class SpreadsheetCell {
  2699. /**
  2700. * @type {CellValue}
  2701. */
  2702. originalValue = CellValue.BLANK;
  2703. /**
  2704. * @type {CellValue|null}
  2705. */
  2706. outputValue = null;
  2707. /** @type {boolean} */
  2708. isCalculated = false;
  2709. /** @type {CellExpression|null} */
  2710. parsedExpression = null;
  2711. /**
  2712. * @type {CellValue|null}
  2713. */
  2714. get resolvedValue() { return this.outputValue ?? this.originalValue; }
  2715. }
  2716. /**
  2717. * Integration with Markdown. Adding this block reader to a parser will run a
  2718. * post-process step on any tables in the document tree. Must be used with
  2719. * `MDTableReader`. Tables without at least one formula will not be altered.
  2720. */
  2721. class MDSpreadsheetReader extends MDReader {
  2722. postProcess(state, nodes) {
  2723. for (const node of nodes) {
  2724. if (node instanceof MDTableNode) {
  2725. this.#processTable(node, state);
  2726. }
  2727. }
  2728. }
  2729. /**
  2730. * @param {MDTableNode} tableNode
  2731. * @param {MDState} state
  2732. */
  2733. #processTable(tableNode, state) {
  2734. // Measure table
  2735. const rowCount = tableNode.bodyRows.length;
  2736. var columnCount = 0;
  2737. for (const row of tableNode.bodyRows) {
  2738. columnCount = Math.max(columnCount, row.children.length);
  2739. }
  2740. // Create and populate grid
  2741. const grid = new SpreadsheetGrid(columnCount, rowCount);
  2742. for (var c = 0; c < columnCount; c++) {
  2743. for (var r = 0; r < rowCount; r++) {
  2744. const cellNode = tableNode.bodyRows[r].children[c];
  2745. if (cellNode === undefined) continue;
  2746. const cellText = cellNode.toPlaintext(state);
  2747. const gridCell = grid.cells[c][r];
  2748. gridCell.originalValue = CellValue.fromCellString(cellText);
  2749. }
  2750. }
  2751. // Calculate
  2752. const expressions = new CellExpressionSet(grid);
  2753. expressions.calculateCells();
  2754. // See if anything was calculated. If not, don't mess with table.
  2755. var isCalculated = false;
  2756. for (var c = 0; c < columnCount && !isCalculated; c++) {
  2757. for (var r = 0; r < rowCount; r++) {
  2758. if (grid.cells[c][r].isCalculated) {
  2759. isCalculated = true;
  2760. break;
  2761. }
  2762. }
  2763. }
  2764. if (!isCalculated) return;
  2765. // Copy results back to table
  2766. for (var c = 0; c < columnCount; c++) {
  2767. for (var r = 0; r < rowCount; r++) {
  2768. const cellNode = tableNode.bodyRows[r].children[c];
  2769. if (cellNode === undefined) continue;
  2770. const gridCell = grid.cells[c][r];
  2771. const gridValue = gridCell.outputValue;
  2772. const cellText = gridValue.formattedValue;
  2773. cellNode.children = [ new MDTextNode(cellText) ];
  2774. if (gridCell.isCalculated) {
  2775. cellNode.cssClasses.push('calculated');
  2776. }
  2777. cellNode.cssClasses.push(`spreadsheet-type-${gridValue.type}`);
  2778. if (gridValue.type == CellValue.TYPE_ERROR) {
  2779. cellNode.attributes['title'] = gridValue.value;
  2780. }
  2781. const gridNumber = gridValue.numericValue();
  2782. if (gridNumber !== null) {
  2783. cellNode.attributes['data-numeric-value'] = `${gridNumber}`;
  2784. }
  2785. const gridString = gridValue.stringValue(false);
  2786. if (gridString !== null) {
  2787. cellNode.attributes['data-string-value'] = gridString;
  2788. }
  2789. }
  2790. }
  2791. }
  2792. }