All files / src/utils filters.ts

100% Statements 81/81
100% Branches 22/22
100% Functions 5/5
100% Lines 81/81

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 821x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 6x 6x 4x 4x 4x 1x 7x 7x 2x 2x 5x 5x 5x 1x 14x 14x 14x 14x 14x 14x 14x 2x 2x 14x 14x 5x 5x 5x 2x 2x 2x 5x 3x 3x 5x 5x 5x 14x 14x 7x 7x 14x 14x 3x 3x 14x 14x 3x 3x 3x 3x 14x 14x 14x 1x 3x 3x 3x 1x 1x 1x 1x  
export type FilterSpec = {
  /** Filter name */
  filter: string
  /** Filter ID */
  id?: string
  /** Filter options */
  options?: string[] | { [key: string]: string }
  /** Filter input link labels */
  inputs?: string[]
  /** Filter output link labels */
  outputs?: string[]
}
 
export type FilterChain = FilterSpec[]
 
export type FilterGraph = FilterChain[]
 
function escapeOption(option: string): string {
  if (option.match(/[\\':]/)) {
    return option.replace(/([\\':])/g, '\\$1')
  }
 
  return option
}
 
function escapeFilter(filter: string): string {
  if (filter.match(/[\\'[\],;]/)) {
    return filter.replace(/([\\'[\],;])/g, '\\$1')
  }
 
  return filter
}
 
export function generateFilter(
  spec: FilterSpec,
  escape: boolean = false
): string {
  let filterString = spec.filter
 
  if (spec.id) {
    filterString = `${filterString}@${spec.id}`
  }
 
  if (spec.options) {
    let options = spec.options
 
    if (!Array.isArray(options)) {
      options = Object.entries(options).map(
        ([key, value]) => `${key}=${escapeOption(value)}`
      )
    } else {
      options = options.map((o) => escapeOption(o))
    }
 
    filterString = `${filterString}=${options.join(':')}`
  }
 
  if (escape) {
    filterString = escapeFilter(filterString)
  }
 
  if (spec.inputs) {
    filterString = `${spec.inputs.map((i) => `[${i}]`).join('')}${filterString}`
  }
 
  if (spec.outputs) {
    filterString = `${filterString}${spec.outputs
      .map((o) => `[${o}]`)
      .join('')}`
  }
 
  return filterString
}
 
export function generateFilterChain(chain: FilterChain): string {
  return chain.map((spec) => generateFilter(spec, true)).join(',')
}
 
export function generateFilterGraph(graph: FilterGraph): string {
  return graph.map((chain) => generateFilterChain(chain)).join(';')
}