all files / src/hyperscript/hasCssSelector/ matchAttribute.ts

59.09% Statements 13/22
25% Branches 3/12
100% Functions 1/1
61.9% Lines 13/21
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                                                     
// ~ and * : value contains
// | and ^ : value starts with
// $ : value ends with
 
const attrModifiers: Array<string> =
  [ '~', '*', '|', '^', '$' ]
 
export function matchAttribute(cssSelector: string, attrs: any) {
  // tslint:disable-next-line:prefer-const
  let [ attribute, value ] = cssSelector.split('=')
 
  const attributeLength = attribute.length - 1
 
  const modifier = attribute[attributeLength]
  const modifierIndex = attrModifiers.indexOf(modifier)
 
  Eif (modifierIndex > -1) {
    attribute = attribute.slice(0, attributeLength)
    const attrModifier = attrModifiers[modifierIndex]
 
    const attrValue = String(attrs[attribute])
 
    Iif (!attrValue) return false
 
    switch (attrModifier) {
    case '~': return attrValue.indexOf(value) > -1
    case '*': return attrValue.indexOf(value) > -1
    case '|': return attrValue.indexOf(value) === 0
    case '^': return attrValue.indexOf(value) === 0
    case '$': return attrValue.slice(-value.length) === value
    default: return false
    }
  }
 
  if (value)
    return value === attrs[attribute]
 
  return !!attrs[attribute]
}