cmpstr
Version:
CmpStr is a lightweight, fast and well performing package for calculating string similarity
100 lines (97 loc) • 3.03 kB
JavaScript
// CmpStr v3.2.2 build-bb61120-260311 by Paul Köhler @komed3 / MIT License
import { ErrorUtil } from './Errors.mjs';
class Filter {
static filters = new Map();
static pipeline = new Map();
static getPipeline(hook) {
return ErrorUtil.wrap(
() => {
const cached = Filter.pipeline.get(hook);
if (cached) return cached;
const filter = Filter.filters.get(hook);
if (!filter) return (s) => s;
const pipeline = Array.from(filter.values())
.filter((f) => f.active)
.sort((a, b) => a.priority - b.priority)
.map((f) => f.fn);
const fn = (input) => pipeline.reduce((v, f) => f(v), input);
Filter.pipeline.set(hook, fn);
return fn;
},
`Error compiling filter pipeline for hook <${hook}>`,
{ hook }
);
}
static has(hook, id) {
return !!Filter.filters.get(hook)?.has(id);
}
static add(hook, id, fn, opt = {}) {
return ErrorUtil.wrap(
() => {
const { priority = 10, active = true, overrideable = true } = opt;
const filter = Filter.filters.get(hook) ?? new Map();
const index = filter.get(id);
if (index && !index.overrideable) return false;
filter.set(id, { id, fn, priority, active, overrideable });
Filter.filters.set(hook, filter);
Filter.pipeline.delete(hook);
return true;
},
`Error adding filter <${id}> to hook <${hook}>`,
{ hook, id, opt }
);
}
static remove(hook, id) {
Filter.pipeline.delete(hook);
const filter = Filter.filters.get(hook);
return filter ? filter.delete(id) : false;
}
static pause(hook, id) {
Filter.pipeline.delete(hook);
const f = Filter.filters.get(hook)?.get(id);
return !!(f && ((f.active = false), true));
}
static resume(hook, id) {
Filter.pipeline.delete(hook);
const f = Filter.filters.get(hook)?.get(id);
return !!(f && ((f.active = true), true));
}
static list(hook, active = false) {
const filter = Filter.filters.get(hook);
if (!filter) return [];
const out = [];
for (const f of filter.values()) if (!active || f.active) out.push(f.id);
return out;
}
static apply(hook, input) {
return ErrorUtil.wrap(
() => {
const fn = Filter.getPipeline(hook);
return Array.isArray(input) ? input.map(fn) : fn(input);
},
`Error applying filters for hook <${hook}>`,
{ hook, input }
);
}
static async applyAsync(hook, input) {
return ErrorUtil.wrapAsync(
async () => {
const fn = Filter.getPipeline(hook);
return Array.isArray(input)
? Promise.all(input.map(fn))
: Promise.resolve(fn(input));
},
`Error applying filters for hook <${hook}>`,
{ hook, input }
);
}
static clear(hook) {
Filter.pipeline.clear();
if (hook) Filter.filters.delete(hook);
else Filter.filters.clear();
}
static clearPipeline() {
Filter.pipeline.clear();
}
}
export { Filter };