PHP and Javascript implementations of a simple markdown parser
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

spreadsheet.js 91KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011
  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. * ```
  1370. * ; number
  1371. * ; number 3
  1372. * ; currency 2
  1373. * ; percent 0
  1374. * ```
  1375. *
  1376. * @param {CellExpressionToken[]} tokens
  1377. * @param {number} start
  1378. * @param {number} end
  1379. * @param {CellAddress} address
  1380. * @return {any[]} CellValue type and decimal places
  1381. */
  1382. static #tryFormat(tokens, start, end, address) {
  1383. const count = end - start + 1;
  1384. if (count < 0 || count > 2) return null;
  1385. if (!tokens[start].type.isPotentialName()) return null;
  1386. const type = tokens[start].content.toLowerCase();
  1387. if (!CellValue.isTypeNumeric(type)) return null;
  1388. var decimals;
  1389. if (count > 1) {
  1390. if (tokens[start + 1].type != CellExpressionTokenType.Number) return null;
  1391. decimals = parseInt(tokens[start + 1].content);
  1392. } else {
  1393. decimals = null;
  1394. }
  1395. return [ type, decimals ];
  1396. }
  1397. /**
  1398. * @param {CellExpressionToken[]} tokens
  1399. * @param {number} start
  1400. * @param {number} end
  1401. * @param {CellAddress} address
  1402. * @returns {CellExpression}
  1403. */
  1404. static #tryExpression(tokens, start, end, address) {
  1405. var expr;
  1406. if (expr = this.#tryParenExpression(tokens, start, end, address)) return expr;
  1407. if (expr = this.#tryNumber(tokens, start, end, address)) return expr;
  1408. if (expr = this.#tryString(tokens, start, end, address)) return expr;
  1409. if (expr = this.#tryBoolean(tokens, start, end, address)) return expr;
  1410. if (expr = this.#tryFunction(tokens, start, end, address)) return expr;
  1411. if (expr = this.#tryRange(tokens, start, end, address)) return expr;
  1412. if (expr = this.#tryReference(tokens, start, end, address)) return expr;
  1413. if (expr = this.#tryInfix(tokens, start, end, address)) return expr;
  1414. if (expr = this.#tryUnary(tokens, start, end, address)) return expr;
  1415. throw new CellSyntaxException("Invalid expression");
  1416. }
  1417. /**
  1418. * @param {CellExpressionToken[]} tokens
  1419. * @param {number} start
  1420. * @param {number} end
  1421. * @param {CellAddress} address
  1422. * @returns {CellExpression|null}
  1423. */
  1424. static #tryParenExpression(tokens, start, end, address) {
  1425. if (tokens[start].type != CellExpressionTokenType.OpenParen) return null;
  1426. if (tokens[end].type != CellExpressionTokenType.CloseParen) return null;
  1427. var parenLevel = 0;
  1428. for (var t = start + 1; t < end; t++) {
  1429. if (tokens[t].type == CellExpressionTokenType.OpenParen) {
  1430. parenLevel++;
  1431. } else if (tokens[t].type == CellExpressionTokenType.CloseParen) {
  1432. parenLevel--;
  1433. }
  1434. if (parenLevel < 0) return null;
  1435. }
  1436. if (parenLevel != 0) return null;
  1437. return this.#tryExpression(tokens, start + 1, end - 1, address);
  1438. }
  1439. /**
  1440. * @param {CellExpressionToken[]} tokens
  1441. * @param {number} start
  1442. * @param {number} end
  1443. * @param {CellAddress} address
  1444. * @returns {CellExpression|null}
  1445. */
  1446. static #tryNumber(tokens, start, end, address) {
  1447. if (tokens[end].type != CellExpressionTokenType.Number) return null;
  1448. if (end > start + 1) return null;
  1449. const val = CellValue.fromCellString(tokens[end].content);
  1450. if (end > start) {
  1451. if (tokens[start].type != CellExpressionTokenType.Minus) return null;
  1452. val.value = -val.value;
  1453. }
  1454. return new CellExpression(CellExpressionOperation.Number, [ val ]);
  1455. }
  1456. /**
  1457. * @param {CellExpressionToken[]} tokens
  1458. * @param {number} start
  1459. * @param {number} end
  1460. * @param {CellAddress} address
  1461. * @returns {CellExpression|null}
  1462. */
  1463. static #tryString(tokens, start, end, address) {
  1464. if (start != end) return null;
  1465. if (tokens[start].type != CellExpressionTokenType.String) return null;
  1466. const str = tokens[start].content;
  1467. return new CellExpression(CellExpressionOperation.String, [ new CellValue(str, str, CellValue.TYPE_STRING, 0) ]);
  1468. }
  1469. /**
  1470. * @param {CellExpressionToken[]} tokens
  1471. * @param {number} start
  1472. * @param {number} end
  1473. * @param {CellAddress} address
  1474. * @returns {CellExpression|null}
  1475. */
  1476. static #tryBoolean(tokens, start, end, address) {
  1477. if (start != end) return null;
  1478. if (!tokens[start].type.isPotentialName()) return null;
  1479. const str = tokens[start].content.toUpperCase();
  1480. if (str != 'TRUE' && str != 'FALSE') return null;
  1481. return new CellExpression(CellExpressionOperation.Boolean, [ new CellValue(str, str == 'TRUE', CellValue.TYPE_BOOLEAN) ]);
  1482. }
  1483. /**
  1484. * @param {CellExpressionToken[]} tokens
  1485. * @param {number} start
  1486. * @param {number} end
  1487. * @param {CellAddress} address
  1488. * @returns {CellExpression|null}
  1489. */
  1490. static #tryFunction(tokens, start, end, address) {
  1491. const count = end - start + 1;
  1492. if (count < 3) return null;
  1493. if (!tokens[start].type.isPotentialName()) return null;
  1494. const qualifier = tokens[start].content;
  1495. if (tokens[start + 1].type != CellExpressionTokenType.OpenParen) return null;
  1496. if (tokens[end].type != CellExpressionTokenType.CloseParen) return null;
  1497. const argList = this.#tryArgumentList(tokens, start + 2, end - 1, address);
  1498. if (argList === null) return null;
  1499. return new CellExpression(CellExpressionOperation.Function, argList, qualifier);
  1500. }
  1501. /**
  1502. * @param {CellExpressionToken[]} tokens
  1503. * @param {number} start
  1504. * @param {number} end
  1505. * @param {CellAddress} address
  1506. * @returns {CellExpression[]|null}
  1507. */
  1508. static #tryArgumentList(tokens, start, end, address) {
  1509. const count = end - start + 1;
  1510. if (count == 0) return [];
  1511. var parenDepth = 0;
  1512. const argCount = 1;
  1513. // Populate argTokens with tuples of start and end token indices for each arg.
  1514. /** @type {int[][]} */
  1515. var argTokens = []; // argindex -> [ start, end ]
  1516. var exprStartToken = start;
  1517. for (var i = start; i <= end; i++) {
  1518. if (tokens[i].type == CellExpressionTokenType.OpenParen) {
  1519. parenDepth++;
  1520. } else if (tokens[i].type == CellExpressionTokenType.CloseParen) {
  1521. parenDepth--;
  1522. } else if (tokens[i].type == CellExpressionTokenType.Comma && parenDepth == 0) {
  1523. const exprEndToken = i - 1;
  1524. argTokens.push([ exprStartToken, exprEndToken ]);
  1525. exprStartToken = i + 1;
  1526. }
  1527. }
  1528. argTokens.push([ exprStartToken, end ]);
  1529. // Convert token ranges to expressions
  1530. var args = [];
  1531. for (const argToken of argTokens) {
  1532. const arg = this.#tryExpression(tokens, argToken[0], argToken[1], address);
  1533. if (arg === null) return null;
  1534. args.push(arg);
  1535. }
  1536. return args;
  1537. }
  1538. /**
  1539. * @param {CellExpressionToken[]} tokens
  1540. * @param {number} start
  1541. * @param {number} end
  1542. * @param {CellAddress} address
  1543. * @returns {CellExpression|null}
  1544. */
  1545. static #tryRange(tokens, start, end, address) {
  1546. const count = end - start + 1;
  1547. if (count != 3) return null;
  1548. if (!tokens[start].type.isPotentialAddress()) return null;
  1549. const first = tokens[start].content.toUpperCase();
  1550. if (tokens[start + 1].type != CellExpressionTokenType.Colon) return null;
  1551. if (!tokens[end].type.isPotentialAddress()) return null;
  1552. const last = tokens[end].content.toUpperCase();
  1553. const firstAddress = CellAddress.fromString(first);
  1554. const lastAddress = CellAddress.fromString(last);
  1555. const range = new CellAddressRange(firstAddress, lastAddress);
  1556. return new CellExpression(CellExpressionOperation.Range, [ range ]);
  1557. }
  1558. /**
  1559. * @param {CellExpressionToken[]} tokens
  1560. * @param {number} start
  1561. * @param {number} end
  1562. * @param {CellAddress} address
  1563. * @returns {CellExpression|null}
  1564. */
  1565. static #tryReference(tokens, start, end, address) {
  1566. if (start != end) return null;
  1567. if (!tokens[start].type.isPotentialAddress()) return null;
  1568. const ref = tokens[start].content.toUpperCase();
  1569. const refAddress = CellAddress.fromString(ref, address, true);
  1570. return new CellExpression(CellExpressionOperation.Reference, [ refAddress ]);
  1571. }
  1572. static #infixPriority = {};
  1573. static {
  1574. this.#infixPriority[CellExpressionTokenType.Minus.name] = 1;
  1575. this.#infixPriority[CellExpressionTokenType.Plus.name] = 2;
  1576. this.#infixPriority[CellExpressionTokenType.Divide.name] = 3;
  1577. this.#infixPriority[CellExpressionTokenType.Multiply.name] = 4;
  1578. this.#infixPriority[CellExpressionTokenType.Ampersand.name] = 10;
  1579. this.#infixPriority[CellExpressionTokenType.GreaterThan.name] = 20;
  1580. this.#infixPriority[CellExpressionTokenType.GreaterThanEqual.name] = 20;
  1581. this.#infixPriority[CellExpressionTokenType.LessThan.name] = 20;
  1582. this.#infixPriority[CellExpressionTokenType.LessThanEqual.name] = 20;
  1583. this.#infixPriority[CellExpressionTokenType.Equal.name] = 20;
  1584. this.#infixPriority[CellExpressionTokenType.Unequal.name] = 20;
  1585. }
  1586. /**
  1587. * @param {CellExpressionToken[]} tokens
  1588. * @param {number} start
  1589. * @param {number} end
  1590. * @param {CellAddress} address
  1591. * @returns {CellExpression|null}
  1592. */
  1593. static #tryInfix(tokens, start, end, address) {
  1594. const count = end - start + 1;
  1595. if (count < 3) return null;
  1596. var candidates = [];
  1597. var parenLevel = 0;
  1598. var i;
  1599. for (i = start; i <= end; i++) {
  1600. if (tokens[i].type == CellExpressionTokenType.OpenParen) {
  1601. parenLevel++;
  1602. } else if (tokens[i].type == CellExpressionTokenType.CloseParen) {
  1603. parenLevel--;
  1604. } else if (parenLevel == 0 && i > start && i < end) {
  1605. const op = tokens[i].type.name;
  1606. const priority = this.#infixPriority[op] ?? false;
  1607. if (priority === false) continue;
  1608. candidates.push({ priority: priority, i: i });
  1609. }
  1610. }
  1611. candidates.sort((a, b) => a.priority - b.priority);
  1612. var bestCandidate = null;
  1613. var operand1, operand2;
  1614. for (const candidate of candidates) {
  1615. try {
  1616. i = candidate.i;
  1617. operand1 = this.#tryExpression(tokens, start, i - 1, address);
  1618. if (operand1 === null) continue;
  1619. operand2 = this.#tryExpression(tokens, i + 1, end, address);
  1620. if (operand2 === null) continue;
  1621. bestCandidate = candidate;
  1622. break;
  1623. } catch (e) {
  1624. if (!(e instanceof CellSyntaxException)) {
  1625. throw e;
  1626. }
  1627. }
  1628. }
  1629. if (bestCandidate === null) {
  1630. return null;
  1631. }
  1632. i = bestCandidate.i;
  1633. switch (tokens[bestCandidate.i].type) {
  1634. case CellExpressionTokenType.Plus:
  1635. return new CellExpression(CellExpressionOperation.Add, [ operand1, operand2 ]);
  1636. case CellExpressionTokenType.Minus:
  1637. return new CellExpression(CellExpressionOperation.Subtract, [ operand1, operand2 ]);
  1638. case CellExpressionTokenType.Multiply:
  1639. return new CellExpression(CellExpressionOperation.Multiply, [ operand1, operand2 ]);
  1640. case CellExpressionTokenType.Divide:
  1641. return new CellExpression(CellExpressionOperation.Divide, [ operand1, operand2 ]);
  1642. case CellExpressionTokenType.GreaterThan:
  1643. return new CellExpression(CellExpressionOperation.GreaterThan, [ operand1, operand2 ]);
  1644. case CellExpressionTokenType.GreaterThanEqual:
  1645. return new CellExpression(CellExpressionOperation.GreaterThanEqual, [ operand1, operand2 ]);
  1646. case CellExpressionTokenType.LessThan:
  1647. return new CellExpression(CellExpressionOperation.LessThan, [ operand1, operand2 ]);
  1648. case CellExpressionTokenType.LessThanEqual:
  1649. return new CellExpression(CellExpressionOperation.LessThanEqual, [ operand1, operand2 ]);
  1650. case CellExpressionTokenType.Equal:
  1651. return new CellExpression(CellExpressionOperation.Equal, [ operand1, operand2 ]);
  1652. case CellExpressionTokenType.Unequal:
  1653. return new CellExpression(CellExpressionOperation.Unequal, [ operand1, operand2 ]);
  1654. case CellExpressionTokenType.Ampersand:
  1655. return new CellExpression(CellExpressionOperation.Concatenate, [ operand1, operand2 ]);
  1656. }
  1657. return null;
  1658. }
  1659. /**
  1660. * @param {CellExpressionToken[]} tokens
  1661. * @param {number} start
  1662. * @param {number} end
  1663. * @param {CellAddress} address
  1664. * @returns {CellExpression|null}
  1665. */
  1666. static #tryUnary(tokens, start, end, address) {
  1667. const count = end - start + 1;
  1668. if (count < 2) return null;
  1669. const ops = [
  1670. [ CellExpressionTokenType.Minus, CellExpressionOperation.UnaryMinus ],
  1671. [ CellExpressionTokenType.Not, CellExpressionOperation.UnaryNot ],
  1672. ];
  1673. for (const op of ops) {
  1674. if (tokens[start].type != op[0]) continue;
  1675. const operand = this.#tryExpression(tokens, start + 1, end, address);
  1676. if (operand === null) return null;
  1677. return new CellExpression(op[1], [ operand ]);
  1678. }
  1679. return null;
  1680. }
  1681. }
  1682. /**
  1683. * Parsing token for an expression.
  1684. */
  1685. class CellExpressionToken {
  1686. /** @type {CellExpressionTokenType} */
  1687. type;
  1688. /** @type {string} */
  1689. content;
  1690. /**
  1691. * @param {CellExpressionTokenType} type
  1692. * @param {string} content
  1693. */
  1694. constructor(type, content) {
  1695. this.type = type;
  1696. this.content = content;
  1697. }
  1698. }
  1699. /**
  1700. * The location of a cell in a table. If the address was specified without a
  1701. * row, the address is considered "unresolved" and needs more context to
  1702. * uniquely identify a cell.
  1703. */
  1704. class CellAddress {
  1705. /**
  1706. * @type {string}
  1707. */
  1708. get name() { return this.#name; }
  1709. #name;
  1710. /**
  1711. * Whether the column should remain unchanged when transposed. This is
  1712. * symbolized by prefixing the column name with a `$` (e.g. `$C3`).
  1713. * @type {boolean}
  1714. */
  1715. get isColumnFixed() { return this.#isColumnFixed; }
  1716. #isColumnFixed = false;
  1717. /**
  1718. * Zero-based column index.
  1719. * @type {number}
  1720. */
  1721. get columnIndex() { return this.#columnIndex; };
  1722. #columnIndex = -1;
  1723. /**
  1724. * Letter code for the column.
  1725. * @type {string}
  1726. */
  1727. get columnLetter() { return CellAddress.#columnIndexToLetters(this.#columnIndex); }
  1728. /**
  1729. * Whether the row should remain unchanged when transposed. This is
  1730. * symbolized by prefixing the row number with a `$` (e.g. `C$3`).
  1731. * @type {boolean}
  1732. */
  1733. get isRowFixed() { return this.#isRowFixed; }
  1734. #isRowFixed = false;
  1735. /**
  1736. * Zero-based row index.
  1737. * @type {number}
  1738. */
  1739. get rowIndex() { return this.#rowIndex; }
  1740. #rowIndex = -1;
  1741. /**
  1742. * One-based row number. This is the human-facing row number.
  1743. */
  1744. get rowNumber() { return this.#rowIndex + 1; }
  1745. /**
  1746. * Whether this address has both a definite column and row.
  1747. * @type {boolean}
  1748. */
  1749. get isResolved() { return this.columnIndex >= 0 && this.rowIndex >= 0; }
  1750. /**
  1751. * @param {number} columnIndex - 0-based column index
  1752. * @param {number} rowIndex - 0-based row index
  1753. * @param {boolean} isColumnFixed - whether the column name is fixed in
  1754. * place during transpositions. Denoted with a `$` in front of the column letters.
  1755. * @param {boolean} isRowFixed - whether the row number is fixed in place
  1756. * during transpositions. Denoted with a `$` in front of the row digits.
  1757. */
  1758. constructor(columnIndex, rowIndex, isColumnFixed=false, isRowFixed=false) {
  1759. if (typeof columnIndex != 'number') {
  1760. throw new Error(`columnIndex must be number, got ${typeof columnIndex}`);
  1761. }
  1762. if (typeof rowIndex != 'number') {
  1763. throw new Error(`rowIndex must be number, got ${typeof rowIndex}`);
  1764. }
  1765. this.#columnIndex = columnIndex;
  1766. this.#rowIndex = rowIndex;
  1767. this.#isColumnFixed = isColumnFixed;
  1768. this.#isRowFixed = isRowFixed;
  1769. this.#name = CellAddress.#formatAddress(columnIndex, rowIndex, isColumnFixed, isRowFixed);
  1770. }
  1771. /**
  1772. * Tests if a string is formatted like an address.
  1773. *
  1774. * @param {string} text
  1775. * @returns {boolean}
  1776. */
  1777. static isAddress(text) {
  1778. return this.fromString(text) != null;
  1779. }
  1780. /**
  1781. * Returns a converted form of this address reference in a formula that has
  1782. * been copied from its original location. In other words, if a formula
  1783. * refers to a cell one to the left and that formula is copied to the next
  1784. * cell down, that copy's reference should point to the cell on the next
  1785. * row as well. Addresses with an absolute column or row (e.g. "A5") will
  1786. * not be altered on that axis.
  1787. *
  1788. * Examples:
  1789. * - C6.transpose(A5, A9) = C10 (A9-A5 = +4 rows, C6 + 4 rows = C10)
  1790. * - C6.transpose(A5, B9) = D10 (B9-A5 = +4 rows +1 cols, C6 + 4 rows + 1
  1791. * col = D10)
  1792. * - C$6.transpose(A5, A9) = C6 (A9-A5 = +4 rows, but row is fixed, so
  1793. * still C6)
  1794. * - B.transpose(A5, A9) = B9 (A9-A4 = +4 rows, B has no row so last row
  1795. * used = B9)
  1796. * - A1.transpose(C3, A1) = null (out of bounds)
  1797. *
  1798. * @param {CellAddress} relativeFrom - original address of the formula
  1799. * @param {CellAddress} relativeTo - address where the formula is being
  1800. * repeated
  1801. * @param {boolean} resolveToRow - whether to fill in a row number if this
  1802. * address doesn't have one
  1803. * @returns {CellAddress|null} - resolved address, or `null` if out of bounds
  1804. */
  1805. transpose(relativeFrom, relativeTo, resolveToRow = true) {
  1806. if (!relativeFrom.isResolved || !relativeTo.isResolved) {
  1807. throw new CellEvaluationException("Can only transpose to and from resolved addresses");
  1808. }
  1809. var newColumnIndex = this.columnIndex;
  1810. if (!this.isColumnFixed) {
  1811. const columnDelta = relativeTo.columnIndex - relativeFrom.columnIndex;
  1812. newColumnIndex += columnDelta;
  1813. }
  1814. var newRowIndex = this.rowIndex;
  1815. if (!this.isResolved && resolveToRow) {
  1816. newRowIndex = relativeFrom.rowIndex;
  1817. }
  1818. if (newRowIndex != -1 && !this.isRowAbsolute) {
  1819. const rowDelta = relativeTo.rowIndex - relativeFrom.rowIndex;
  1820. newRowIndex += rowDelta;
  1821. }
  1822. if (newColumnIndex < 0 || newRowIndex < 0) return null;
  1823. return new CellAddress(newColumnIndex, newRowIndex);
  1824. }
  1825. equals(other) {
  1826. if (!(other instanceof CellAddress)) return false;
  1827. return other.columnIndex == this.columnIndex && other.rowIndex == this.rowIndex;
  1828. }
  1829. exactlyEquals(other) {
  1830. if (!(other instanceof CellAddress)) return false;
  1831. return other.name == this.name;
  1832. }
  1833. toString() {
  1834. return this.name;
  1835. }
  1836. /**
  1837. * Converts column letters (e.g. `A`, `C`, `AA`) to a 0-based column index.
  1838. * Assumes a validated well-formed column letter or else behavior is undefined.
  1839. *
  1840. * @param {string} letters
  1841. * @returns {number} column index
  1842. */
  1843. static #lettersToColumnIndex(letters) {
  1844. const ACodepoint = 'A'.codePointAt(0);
  1845. var columnIndex = 0;
  1846. for (var i = letters.length - 1; i >= 0; i--) {
  1847. const letterIndex = letters.codePointAt(i) - ACodepoint;
  1848. columnIndex = columnIndex * 26 + letterIndex;
  1849. }
  1850. return columnIndex;
  1851. }
  1852. /**
  1853. * Converts a column index to column letters (e.g. index 0 = `A`).
  1854. *
  1855. * @param {number} columnIndex
  1856. * @returns {string}
  1857. */
  1858. static #columnIndexToLetters(columnIndex) {
  1859. var letters = '';
  1860. if (columnIndex >= 0) {
  1861. const ACodepoint = 'A'.codePointAt(0);
  1862. var remaining = columnIndex;
  1863. do {
  1864. letters = String.fromCodePoint(ACodepoint + (remaining % 26)) + letters;
  1865. remaining = Math.floor(remaining / 26);
  1866. } while (remaining > 0);
  1867. }
  1868. return letters;
  1869. }
  1870. static #formatAddress(columnIndex, rowIndex, isColumnFixed, isRowFixed) {
  1871. var addr = '';
  1872. if (isColumnFixed && columnIndex >= 0) addr += '$';
  1873. if (columnIndex >= 0) addr += this.#columnIndexToLetters(columnIndex);
  1874. if (isRowFixed && rowIndex >= 0) addr += '$';
  1875. if (rowIndex >= 0) addr += `${rowIndex + 1}`;
  1876. return addr;
  1877. }
  1878. /**
  1879. * Attempts to convert a cell address string to a `CellAddress`.
  1880. *
  1881. * @param {string} address - cell address string
  1882. * @param {CellAddress|null} relativeTo - address to resolve relative
  1883. * addresses against
  1884. * @param {boolean} throwIfInvalid - whether to throw an error if address
  1885. * is invalid
  1886. * @returns {CellAddress|null} address, if parsable
  1887. * @throws {CellEvaluationException} if the address is invalid and
  1888. * `throwIfInvalid` is `true`
  1889. */
  1890. static fromString(address, relativeTo=null, throwIfInvalid=false) {
  1891. const groups = /^(\$?)([A-Z]{1,2}?)((?:\$(?=[0-9]))?)([0-9]*)$/i.exec(address);
  1892. if (groups === null) {
  1893. if (throwIfInvalid) throw new CellEvaluationException(`Bad address "${address}"`, '#REF');
  1894. return null;
  1895. }
  1896. const isColumnFixed = groups[1] == '$';
  1897. const letters = groups[2].toUpperCase();
  1898. const isRowFixed = groups[3] == '$';
  1899. const numbers = groups[4];
  1900. var columnIndex = this.#lettersToColumnIndex(letters);
  1901. var rowIndex = (numbers.length == 0) ? -1 : parseInt(numbers) - 1;
  1902. if (columnIndex < 0 && relativeTo != null) columnIndex = relativeTo.columnIndex;
  1903. if (rowIndex < 0 && relativeTo != null) rowIndex = relativeTo.rowIndex;
  1904. return new CellAddress(columnIndex, rowIndex, isColumnFixed, isRowFixed);
  1905. }
  1906. }
  1907. /**
  1908. * Range of cells addresses. Can be iterated via `cellsIn`.
  1909. */
  1910. class CellAddressRange {
  1911. /** @type {boolean} */
  1912. isResolved;
  1913. /** @type {number} */
  1914. minColumnIndex;
  1915. /** @type {number} */
  1916. maxColumnIndex;
  1917. /** @type {number} */
  1918. minRowIndex;
  1919. /** @type {number} */
  1920. maxRowIndex;
  1921. /** @type {string} */
  1922. name;
  1923. /**
  1924. * Creates a rectangular range between two corner cells. They can be in
  1925. * any order. The given cells must either both be resolved or both unresolved.
  1926. *
  1927. * @param {CellAddress} fromCell
  1928. * @param {CellAddress} toCell
  1929. */
  1930. constructor(fromCell, toCell) {
  1931. if (fromCell.isResolved != toCell.isResolved) {
  1932. throw new CellEvaluationException(`Cannot mix resolved and unresolved cell addresses in range: ${fromCell.name} and ${toCell.name}`);
  1933. }
  1934. this.minColumnIndex = Math.min(fromCell.columnIndex, toCell.columnIndex);
  1935. this.maxColumnIndex = Math.max(fromCell.columnIndex, toCell.columnIndex);
  1936. this.minRowIndex = Math.min(fromCell.rowIndex, toCell.rowIndex);
  1937. this.maxRowIndex = Math.max(fromCell.rowIndex, toCell.rowIndex);
  1938. this.isResolved = fromCell.isResolved;
  1939. this.name = (new CellAddress(this.minColumnIndex, this.minRowIndex)).name +
  1940. ':' +
  1941. (new CellAddress(this.maxColumnIndex, this.maxRowIndex)).name;
  1942. }
  1943. /**
  1944. * Creates an iterator for every `CellAddress` in this range within the
  1945. * confines of the given grid's dimensions. Iterates each row in the first
  1946. * column, then each row in the second, etc. Iteration range is inclusive
  1947. * of the min and max extents.
  1948. *
  1949. * Example:
  1950. * ```
  1951. * for (const address of range.cellsIn(grid)) {
  1952. * ...
  1953. * }
  1954. * ```
  1955. *
  1956. * @param {SpreadsheetGrid} grid
  1957. * @returns {object} iterable object
  1958. */
  1959. cellsIn(grid) {
  1960. const minCol = this.minColumnIndex < 0 ? 0 : this.minColumnIndex;
  1961. const maxCol = this.maxColumnIndex < 0 ? grid.columnCount - 1
  1962. : Math.min(this.maxColumnIndex, grid.columnCount - 1);
  1963. const minRow = this.minRowIndex < 0 ? 0 : this.minRowIndex;
  1964. const maxRow = this.maxRowIndex < 0 ? grid.rowCount - 1
  1965. : Math.min(this.maxRowIndex, grid.rowCount - 1);
  1966. const iterable = {};
  1967. iterable[Symbol.iterator] = function() {
  1968. var currentCol = minCol;
  1969. var currentRow = minRow;
  1970. return {
  1971. next() {
  1972. const col = currentCol;
  1973. const row = currentRow++;
  1974. if (currentRow > maxRow) {
  1975. currentRow = minRow;
  1976. currentCol++;
  1977. }
  1978. return {
  1979. value: new CellAddress(col, row),
  1980. done: col > maxCol || row > maxRow,
  1981. };
  1982. }
  1983. };
  1984. };
  1985. return iterable;
  1986. }
  1987. }
  1988. /**
  1989. * A value in a spreadsheet or calculation.
  1990. */
  1991. class CellValue {
  1992. /**
  1993. * Blank cell. `value` is `null`.
  1994. */
  1995. static TYPE_BLANK = 'blank';
  1996. /**
  1997. * Currency value. `value` is `number`.
  1998. */
  1999. static TYPE_CURRENCY = 'currency';
  2000. /**
  2001. * Regular number value. `value` is `number`.
  2002. */
  2003. static TYPE_NUMBER = 'number';
  2004. /**
  2005. * Percentage. `value` is `number`, represented as a ratio (100% = 1.0).
  2006. */
  2007. static TYPE_PERCENT = 'percent';
  2008. /**
  2009. * Unaltered text value. `value` is `string`.
  2010. */
  2011. static TYPE_STRING = 'string';
  2012. /**
  2013. * Boolean. `value` is `boolean`.
  2014. */
  2015. static TYPE_BOOLEAN = 'boolean';
  2016. /**
  2017. * A formula that has resulted in an error during parsing or evaluation.
  2018. * `value` is `string` error message.
  2019. */
  2020. static TYPE_ERROR = 'error';
  2021. /**
  2022. * A formula expression. `value` is `string` and includes the leading `=`.
  2023. */
  2024. static TYPE_FORMULA = 'formula';
  2025. // -- Properties -----
  2026. /**
  2027. * A blank value.
  2028. * @type {CellValue}
  2029. */
  2030. static BLANK = new CellValue('', null, CellValue.TYPE_BLANK);
  2031. /**
  2032. * Type of value. One of the `TYPE_` constants.
  2033. * @type {string}
  2034. */
  2035. type = CellValue.TYPE_STRING;
  2036. /**
  2037. * Number of decimal places shown in the formatted value.
  2038. * @type {number}
  2039. */
  2040. decimals = 0;
  2041. /**
  2042. * The string shown in the table cell to the user.
  2043. * @type {string}
  2044. */
  2045. formattedValue = '';
  2046. /**
  2047. * The PHP data value. E.g. a `float` for currency values or an `Exception`
  2048. * for errors.
  2049. * @type {any}
  2050. */
  2051. value = null;
  2052. /**
  2053. * Constructs a cell value explicitly. Values are not validated. Consider
  2054. * using `.fromCellString()` or `.fromValue()` to populate values more
  2055. * intelligently and consistently.
  2056. *
  2057. * @param {string} formattedValue
  2058. * @param {any} value
  2059. * @param {string} type
  2060. * @param {number} decimals
  2061. */
  2062. constructor(
  2063. formattedValue,
  2064. value = null,
  2065. type = CellValue.TYPE_STRING,
  2066. decimals = 0
  2067. ) {
  2068. this.formattedValue = formattedValue;
  2069. this.value = value;
  2070. this.type = type;
  2071. this.decimals = decimals;
  2072. }
  2073. /**
  2074. * Returns whether this value is a numeric type.
  2075. *
  2076. * @returns {boolean}
  2077. */
  2078. isNumeric() {
  2079. return CellValue.isTypeNumeric(this.type);
  2080. }
  2081. /**
  2082. * Creates a CellValue from formatted table cell contents. Attempts to
  2083. * detect formatted numbers including currency and percentages.
  2084. *
  2085. * @param {string} cellString
  2086. * @returns {CellValue}
  2087. */
  2088. static fromCellString(cellString) {
  2089. const cv = new CellValue(cellString);
  2090. cv.#populateFromCellString(cellString);
  2091. return cv;
  2092. }
  2093. /**
  2094. * Creates a CellValue from a value. Based off datatype, not string
  2095. * formatting; use `fromCellString` to parse formatted numbers.
  2096. *
  2097. * @param {any} value
  2098. * @param {string|null} type - optional forced type
  2099. * @param {number|null} decimals - optional number of decimal places to format to
  2100. * @returns {CellValue}
  2101. * @throws {CellEvaluationException} if `value` is of an unsupported type
  2102. */
  2103. static fromValue(value, type = null, decimals = null) {
  2104. if (value === null) {
  2105. return new CellValue('', null, CellValue.TYPE_BLANK);
  2106. }
  2107. if (value instanceof Error) {
  2108. if (value instanceof CellException) {
  2109. return new CellValue(value.errorSymbol, value.message, CellValue.TYPE_ERROR);
  2110. }
  2111. return new CellValue('#ERROR', value.message, CellValue.TYPE_ERROR);
  2112. }
  2113. if (typeof value == 'boolean') {
  2114. const formatted = CellValue.formatType(value, CellValue.TYPE_BOOLEAN, 0);
  2115. return new CellValue(formatted, value, CellValue.TYPE_BOOLEAN);
  2116. }
  2117. if (typeof value == 'number') {
  2118. const resolvedType = type || CellValue.TYPE_NUMBER;
  2119. const resolvedDecimals = (decimals !== null) ? decimals :
  2120. (resolvedType == CellValue.TYPE_CURRENCY ? 2 : CellValue.#autodecimals(resolvedType == CellValue.TYPE_PERCENT ? value * 100.0 : value));
  2121. const formatted = CellValue.formatType(value, resolvedType, resolvedDecimals);
  2122. return new CellValue(formatted, value, resolvedType, resolvedDecimals);
  2123. }
  2124. if (typeof value != 'string') {
  2125. throw new CellEvaluationException(`Value of type ${typeof value} unsupported`);
  2126. }
  2127. const trimmed = value.trim();
  2128. if (trimmed.startsWith('=')) {
  2129. return new CellValue(trimmed, trimmed, CellValue.TYPE_FORMULA);
  2130. }
  2131. return new CellValue(trimmed, trimmed, CellValue.TYPE_STRING);
  2132. }
  2133. /**
  2134. * @param {string|null} cellString
  2135. */
  2136. #populateFromCellString(cellString) {
  2137. cellString = (cellString !== null) ? cellString.trim() : null;
  2138. this.formattedValue = cellString;
  2139. // blank
  2140. if (cellString === null || cellString == '') {
  2141. this.type = CellValue.TYPE_BLANK;
  2142. this.value = null;
  2143. return;
  2144. }
  2145. // 'literal
  2146. if (cellString.startsWith("'")) {
  2147. const stripped = cellString.substring(1).trim();
  2148. this.type = CellValue.TYPE_STRING;
  2149. this.formattedValue = stripped;
  2150. this.value = stripped;
  2151. return;
  2152. }
  2153. // =TRUE
  2154. const caps = cellString.toUpperCase();
  2155. if (caps == 'TRUE') {
  2156. this.type = CellValue.TYPE_BOOLEAN;
  2157. this.formattedValue = caps;
  2158. this.value = true;
  2159. this.formattedValue = 'TRUE';
  2160. return;
  2161. }
  2162. // =FALSE
  2163. if (caps == 'FALSE') {
  2164. this.type = CellValue.TYPE_BOOLEAN;
  2165. this.formattedValue = caps;
  2166. this.value = false;
  2167. this.formattedValue = 'FALSE';
  2168. return;
  2169. }
  2170. // =A*B
  2171. if (cellString.startsWith('=')) {
  2172. this.type = CellValue.TYPE_FORMULA;
  2173. this.value = cellString;
  2174. return;
  2175. }
  2176. // -$1,234.56
  2177. var groups;
  2178. if (groups = /^([-]?)\$(-?[0-9,]*\.)([0-9]+)$/.exec(cellString)) {
  2179. const sign = groups[1];
  2180. const dollars = groups[2].replace(/,/g, '');
  2181. const cents = groups[3];
  2182. this.type = CellValue.TYPE_CURRENCY;
  2183. this.decimals = 2;
  2184. this.value = parseFloat(sign + dollars + cents);
  2185. this.formattedValue = CellValue.#formatCurrency(this.value, this.decimals);
  2186. return;
  2187. }
  2188. // -$1,234
  2189. if (groups = /^([-]?)\$(-?[0-9,]+)$/.exec(cellString)) {
  2190. const sign = groups[1];
  2191. const dollars = groups[2].replace(/,/g, '');
  2192. this.type = CellValue.TYPE_CURRENCY;
  2193. this.decimals = 0;
  2194. this.value = parseFloat(sign + dollars);
  2195. this.formattedValue = CellValue.#formatCurrency(this.value, this.decimals);
  2196. return;
  2197. }
  2198. // -1,234.56%
  2199. if (groups = /^([-]?[0-9,]*\.)([0-9,]+)%$/.exec(cellString)) {
  2200. const wholes = groups[1].replace(/,/, '');
  2201. const decimals = groups[2];
  2202. this.type = CellValue.TYPE_PERCENT;
  2203. this.decimals = decimals.length;
  2204. this.value = parseFloat(wholes + decimals) / 100.0;
  2205. this.formattedValue = CellValue.#formatPercent(this.value, this.decimals);
  2206. return;
  2207. }
  2208. // -1,234%
  2209. if (groups = /^([-]?[0-9,]+)%$/.exec(cellString)) {
  2210. const wholes = groups[1].replace(/,/g, '');
  2211. this.type = CellValue.TYPE_PERCENT;
  2212. this.decimals = 0;
  2213. this.value = parseFloat(wholes) / 100.0;
  2214. this.formattedValue = CellValue.#formatPercent(this.value, this.decimals);
  2215. return;
  2216. }
  2217. // -1,234.56
  2218. if (groups = /^([-]?[0-9,]*\.)([0-9]+)$/.exec(cellString)) {
  2219. const wholes = groups[1].replace(/,/g, '');
  2220. const decimals = groups[2];
  2221. this.type = CellValue.TYPE_NUMBER;
  2222. this.decimals = decimals.length;
  2223. this.value = parseFloat(wholes + decimals);
  2224. this.formattedValue = CellValue.#formatNumber(this.value, this.decimals);
  2225. return;
  2226. }
  2227. // -1,234
  2228. if (groups = /^([-]?[0-9,]+)$/.exec(cellString)) {
  2229. const wholes = groups[1].replace(/,/g, '');
  2230. this.type = CellValue.TYPE_NUMBER;
  2231. this.decimals = 0;
  2232. this.value = parseFloat(wholes);
  2233. this.formattedValue = CellValue.#formatNumber(this.value, this.decimals);
  2234. return;
  2235. }
  2236. this.type = CellValue.TYPE_STRING;
  2237. this.value = cellString;
  2238. }
  2239. /**
  2240. * Returns the boolean equivalent of this value if possible.
  2241. *
  2242. * @returns {boolean|null}
  2243. */
  2244. booleanValue() {
  2245. switch (this.type) {
  2246. case CellValue.TYPE_BLANK:
  2247. return false;
  2248. case CellValue.TYPE_BOOLEAN:
  2249. return this.value;
  2250. case CellValue.TYPE_CURRENCY:
  2251. case CellValue.TYPE_NUMBER:
  2252. case CellValue.TYPE_PERCENT:
  2253. return this.value != 0;
  2254. case CellValue.TYPE_ERROR:
  2255. case CellValue.TYPE_FORMULA:
  2256. case CellValue.TYPE_STRING:
  2257. return null;
  2258. }
  2259. }
  2260. /**
  2261. * Returns the numeric value of this value if possible.
  2262. *
  2263. * @returns {number|null}
  2264. */
  2265. numericValue() {
  2266. switch (this.type) {
  2267. case CellValue.TYPE_BLANK:
  2268. return 0.0;
  2269. case CellValue.TYPE_BOOLEAN:
  2270. return this.value ? 1.0 : 0.0;
  2271. case CellValue.TYPE_CURRENCY:
  2272. case CellValue.TYPE_NUMBER:
  2273. case CellValue.TYPE_PERCENT:
  2274. return this.value;
  2275. case CellValue.TYPE_ERROR:
  2276. case CellValue.TYPE_FORMULA:
  2277. case CellValue.TYPE_STRING:
  2278. return null;
  2279. }
  2280. }
  2281. /**
  2282. * Returns the string value of this value if possible.
  2283. *
  2284. * @param {boolean} formatted
  2285. * @returns {string|null}
  2286. */
  2287. stringValue(formatted = false) {
  2288. switch (this.type) {
  2289. case CellValue.TYPE_BLANK:
  2290. return '';
  2291. case CellValue.TYPE_BOOLEAN:
  2292. return this.value ? 'TRUE' : 'FALSE';
  2293. case CellValue.TYPE_CURRENCY:
  2294. case CellValue.TYPE_NUMBER:
  2295. case CellValue.TYPE_PERCENT:
  2296. return formatted ? this.formattedValue : `${this.value}`;
  2297. case CellValue.TYPE_STRING:
  2298. return formatted ? this.formattedValue : this.value;
  2299. case CellValue.TYPE_ERROR:
  2300. case CellValue.TYPE_FORMULA:
  2301. return null;
  2302. }
  2303. }
  2304. // -- Operations --------------------------------------------------------
  2305. /**
  2306. * Returns the result of this value plus `b`.
  2307. *
  2308. * @param {CellValue} b
  2309. * @returns {CellValue} sum
  2310. */
  2311. add(b) {
  2312. return CellValue.#binaryNumericOperation(this, b, '+',
  2313. (aVal, bVal) => aVal + bVal);
  2314. }
  2315. /**
  2316. * Returns the result of this value minus `b`.
  2317. *
  2318. * @param {CellValue} b
  2319. * @returns {CellValue} difference
  2320. */
  2321. subtract(b) {
  2322. return CellValue.#binaryNumericOperation(this, b, '-',
  2323. (aVal, bVal) => aVal - bVal);
  2324. }
  2325. /**
  2326. * Returns the result of this value multiplied by `b`.
  2327. *
  2328. * @param {CellValue} b
  2329. * @returns {CellValue} product
  2330. */
  2331. multiply(b) {
  2332. return CellValue.#binaryNumericOperation(this, b, '*',
  2333. (aVal, bVal) => aVal * bVal);
  2334. }
  2335. /**
  2336. * Returns the result of this value divided by `b`.
  2337. *
  2338. * @param {CellValue} b
  2339. * @returns {CellValue} quotient
  2340. * @throws {CellEvaluationException} on divide by zero
  2341. */
  2342. divide(b) {
  2343. return CellValue.#binaryNumericOperation(this, b, '/', (aVal, bVal) => {
  2344. if (bVal == 0) throw new CellEvaluationException("Division by zero", '#NAN');
  2345. return aVal / bVal
  2346. });
  2347. }
  2348. /**
  2349. * Returns the result of this value modulo by `b`.
  2350. *
  2351. * @param {CellValue} b
  2352. * @returns {CellValue} remainder
  2353. * @throws {CellEvaluationException} on divide by zero
  2354. */
  2355. modulo(b) {
  2356. return CellValue.#binaryNumericOperation(this, b, '%', (aVal, bVal) => {
  2357. if (bVal == 0) throw new CellEvaluationException("Division by zero", '#NAN');
  2358. return aVal % bVal
  2359. });
  2360. }
  2361. /**
  2362. * Returns the result of whether this value is greater than `b`.
  2363. *
  2364. * @param {CellValue} b
  2365. * @returns {CellValue}
  2366. */
  2367. gt(b) {
  2368. return CellValue.fromValue(CellValue.#compare(this, b) > 0);
  2369. }
  2370. /**
  2371. * Returns the result of whether tihs value is greater than or equal to `b`.
  2372. *
  2373. * @param {CellValue} b
  2374. * @returns {CellValue}
  2375. */
  2376. gte(b) {
  2377. return CellValue.fromValue(CellValue.#compare(this, b) >= 0);
  2378. }
  2379. /**
  2380. * Returns the result of whether this value is less than `b`.
  2381. *
  2382. * @param {CellValue} b
  2383. * @returns {CellValue}
  2384. */
  2385. lt(b) {
  2386. return CellValue.fromValue(CellValue.#compare(this, b) < 0);
  2387. }
  2388. /**
  2389. * Returns the result of whether this value is less than or equal to `b`.
  2390. *
  2391. * @param {CellValue} b
  2392. * @returns {CellValue}
  2393. */
  2394. lte(b) {
  2395. return CellValue.fromValue(CellValue.#compare(this, b) <= 0);
  2396. }
  2397. /**
  2398. * Returns the result of whether this value is equal to `b`.
  2399. *
  2400. * @param {CellValue} b
  2401. * @returns {CellValue}
  2402. */
  2403. eq(b) {
  2404. return CellValue.fromValue(CellValue.#compare(this, b) == 0);
  2405. }
  2406. /**
  2407. * Returns the result of whether this value is unequal to `b`.
  2408. *
  2409. * @param {CellValue} b
  2410. * @returns {CellValue}
  2411. */
  2412. neq(b) {
  2413. return CellValue.fromValue(CellValue.#compare(this, b) != 0);
  2414. }
  2415. /**
  2416. * Returns the boolean not of this value.
  2417. *
  2418. * @returns {CellValue}
  2419. */
  2420. not() {
  2421. switch (this.type) {
  2422. case CellValue.TYPE_BLANK:
  2423. return CellValue.fromValue(true);
  2424. case CellValue.TYPE_CURRENCY:
  2425. case CellValue.TYPE_NUMBER:
  2426. case CellValue.TYPE_PERCENT:
  2427. return CellValue.fromValue(this.value == 0);
  2428. case CellValue.TYPE_STRING:
  2429. throw new CellEvaluationException("Cannot perform NOT on string");
  2430. case CellValue.TYPE_BOOLEAN:
  2431. return CellValue.fromValue(!this.value);
  2432. case CellValue.TYPE_ERROR:
  2433. throw this.value;
  2434. case CellValue.TYPE_FORMULA:
  2435. throw new CellEvaluationException("Cannot perform NOT on expression");
  2436. }
  2437. }
  2438. /**
  2439. * Returns the string representation of a value concatenated to the string
  2440. * representation of this value.
  2441. *
  2442. * @param {CellValue} b
  2443. * @returns {CellValue}
  2444. */
  2445. concatenate(b) {
  2446. const s1 = this.stringValue(true);
  2447. const s2 = b.stringValue(true);
  2448. if (s1 === null || s2 === null) {
  2449. throw new CellEvaluationException("Concatenation requires string arguments");
  2450. }
  2451. return CellValue.fromValue(`${s1}${s2}`);
  2452. }
  2453. /**
  2454. * Helper to resolve two numeric arguments and perform an operation on them.
  2455. *
  2456. * @param {CellValue} a - operand A
  2457. * @param {CellValue} b - operand B
  2458. * @param {string} op - operator
  2459. * @param {function} fn - takes two `number` arguments and returns a `number` result
  2460. * @returns {CellValue} result
  2461. * @throws {CellEvaluationException}
  2462. */
  2463. static #binaryNumericOperation(a, b, op, fn) {
  2464. const ops = this.#resolveNumericOperands(a, b, op);
  2465. const aNum = ops[0];
  2466. const bNum = ops[1];
  2467. const type = ops[2];
  2468. const result = fn(aNum, bNum);
  2469. return CellValue.fromValue(result, type);
  2470. }
  2471. /**
  2472. * Determines what the result of a calculation with two operands should
  2473. * look like. Returns a tuple array of the A float value, the B float value,
  2474. * and the type of the result.
  2475. *
  2476. * @param {CellValue} a - operand A
  2477. * @param {CellValue} b - operand B
  2478. * @param {string} op - operator symbol
  2479. * @returns {Array} 3-element tuple array with A number value, B number value,
  2480. * and result type string
  2481. * @throws {CellEvaluationException} if types are incompatible for numeric operations
  2482. */
  2483. static #resolveNumericOperands(a, b, op) {
  2484. if (a.type == this.TYPE_ERROR) throw a.value;
  2485. if (b.type == this.TYPE_ERROR) throw b.value;
  2486. if (a.type == this.TYPE_STRING || b.type == this.TYPE_STRING) {
  2487. throw new CellEvaluationException("Cannot perform math on text values");
  2488. }
  2489. if (a.type == this.TYPE_BLANK) {
  2490. if (b.type == this.TYPE_BLANK) {
  2491. return [ 0, 0, this.TYPE_NUMBER, 0 ];
  2492. }
  2493. return [ 0, b.value, b.type ];
  2494. } else if (b.type == this.TYPE_BLANK) {
  2495. return [ a.value, 0, a.type ];
  2496. }
  2497. const isMultOrDiv = (op == '*' || op == '/' || op == '%');
  2498. if (a.type == b.type) {
  2499. return [ a.value, b.value, a.type ];
  2500. }
  2501. switch (a.type + b.type) {
  2502. case this.TYPE_CURRENCY + this.TYPE_NUMBER:
  2503. case this.TYPE_CURRENCY + this.TYPE_PERCENT:
  2504. return [ a.value, b.value, this.TYPE_CURRENCY ];
  2505. case this.TYPE_PERCENT + this.TYPE_CURRENCY:
  2506. return [ a.value, b.value,
  2507. isMultOrDiv ? this.TYPE_CURRENCY : this.TYPE_PERCENT ];
  2508. case this.TYPE_PERCENT + this.TYPE_NUMBER:
  2509. return [ a.value, b.value,
  2510. isMultOrDiv ? this.TYPE_NUMBER : this.TYPE_PERCENT ];
  2511. case this.TYPE_NUMBER + this.TYPE_CURRENCY:
  2512. return [ a.value, b.value, b.type ];
  2513. case this.TYPE_NUMBER + this.TYPE_PERCENT:
  2514. return [ a.value, b.value,
  2515. isMultOrDiv ? this.TYPE_NUMBER : b.type ];
  2516. case this.TYPE_BOOLEAN + this.TYPE_CURRENCY:
  2517. case this.TYPE_BOOLEAN + this.TYPE_NUMBER:
  2518. case this.TYPE_BOOLEAN + this.TYPE_PERCENT:
  2519. return [ a.value ? 1 : 0, b.value, b.type ];
  2520. case this.TYPE_CURRENCY + this.TYPE_BOOLEAN:
  2521. case this.TYPE_NUMBER + this.TYPE_BOOLEAN:
  2522. case this.TYPE_PERCENT + this.TYPE_BOOLEAN:
  2523. return [ a.value, b.value ? 1 : 0, a.type ];
  2524. }
  2525. throw new CellEvaluationException(`Unhandled operand types "${a.type}" and "${b.type}"`);
  2526. }
  2527. /**
  2528. * Performs a comparison of two values.
  2529. *
  2530. * @param {CellValue} a
  2531. * @param {CellValue} b
  2532. * @returns {number} `-1`, `0`, or `1` if a < b, a == b, or a > b, respectively
  2533. */
  2534. static #compare(a, b) {
  2535. const args = CellValue.#resolveComparableArguments(a, b);
  2536. const valueA = args[0];
  2537. const valueB = args[1];
  2538. if (typeof valueA == 'string') {
  2539. return valueA.localeCompare(valueB, undefined, { sensitivity: 'accent' });
  2540. } else {
  2541. if (valueA < valueB) return -1;
  2542. if (valueA > valueB) return 1;
  2543. return 0;
  2544. }
  2545. }
  2546. /**
  2547. * @param {CellValue} a
  2548. * @param {CellValue} b
  2549. * @returns {Array}
  2550. */
  2551. static #resolveComparableArguments(a, b) {
  2552. if (a.type == CellValue.TYPE_ERROR) throw a.value;
  2553. if (b.type == CellValue.TYPE_ERROR) throw b.value;
  2554. if (a.type == CellValue.TYPE_FORMULA) throw new CellEvaluationException("Can't compare formula values");
  2555. if (b.type == CellValue.TYPE_FORMULA) throw new CellEvaluationException("Can't compare formula values");
  2556. const aNumValue = a.value;
  2557. const bNumValue = b.value;
  2558. const aStrValue = `${a.value}`;
  2559. const bStrValue = `${b.value}`;
  2560. switch (a.type) {
  2561. case CellValue.TYPE_BLANK:
  2562. aNumValue = 0;
  2563. aStrValue = '';
  2564. break;
  2565. case CellValue.TYPE_BOOLEAN:
  2566. aNumValue = (aNumValue) ? 1 : 0;
  2567. break;
  2568. }
  2569. switch (b.type) {
  2570. case CellValue.TYPE_BLANK:
  2571. bNumValue = 0;
  2572. bStrValue = '';
  2573. break;
  2574. case CellValue.TYPE_BOOLEAN:
  2575. bNumValue = (bNumValue) ? 1 : 0;
  2576. break;
  2577. }
  2578. if (a.type == CellValue.TYPE_STRING || b.type == CellValue.TYPE_STRING) {
  2579. return [ aStrValue, bStrValue ];
  2580. }
  2581. return [ aNumValue, bNumValue ];
  2582. }
  2583. /**
  2584. * Returns a formatted string for the given raw value, value type, and
  2585. * decimal places.
  2586. *
  2587. * @param {any} value
  2588. * @param {string} type
  2589. * @param {number} decimals
  2590. * @returns {string} formatted value
  2591. */
  2592. static formatType(value, type, decimals) {
  2593. switch (type) {
  2594. case CellValue.TYPE_BLANK: return '';
  2595. case CellValue.TYPE_CURRENCY: return CellValue.#formatCurrency(value, decimals);
  2596. case CellValue.TYPE_NUMBER: return CellValue.#formatNumber(value, decimals);
  2597. case CellValue.TYPE_PERCENT: return CellValue.#formatPercent(value, decimals);
  2598. case CellValue.TYPE_BOOLEAN: return value ? 'TRUE' : 'FALSE';
  2599. case CellValue.TYPE_STRING: return `${value}`;
  2600. case CellValue.TYPE_FORMULA: return `${value}`;
  2601. }
  2602. }
  2603. /**
  2604. * @param {number} value
  2605. * @param {number} decimals
  2606. * @returns {string}
  2607. */
  2608. static #formatNumber(value, decimals) {
  2609. return (value).toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
  2610. }
  2611. /**
  2612. * @param {number} dollars
  2613. * @param {number} decimals
  2614. * @returns {string}
  2615. */
  2616. static #formatCurrency(dollars, decimals) {
  2617. var s = (dollars).toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
  2618. if (s.startsWith('-')) {
  2619. return '-$' + s.substring(1);
  2620. }
  2621. return '$' + s;
  2622. }
  2623. /**
  2624. * @param {number} value
  2625. * @param {number} decimals
  2626. * @returns {string}
  2627. */
  2628. static #formatPercent(value, decimals) {
  2629. const dec = value * 100.0;
  2630. return (dec).toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals }) + '%';
  2631. }
  2632. /**
  2633. * Determines a good number of decimal places to format a value to.
  2634. *
  2635. * @param {any} value
  2636. * @param {number} maxDigits
  2637. * @returns {number} digit count
  2638. */
  2639. static #autodecimals(value, maxDigits = 6) {
  2640. if (value instanceof CellValue) {
  2641. return CellValue.#autodecimals(value.value);
  2642. }
  2643. if (typeof value == 'number') {
  2644. var s = (value).toLocaleString(undefined, { maximumFractionDigits: maxDigits });
  2645. if (/\./.exec(s) === null) return 0;
  2646. var fraction = s.split('.')[1];
  2647. return Math.min(maxDigits, fraction.length);
  2648. }
  2649. return 0;
  2650. }
  2651. /**
  2652. * Tests if a type is numeric.
  2653. *
  2654. * @param {string} type
  2655. * @returns {boolean}
  2656. */
  2657. static isTypeNumeric(type) {
  2658. return type == CellValue.TYPE_NUMBER ||
  2659. type == CellValue.TYPE_PERCENT ||
  2660. type == CellValue.TYPE_CURRENCY ||
  2661. type == CellValue.TYPE_BOOLEAN;
  2662. }
  2663. toString() {
  2664. return `[CellValue type=${this.type} value=${this.value} "${this.formattedValue}"]`;
  2665. }
  2666. }
  2667. /**
  2668. * A rectangular grid of `SpreadsheetCell`s representing a spreadsheet.
  2669. * Agnostic of presentation.
  2670. */
  2671. class SpreadsheetGrid {
  2672. /**
  2673. * Indexed by column then row.
  2674. * @type {SpreadsheetCell[][]}
  2675. */
  2676. cells;
  2677. /** @type {number} */
  2678. columnCount;
  2679. /** @type {number} */
  2680. rowCount;
  2681. /**
  2682. * @param {number} columnCount
  2683. * @param {number} rowCount
  2684. */
  2685. constructor(columnCount, rowCount) {
  2686. this.columnCount = columnCount;
  2687. this.rowCount = rowCount;
  2688. this.cells = new Array(columnCount);
  2689. for (var c = 0; c < columnCount; c++) {
  2690. this.cells[c] = new Array(rowCount);
  2691. for (var r = 0; r < rowCount; r++) {
  2692. this.cells[c][r] = new SpreadsheetCell();
  2693. }
  2694. }
  2695. }
  2696. /**
  2697. * @param {CellAddress} address
  2698. * @returns {SpreadsheetCell|null} cell, or `null` if no cell available
  2699. * @throws {CellEvaluationException} if the address it out of bounds
  2700. */
  2701. cellAt(address) {
  2702. const c = address.columnIndex, r = address.rowIndex;
  2703. if (c < 0 || c >= this.cells.length) throw new CellEvaluationException(`Unresolved cell address ${address.name}`, '#REF');
  2704. const row = this.cells[c];
  2705. if (r < 0 || r >= row.length) throw new CellEvaluationException(`Unresolved cell address ${address.name}`, '#REF');
  2706. return row[r];
  2707. }
  2708. /**
  2709. * Returns the original value at the given address.
  2710. * @param {CellAddress} address
  2711. */
  2712. valueAt(address) {
  2713. return this.cellAt(address)?.originalValue;
  2714. }
  2715. /**
  2716. * Returns the computed value at the given address.
  2717. * @param {CellAddress} address
  2718. * @returns {CellValue|null} computed value or `null`
  2719. */
  2720. outputValueAt(address) {
  2721. return this.cellAt(address)?.outputValue;
  2722. }
  2723. }
  2724. /**
  2725. * One cell in a spreadsheet grid. Has an `originalValue` to start and an
  2726. * evaluated `outputValue` after population by a `CellExpressionSet` computation.
  2727. */
  2728. class SpreadsheetCell {
  2729. /**
  2730. * @type {CellValue}
  2731. */
  2732. originalValue = CellValue.BLANK;
  2733. /**
  2734. * @type {CellValue|null}
  2735. */
  2736. outputValue = null;
  2737. /**
  2738. * Whether `outputValue` is the result of a formula evaluation.
  2739. * @type {boolean}
  2740. */
  2741. isCalculated = false;
  2742. /** @type {CellExpression|null} */
  2743. parsedExpression = null;
  2744. /**
  2745. * @type {CellValue|null}
  2746. */
  2747. get resolvedValue() { return this.outputValue ?? this.originalValue; }
  2748. }
  2749. /**
  2750. * Integration with Markdown. Adding this block reader to a parser will run a
  2751. * post-process step on any tables in the document tree. Must be used with
  2752. * `MDTableReader`. Tables without at least one formula will not be altered.
  2753. */
  2754. class MDSpreadsheetReader extends MDReader {
  2755. postProcess(state, nodes) {
  2756. for (const node of nodes) {
  2757. if (node instanceof MDTableNode) {
  2758. this.#processTable(node, state);
  2759. }
  2760. }
  2761. }
  2762. /**
  2763. * @param {MDTableNode} tableNode
  2764. * @param {MDState} state
  2765. */
  2766. #processTable(tableNode, state) {
  2767. // Measure table
  2768. const rowCount = tableNode.bodyRows.length;
  2769. var columnCount = 0;
  2770. for (const row of tableNode.bodyRows) {
  2771. columnCount = Math.max(columnCount, row.children.length);
  2772. }
  2773. // Create and populate grid
  2774. const grid = new SpreadsheetGrid(columnCount, rowCount);
  2775. for (var c = 0; c < columnCount; c++) {
  2776. for (var r = 0; r < rowCount; r++) {
  2777. const cellNode = tableNode.bodyRows[r].children[c];
  2778. if (cellNode === undefined) continue;
  2779. const cellText = cellNode.toPlaintext(state);
  2780. const gridCell = grid.cells[c][r];
  2781. gridCell.originalValue = CellValue.fromCellString(cellText);
  2782. }
  2783. }
  2784. // Calculate
  2785. const expressions = new CellExpressionSet(grid);
  2786. expressions.calculateCells();
  2787. // See if anything was calculated. If not, don't mess with table.
  2788. var isCalculated = false;
  2789. for (var c = 0; c < columnCount && !isCalculated; c++) {
  2790. for (var r = 0; r < rowCount; r++) {
  2791. if (grid.cells[c][r].isCalculated) {
  2792. isCalculated = true;
  2793. break;
  2794. }
  2795. }
  2796. }
  2797. if (!isCalculated) return;
  2798. // Copy results back to table
  2799. for (var c = 0; c < columnCount; c++) {
  2800. for (var r = 0; r < rowCount; r++) {
  2801. const cellNode = tableNode.bodyRows[r].children[c];
  2802. if (cellNode === undefined) continue;
  2803. const gridCell = grid.cells[c][r];
  2804. const gridValue = gridCell.outputValue;
  2805. const cellText = gridValue.formattedValue;
  2806. cellNode.children = [ new MDTextNode(cellText) ];
  2807. if (gridCell.isCalculated) {
  2808. cellNode.cssClasses.push('calculated');
  2809. }
  2810. cellNode.cssClasses.push(`spreadsheet-type-${gridValue.type}`);
  2811. if (gridValue.type == CellValue.TYPE_ERROR) {
  2812. cellNode.attributes['title'] = gridValue.value;
  2813. }
  2814. const gridNumber = gridValue.numericValue();
  2815. if (gridNumber !== null) {
  2816. cellNode.attributes['data-numeric-value'] = `${gridNumber}`;
  2817. }
  2818. const gridString = gridValue.stringValue(false);
  2819. if (gridString !== null) {
  2820. cellNode.attributes['data-string-value'] = gridString;
  2821. }
  2822. }
  2823. }
  2824. }
  2825. }