-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRule.ts
More file actions
38 lines (37 loc) · 1 KB
/
Rule.ts
File metadata and controls
38 lines (37 loc) · 1 KB
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
import { Criteria } from "./Criteria"
export abstract class Rule {
abstract readonly precedence: number
abstract readonly class: string
readonly symbol: string | undefined
abstract is(value: any): boolean
abstract is(value: any, object?: any): boolean
filter<T>(value: T[]): T[] {
return value.filter(element => this.is(element))
}
abstract toString(): string
stringify(precedence = 0): string {
let result = this.toString()
if (this.precedence < precedence)
result = "(" + result + ")"
return result
}
}
const creators: ((criteria: Criteria) => Rule | undefined)[] = [
criteria => (criteria instanceof Rule ? criteria : undefined),
]
export function add(create: (criteria: Criteria) => Rule | undefined) {
creators.push(create)
}
let always: Rule
export function setFallback(fallback: Rule) {
always = fallback
}
export function create(criteria: Criteria): Rule {
let result: Rule | undefined
for (const c of creators) {
result = c(criteria)
if (result)
break
}
return result || always
}