-
Notifications
You must be signed in to change notification settings - Fork 0
/
parsing.js
539 lines (457 loc) · 13.5 KB
/
parsing.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
import {getNumberInsteadLiteral, getSelection, Cell, checkStringId, getLiteralInsteadNumber} from "./scripts.js";
import {Formula, SUM, SUB, MULT, DIV, AVG, MAX, MIN, LENGTH, FILL} from "./formulas_logic.js";
/**
* Array of separators for parsing.
* @type Array<string>
*/
let SEPS = ['==', '!=', '**', '<=', '>=', '&&', '||', '(', ')', '<', '>','+', '-', '*', '/', '%', '!', ':', ';'];
/**
* Check string for similarity with a calculated expression.
* @param cell_value : string
* @returns {boolean|string[]}
*/
export function isCalcExpression(cell_value){
return cell_value[0] === '=';
}
/**
* Get an array of separators, suitable for parsing.
* @returns Array<string>
*/
function generateWorkingSeparators(){
let swapSeps = [];
for (let sep of SEPS){
swapSeps.push('\\' + sep + '\\');
}
return swapSeps;
}
/**
* Check cell value for containing only one formula.
* @param cell_value : string
* @returns {boolean}
*/
export function isSingleFunction(cell_value){
let counter = 0;
let isChanged = false;
for (let i = 0; i < cell_value.length; i++){
if (cell_value[i] === '('){
counter += 1;
isChanged = true;
}
if (cell_value[i] === ')'){
counter -= 1;
}
if (counter === 0 && isChanged === true){
return i === cell_value.length - 1;
}
}
}
/**
* Check string on similarity with separators from SEPS array.
* @param string : string
* @returns {boolean}
*/
function isSeparator(string){
for (let sep of SEPS){
if (sep === string) return true;
}
return false;
}
/**
* Get a safe string for future eval() operations.
* @param str_array : Array<string>
* @returns {string|boolean}
*/
function getSafeEvalStr(str_array){
let safeString = '';
for (let str of str_array){
str = str.trim();
if (isDigit(str) || isSeparator(str)){
safeString += str;
}
else if (isCellNumber(str)){
if (checkStringId(getCellHTMLId(str))) {
safeString += getCellHTMLValue(str);
}
else return false;
}
else return false;
}
return safeString;
}
/**
* Delete all empty strings of array.
* @param array : Array<string>
* @returns Array<string>
*/
function deleteEmptyStrings(array){
return array.filter(el => el.trim() !== '');
}
/**
* Clues all double separators, which are not in same element (for example : '<', '=' become '<=')
* @param parsed_expression : Array<string>
* @returns Array<string>
*/
function clueDoubleSeparators(parsed_expression){
let result = [];
for (let i = 0; i < parsed_expression.length; i++){
if (i < parsed_expression.length && isSeparator(parsed_expression[i] + parsed_expression[i + 1])){
result.push(parsed_expression[i] + parsed_expression[i + 1]);
i++;
}
else result.push(parsed_expression[i]);
}
return result;
}
/**
* Get an array of elements from a string.
* @param calc_expression : string
* @param for_args : boolean
* @returns Array<string>
*/
export function parseAll(calc_expression, for_args = false){
let sepsForSwap = generateWorkingSeparators();
let result_str = calc_expression;
for (let i = 0; i < SEPS.length; i++){
if (!for_args && (SEPS[i] === ';' || SEPS[i] === ':')) continue;
result_str = result_str.replaceAll(SEPS[i], sepsForSwap[i]);
}
return clueDoubleSeparators(deleteEmptyStrings(result_str.split('\\')));
// return result_str.split('\\');
}
/**
* Calculate an calculable string expression.
* @param calc_expression : string
* @returns {string|boolean}
*/
export function calcExpression(calc_expression){
calc_expression = calc_expression.slice(1);
while (hasSubFormula(calc_expression)){
calc_expression = calcSubFormula(calc_expression);
if (calc_expression === false) return false;
}
let parsed_expression = parseAll(calc_expression);
let safeString = getSafeEvalStr(parsed_expression);
if (safeString === false) return false;
let result = '';
try {
result = eval(safeString);
if (result === Infinity || result === -Infinity || isNaN(Number(result))){
return false;
}
return String(result);
} catch (e) {
if (e instanceof SyntaxError) return false;
}
}
/**
* Check the cell_value for similarity with formula format.
* @param cell_value : string
* @returns {boolean}
*/
export function isFormula(cell_value){
return cell_value.trim().match("^=[A-Za-z]{1,}\\(.{1,}\\)$") !== null;
}
/**
* Check args for subformula.
* @param args : string
* @returns {boolean}
*/
export function hasSubFormula(args){
return args.match("=[A-Za-z]{1,}\\(.{1,}\\)") !== null;
}
/**
* Get a position of ) with nesting
* @param params : string
* @returns {number}
*/
export function getEndOfArgs(params){
let counter = 0;
let isChanged = false;
let formula_start = -1;
for (let i = 0; i < params.length; i++){
if (params[i] === '=') formula_start = i;
if (params[i] === '(' && formula_start !== -1){
counter += 1;
isChanged = true;
}
if (params[i] === ')' && formula_start !== -1) {
counter -= 1;
}
if (counter === 0 && isChanged === true && formula_start !== -1){
return i;
}
}
return -1;
}
/**
* Calculates sub formula in string and replaces formula with result
* @param params : string
* @returns
*/
export function calcSubFormula(params){
let end_of_args = getEndOfArgs(params);
if (end_of_args === -1) return false;
let result = calcFormula(params.slice(params.indexOf('='), end_of_args + 1));
if (result === '#ОШИБКА') return false;
return params.replace(params.slice(params.indexOf('='), end_of_args + 1), result);
}
/**
* Calculate slice of cells values.
* Returns false, if args have wrong format.
* @param args : Array<string>
* @param action : function
* @returns {boolean|number}
*/
export function calcSliceArgs(args, action){
if (args.length !== 2) return false;
if (!isCellNumber(args[0]) || !isCellNumber(args[1])) return false;
let start_cell = new Cell(getCellHTMLId(args[0]));
if (!checkStringId(start_cell.getFullId())) return false;
start_cell.setValue(document.getElementById(start_cell.getFullId()).value);
let finish_cell = new Cell(getCellHTMLId(args[1]));
if (!checkStringId(finish_cell.getFullId())) return false;
finish_cell.setValue(document.getElementById(finish_cell.getFullId()).value);
return calcSelection(getSelection(start_cell, finish_cell), action);
}
/**
* Get a parsed cell number ('$a$1' --> '$', 'a', '$', '1')
* @param cell_number_str : string
* @returns Array<string>
*/
function parseCellNumber(cell_number_str){
let parsedNum = [];
let acc = '';
let i = 0;
while (i < cell_number_str.length){
if (cell_number_str[i] === '$'){
parsedNum.push(cell_number_str[i]);
i++;
}
while(cell_number_str[i] !== '$' && !isDigit(cell_number_str[i])){
acc += cell_number_str[i];
i++;
}
parsedNum.push(acc);
acc = '';
if (cell_number_str[i] === '$'){
parsedNum.push(cell_number_str[i]);
i++;
}
while(cell_number_str[i] !== undefined){
acc += cell_number_str[i];
i++;
}
}
parsedNum.push(acc);
return parsedNum;
}
/**
* Get all cell numbers from formula or calc expression.
* @param args_str : string
* @returns Array<string>
*/
function getAllCellNumbersArguments(args_str) {
let args = parseAll(args_str, true);
trimArguments(args);
let cell_args = [];
for (let arg of args) {
if (isCellNumber(arg)) {
cell_args.push(arg);
}
}
return cell_args;
}
/**
* Add offset to current cell number.
* @param parsed_cell : Array<string>
* @param vert : number
* @param hor : number
*/
function addOffsetToCell(parsed_cell, vert, hor){
let num_vert = 0;
let num_hor = 0;
let check_id = [];
for (let i = 0; i < parsed_cell.length; i++){
if (parsed_cell[i] === '$') {
i++;
check_id.push(parsed_cell[i]);
continue;
}
if (isDigit(parsed_cell[i])){
num_vert = Number(parsed_cell[i]);
parsed_cell[i] = String(num_vert + vert);
check_id.push(Number(parsed_cell[i]));
}
else{
num_hor = Number(getNumberInsteadLiteral(parsed_cell[i]));
parsed_cell[i] = getLiteralInsteadNumber(num_hor + hor);
check_id.push(Number(getNumberInsteadLiteral(parsed_cell[i])));
}
}
if (checkStringId(check_id.join('_'))){
return parsed_cell.join('');
}
else return false;
}
/**
* Add offset to all cell numbers in formula.
* @param indicative_cell : Cell
* @param current_cell : Cell
* @param formula : string
* @returns {*}
*/
export function addOffsetToRelFormula(indicative_cell, current_cell, formula){
let cell_args = getAllCellNumbersArguments(formula);
let new_cell_args = [];
if (cell_args === []) return formula;
let vert_diff = current_cell.getRowNum() - indicative_cell.getRowNum();
let hor_diff = current_cell.getColNum() - indicative_cell.getColNum();
for (let arg of cell_args){
let parsed_arg = parseCellNumber(arg);
let offset_cell = addOffsetToCell(parsed_arg, vert_diff, hor_diff);
if (offset_cell === false) return false;
new_cell_args.push(offset_cell);
}
for (let i = 0; i < new_cell_args.length; i++){
formula = formula.replace(cell_args[i], new_cell_args[i]);
}
return formula;
}
/**
* Calculate separated arguments.
* @param args : Array<string>
* @param action : function
* @returns {number, boolean}
*/
export function calcSepArgs(args, action){
for (let arg of args){
if (arg.includes(':')) return false;
}
return action(args);
}
/**
* Trim arguments in array
* @param args : Array<string>
*/
export function trimArguments(args){
for (let i = 0; i < args.length; i++){
args[i] = args[i].trim();
}
}
/**
* Calculate values of cells in selection.
* @param selection : Selection
* @param action : function
* @returns {number}
*/
function calcSelection(selection, action){
return action(selection);
}
/**
* Check value for string representation of number.
* @param value : string
* @returns {boolean}
*/
export function isDigit(value){
return !isNaN(value) && value !== '' && Number(value) !== Number.POSITIVE_INFINITY && Number(value) !== Number.NEGATIVE_INFINITY;
}
/**
* Get cell value of table.
* Cell number format like A1, b3, C20.
* @param cell_number : string
* @returns {string}
*/
export function getCellHTMLValue(cell_number){
return document.getElementById(getCellHTMLId(cell_number)).value;
}
/**
* Get cell id for HTML search.
* Cell number format like A1, b3, C20.
* @param cell_number : string
* @returns {string}
*/
export function getCellHTMLId(cell_number){
let letterId = cell_number.match("^[$]{0,1}[A-Za-z]{1,3}")[0];
let numberId = cell_number.match("[$]{0,1}[0-9]{1,3}")[0];
if (letterId.includes('$')){
letterId = letterId.replaceAll('$', '');
}
if (numberId.includes('$')){
numberId = numberId.replaceAll('$', '');
}
return `${numberId}_${getNumberInsteadLiteral(letterId)}`
}
/**
* Check value for representation of cell number format like A1, b3, C20.
* @param value : string
* @returns {boolean}
*/
export function isCellNumber(value) {
return value.match("^[$]{0,1}[A-Za-z]{1,3}[$]{0,1}[0-9]{1,3}$") !== null;
}
/**
* Get formula name from string, which containing a string representation of formula.
* @param string_formula : string
* @returns {string}
*/
function getFormulaName(string_formula){
return string_formula.slice(string_formula.indexOf('=') + 1, string_formula.indexOf('(')).toUpperCase();
}
/**
* Get formula arguments from string, which containing a string representation of formula.
* @param string_formula : string
* @returns {string}
*/
function getFormulaArguments(string_formula){
return string_formula.slice(string_formula.indexOf('(') + 1, string_formula.lastIndexOf(')'));
}
/**
* Check formula name for presence in formulas list.
* Returns false, if formula does not exist.
* @param formula_name : string
* @returns {Formula|boolean}
*/
function checkFormula(formula_name){
for (let formula of FORMULAS){
if (formula.getName() === formula_name){
return formula;
}
}
return false;
}
/**
* Calculate formula.
* Returns false, if found errors.
* @param string_formula : string
* @returns {string|boolean}
*/
export function calcFormula(string_formula){
let fName = getFormulaName(string_formula);
if (fName === ''){
return false;
}
let formula = checkFormula(fName);
if (formula === false){
return false;
}
let fArgs = getFormulaArguments(string_formula);
if (fArgs === ''){
return false;
}
return formula.action(fArgs);
}
/**
* List of available formulas.
* @type {Array<Formula>}
*/
const FORMULAS = [
new Formula("SUM", SUM),
new Formula("SUB", SUB),
new Formula("MULT", MULT),
new Formula("DIV", DIV),
new Formula("AVG", AVG),
new Formula("MAX", MAX),
new Formula("MIN", MIN),
new Formula("LENGTH", LENGTH),
new Formula("FILL", FILL)
];