All files / env uaMatch.js

91.67% Statements 22/24
77.27% Branches 17/22
100% Functions 2/2
91.67% Lines 22/24

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                                        11x 11x 8x     8x     11x 11x 11x 53x 53x 53x 3x 1x   50x     43x 43x 9x     9x     7x 7x 1x             11x     2x  
/**
 * UA字符串匹配列表
 * @method env/uaMatch
 * @param {Object} list 检测 Hash 列表
 * @param {String} ua 用于检测的 UA 字符串
 * @param {Object} conf 检测器选项,传递给检测函数
 * @example
 * var $uaMatch = require('@spore-ui/kit/packages/env/uaMatch');
 * var rs = $uaMatch({
 *   trident: 'trident',
 *   presto: /presto/,
 *   gecko: function(ua){
 *     return ua.indexOf('gecko') > -1 && ua.indexOf('khtml') === -1;
 *   }
 * }, 'xxx presto xxx');
 * console.info(rs.presto); // true
 * console.info(rs.trident); // undefined
 */
 
function uaMatch(list, ua, conf) {
  var result = {};
  if (!ua) {
    Iif (typeof window === 'undefined') {
      ua = '';
    } else {
      ua = window.navigator.userAgent;
    }
  }
  ua = ua.toLowerCase();
  Eif (typeof list === 'object') {
    Object.keys(list).forEach(function (key) {
      var tester = list[key];
      Eif (tester) {
        if (typeof tester === 'string') {
          if (ua.indexOf(tester) > -1) {
            result[key] = true;
          }
        } else if (
          Object.prototype.toString.call(tester) === '[object RegExp]'
        ) {
          var match = ua.match(tester);
          if (match) {
            Iif (match[1]) {
              result[key] = match[1];
            } else {
              result[key] = true;
            }
          }
        } else Eif (typeof tester === 'function') {
          if (tester(ua, conf)) {
            result[key] = tester(ua);
          }
        }
      }
    });
  }
 
  return result;
}
 
module.exports = uaMatch;