import { CharCode } from "./charcode" ; export function findToken ( tokenList , token ) { if ( tokenList ) { for ( let start = 0 ; start >= 0 ; start = tokenList . indexOf ( " " , start + 1 ) ) { start = tokenList . indexOf ( token , start ) ; if ( start < 0 ) { return undefined ; } if ( start === 0 || tokenList . charCodeAt ( start - 1 ) === CharCode . space ) { const end = start + token . length ; if ( end === tokenList . length || end < tokenList . length && tokenList . charCodeAt ( end ) === CharCode . space ) { return { start , end } ; } } } } return undefined ; } export namespace TokenList { export function set ( tokenList , token ) { return ! tokenList ? token : ! token || findToken ( tokenList , token ) ? tokenList : `${ tokenList } ${ token }` ; } export function unset ( tokenList , token ) { const span = findToken ( tokenList , token ) ; if ( ! span ) { return tokenList ; } const { start , end } = span ; return end < tokenList . length ? `${ tokenList . slice ( 0 , start ) }${ tokenList . slice ( end + 1 ) }` : tokenList . slice ( 0 , start > 0 ? start - 1 : 0 ) ; } export function computeToggle ( tokenList , toAdd , toRemove ) { if ( ! tokenList ) { return ; } for ( let i = toAdd . length - 1 ; i >= 0 ; i -- ) { const token = toAdd [ i ] ; if ( findToken ( tokenList , token ) ) { toRemove . add ( token ) ; toAdd . splice ( i , 1 ) ; } } } }