From b53430871a4efe017c118e5eaa7aa30e3e51f92f Mon Sep 17 00:00:00 2001 From: Danny Lin Date: Sun, 28 Nov 2021 19:49:35 -0800 Subject: [PATCH] config: filters: Add generic filter processing --- src/config/filters.ts | 72 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 src/config/filters.ts diff --git a/src/config/filters.ts b/src/config/filters.ts new file mode 100644 index 0000000..40854cf --- /dev/null +++ b/src/config/filters.ts @@ -0,0 +1,72 @@ +import { SysPartition } from '../util/partitions' + +export enum FilterMode { + Include = 'include', + Exclude = 'exclude', +} + +export interface SerializedFilters { + mode: FilterMode + + match: string[] + prefix: string[] + suffix: string[] + regex: string[] +} + +export interface Filters { + // true = inclusion list, false = exclusion list + include: boolean + + match: Set + prefix: string[] + suffix: string[] + regex: RegExp[] +} + +export type PartFilters = Record + +export function parseFilters(src: SerializedFilters) { + return { + include: src.mode == FilterMode.Include, + + match: new Set(src.match), + prefix: src.prefix, + suffix: src.suffix, + regex: src.regex.map(pat => new RegExp(pat)), + } as Filters +} + +function _matchFilters(filters: Filters, value: string) { + return filters.match.has(value) || + filters.prefix.find(prefix => value.startsWith(prefix)) != undefined || + filters.suffix.find(suffix => value.endsWith(suffix)) != undefined || + filters.regex.find(regex => value.match(regex)) != null +} + +export function filterValue(filters: Filters, value: string) { + return filters.include ? + _matchFilters(filters, value) : + !_matchFilters(filters, value) +} + +export function filterValues(filters: Filters, values: string[]) { + return values.filter(value => filterValue(filters, value)) +} + +// Map, in-place +export function filterKeys(filters: Filters, map: Map) { + for (let key of map.keys()) { + if (!filterValue(filters, key)) { + map.delete(key) + } + } + + return map +} + +// Map, copy +export function filterKeysCopy(filters: Filters, map: Map) { + return new Map(Array.from(map.entries()) + .filter(([key]) => filterValue(filters, key))) +}