This repository has been archived by the owner on Jun 4, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 74
/
index.ts
102 lines (82 loc) · 2.39 KB
/
index.ts
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
import * as R from 'ramda';
import Logger from 'core/Logger';
import lexer, {ILexerResult} from 'core/syntax-tree/lexer';
import syntaxer, {
ISyntaxerResult,
ISyntaxTree
} from 'core/syntax-tree/syntaxer';
import {Lexicon} from './lexicon';
interface IStructure {
subType?: string;
type: string;
value: any;
block?: IStructure;
left?: IStructure;
right?: IStructure;
}
function toStructure(tree: ISyntaxTree): IStructure {
const {block, left, lexeme, right, value} = tree;
const res: IStructure = {
subType: lexeme.subType,
type: lexeme.type,
value: lexeme.present ? lexeme.present(tree) : value
};
if (block) {
res.block = toStructure(block);
}
if (left) {
res.left = toStructure(left);
}
if (right) {
res.right = toStructure(right);
}
return res;
}
export default class SyntaxTree {
protected lexerResult: ILexerResult;
protected syntaxerResult: ISyntaxerResult;
get isValid() {
return this.syntaxerResult.valid;
}
private get tree() {
return this.syntaxerResult.tree;
}
constructor(
public readonly lexicon: Lexicon,
public readonly query: string,
postProcessor: (res: ILexerResult) => ILexerResult = res => res
) {
this.lexerResult = postProcessor(lexer(this.lexicon, this.query));
this.syntaxerResult = syntaxer(this.lexerResult);
}
evaluate = (target: any) => {
if (!this.isValid) {
const msg = `DataTable filtering syntax is invalid for query: ${this.query}`;
Logger.error(msg);
throw new Error(msg);
}
return this.tree && this.tree.lexeme && this.tree.lexeme.evaluate
? this.tree.lexeme.evaluate(target, this.tree)
: true;
};
filter = (targets: any[]) => {
return targets.filter(this.evaluate);
};
toQueryString() {
return this.lexerResult.valid
? R.map(
l =>
l.lexeme.transform
? l.lexeme.transform(l.value)
: l.value,
this.lexerResult.lexemes
).join(' ')
: '';
}
toStructure() {
if (!this.isValid || !this.syntaxerResult.tree) {
return null;
}
return toStructure(this.syntaxerResult.tree);
}
}