import { AlgoFn } from "./algo" ; import { Int32 } from "./numerics" ; import { buildPatternForExtendedMatch , TermType , termTypeMap } from "./pattern" ; import { Rune } from "./runes" ; import { slab , Slab } from "./slab" ; interface Token { text : Rune [ ] ; prefixLength : Int32 ; } type Offset = [ number , number ] ; function iter ( algoFn , tokens , caseSensitive , normalize , forward , pattern , slab ) { for ( const part of tokens ) { const [ res , pos ] = algoFn ( caseSensitive , normalize , forward , part . text , pattern , true , slab ) ; if ( res . start >= 0 ) { const sidx = res . start + part . prefixLength ; const eidx = res . end + part . prefixLength ; if ( pos !== null ) { const newPos = new Set < number > ( ) ; pos . forEach ( ( v ) => newPos . add ( part . prefixLength + v ) ) ; return [ [ sidx , eidx ] , res . score , newPos ] ; } return [ [ sidx , eidx ] , res . score , pos ] ; } } return [ [ - 1 , - 1 ] , 0 , null ] ; } export function computeExtendedMatch ( text , pattern , fuzzyAlgo , forward ) { const input = [ { text , prefixLength : 0 , } , ] ; const offsets = [ ] ; let totalScore = 0 ; const allPos = new Set < number > ( ) ; for ( const termSet of pattern . termSets ) { let offset = [ 0 , 0 ] ; let currentScore = 0 ; let matched = false ; for ( const term of termSet ) { let algoFn = termTypeMap [ term . typ ] ; if ( term . typ === TermType . Fuzzy ) { algoFn = fuzzyAlgo ; } const [ off , score , pos ] = iter ( algoFn , input , term . caseSensitive , term . normalize , forward , term . text , slab ) ; const sidx = off [ 0 ] ; if ( sidx >= 0 ) { if ( term . inv ) { continue ; } offset = off ; currentScore = score ; matched = true ; if ( pos !== null ) { pos . forEach ( ( v ) => allPos . add ( v ) ) ; } else { for ( let idx = off [ 0 ] ; idx < off [ 1 ] ; ++ idx ) { allPos . add ( idx ) ; } } break ; } else if ( term . inv ) { offset = [ 0 , 0 ] ; currentScore = 0 ; matched = true ; continue ; } } if ( matched ) { offsets . push ( offset ) ; totalScore += currentScore ; } } return { offsets , totalScore , allPos } ; }