From e510c2cde5d2b7b86daf95e3abbbf82681b35756 Mon Sep 17 00:00:00 2001 From: uri Date: Thu, 28 Mar 2024 10:36:34 +0200 Subject: [PATCH] trigger-utils --- src/index.ts | 42 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/src/index.ts b/src/index.ts index 0af552b..60afeec 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,16 +1,17 @@ import { + alljuxt, + complement, includedIn, join, letIn, - logAround, lowercase, + map, max, nonempty, pipe, range, replace, reverse, - sideLog, sort, split, take, @@ -364,3 +365,40 @@ export const someKewyordMatches = (keywords: string[]) => (x: string) => export const urlsInText = (text: string) => text.match(/https?:\/\/[^\s/$.?#].[^\s]*/g) || []; + +type Keywords = { keywords: string[]; antiKeywords?: string[] }; + +type ValueToKeywords = Record< + T, + Keywords +>; + +type PredicateAndValue = [(txt: string) => boolean, T]; + +const keywordMatchers = ( + valuesAndKeywords: ValueToKeywords, +) => + (Object.entries(valuesAndKeywords) as [T, Keywords][]).map( + ( + [value, { keywords, antiKeywords }]: [T, Keywords], + ): PredicateAndValue => [ + alljuxt( + someKewyordMatches(keywords), + complement(someKewyordMatches(antiKeywords ?? [])), + ), + value, + ], + ); + +export const triggerByText = ( + x: ValueToKeywords, +) => + pipe( + keywordMatchers, + (matcher: PredicateAndValue[]): (text: string) => T[] => + // @ts-expect-error pipe typing doesn't handle generics + pipe( + (text) => matcher.filter(([predicate]) => predicate(text)), + map(([, value]) => value), + ), + )(x);