All files / src/infer-encoding infer-encoding-by-mapping.ts

100% Statements 18/18
100% Branches 8/8
100% Functions 6/6
100% Lines 14/14

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 2518x 18x       18x 10x   12x 10x 31x 2x 2x     1x     9x 33x 28x 25x      
import { Encoding, InferEncodingFunc } from '@/consts'
import inferEncodingNormally from './infer-encoding-normally'
 
type EncodingMapping = Partial<Record<Encoding, string | ((path: string) => boolean)>>
 
export default function(mapping: EncodingMapping): InferEncodingFunc {
  const encodingRegExpMap = Object.entries(mapping)
    .map(([key, value]) => {
      if (typeof value === 'string') {
        const pattern = new RegExp(value)
        return { encoding: key as Encoding, match: v => pattern.test(v) }
      } else if (typeof value === 'function') {
        return { encoding: key as Encoding, match: v => value(v) }
      }
 
      throw new Error('Encoding mapping should be function or regexp')
    })
 
  return path => {
    const item = encodingRegExpMap.find(item => item.match(path))
    if (item && Object.values(Encoding).includes(item.encoding)) return item.encoding
    else return inferEncodingNormally(path)
  }
}