All files / src/error-correction ec-level.js

100% Statements 45/45
100% Branches 11/11
100% Functions 2/2
100% Lines 45/45

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 461x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 30x 6x 6x 24x 24x 30x 4x 4x 4x 20x 20x 1x 1x 1x 1x 1x 1x 1x 1x 1x 22x 7x 7x 15x 15x  
export const CORRECTION_LEVEL_L = 1
export const CORRECTION_LEVEL_M = 0
export const CORRECTION_LEVEL_Q = 3
export const CORRECTION_LEVEL_H = 2
 
const correctionLevelNames = ['Medium', 'Low', 'High', 'Quartile']
 
/** @type {Record<string, { bit: number, name: string }>} */
const correctionLevelMap = correctionLevelNames.reduce((acc, name, bit) => {
  const result = { bit, name }
  return { ...acc, [name.toUpperCase()]: result, [name[0]]: result }
}, {})
 
/**
 * Get error correction level from string
 * @param {string} string - correction level text
 * @throws error on invalid correction level
 * @returns {{ bit: number, name: string }} correction level object
 */
export function fromString (string) {
  if (typeof string !== 'string') {
    throw new Error(`expected string instead of ${typeof string}`)
  }
 
  const result = correctionLevelMap[string.toUpperCase()]
  if (!result) {
    const validKeys = [1, 0, 3, 2].flatMap(idx => [correctionLevelNames[idx][0], correctionLevelNames[idx]]).map(name => `"${name}"`).join(', ')
    throw new Error(`Unknown Error Correction Level: "${string}" expected one of the following values (case insensitive): ${validKeys}`)
  }
  return result
}
 
/**
 * Checks if error correction level is valid.
 *
 * Error correction is valid if `string` is one of the following values (case insensitive): `L`,`Low`,`M`,`Medium`,`Q`,`Quartile`,`H` and `High`
 * @param {string} string - target string
 * @returns {boolean} true if correction level is valid, false otherwise
 */
export function isValid (string) {
  if (typeof string !== 'string') {
    return false
  }
  return Object.hasOwn(correctionLevelMap, string.toUpperCase())
}