import {JSONDigester} from "./JSONDigester"; import {Rule} from "./Rule"; export class Rules { private _rules:Array = []; private _digester:JSONDigester; private _cache:{ [key: string]: Array }; constructor() { this._cache = {}; } get rules():Rule[] { return this._rules; } get digester():JSONDigester { return this._digester; } set digester(digester:JSONDigester) { this._digester = digester; for (let rule of this._rules) { rule.digester = digester; } } /** * Register a new Rule instance matching the specified pattern. * * @param pattern Nesting pattern to be matched for this Rule * @param rule Rule instance to be registered */ add(pattern:string, rule:Rule):void { let patternLength = pattern.length; if (patternLength > 1 && pattern.endsWith('/')) { pattern = pattern.substring(0, patternLength - 1); } let list = this._cache[pattern]; if (!list) { list = []; this._cache[pattern] = list; } list.push(rule); this._rules.push(rule); if (this._digester) { rule.digester = this._digester; } } /** * Return a List of all registered Rule instances that match the specified * nesting pattern, or a zero-length List if there are no matches. If more * than one Rule instance matches, they must be returned * in the order originally registered through the add() * method. * * @param pattern Nesting pattern to be matched */ match(pattern:string):Rule[] { let rulesList = this.lookup(pattern); if (! rulesList || rulesList.length < 1) { // Find the longest key, ie more discriminant let longKey = ''; for (let key of Object.keys(this._cache)) { if (key.startsWith('*/')) { if (pattern === key.substring(2) || pattern.endsWith(key.substring(1))) { if (key.length > longKey.length) { rulesList = this.lookup(key); longKey = key; } } } } } if (!rulesList) { rulesList = []; } return rulesList; } /** * Return a List of Rule instances for the specified pattern. If there are no such * rules, return null. * * @param pattern Pattern to be matched */ private lookup(pattern:string):Rule[] { const list = this._cache[pattern]; if (!list) { return null; } return list; } }