wingmeng / front-end-quiz

前端小测试答题收集
0 stars 0 forks source link

JS基础测试39:HEX 颜色处理和伪随机色 #34

Open wingmeng opened 4 years ago

wingmeng commented 4 years ago

题目:

  1. 补全hex颜色值,如 #0 或者 0 都是合法的,1位,2位,3位,6位字符串都是合法的,例如:#A -> #aaaaaa,或者 a -> #aaaaaa;
  2. 获取一个随机的hex颜色值;
  3. 获取一个介于a,b之间的随机颜色。

我的回答:

第 1 题:

function colorPad(hex) {
  const reg = /^#?([0-9a-f]{1,3}|[0-9a-f]{6})$/i;
  let result = '#' + '0'.repeat(6);

  if (reg.test(hex)) {
    result = hex.replace(reg, (_, $1) => {
      $1 = $1.toLowerCase();

      switch($1.length) {
        case 6:
          return '#' + $1;
        case 3:
          return '#' + $1.split('').map(s => s.repeat(2)).join('');
        default:
          return '#' + $1.repeat(6 / $1.length);
      }
    });
  }

  return result;
}

第 2 题:

// http://randomcolour.com/
function randomHex() {
  const range = Math.pow(16, 6) - 1;
  let color = Math.floor(Math.random() * range).toString(16);
  color = '#' + ('0'.repeat(6) + color).slice(-6);

  return color;
}

第 3 题:

// zxx: 我的测试用例测试下来有问题
function colorRange(a, b) {
  let start = parseInt(colorPad(a).substr(1), 16);
  let end = parseInt(colorPad(b).substr(1), 16);

  if (start > end) {
    [start, end] = [end, start];
  }

  return '#' + (Math.round(Math.random() * (end - start)) + start).toString(16);
}
测试用例
https://codepen.io/wingmeng/pen/MWWmbLO ```js // colorPad 测试 const testCases = [ { it: '0', expect: '#000000' }, { it: '#0', expect: '#000000' }, { it: 'a', expect: '#aaaaaa' }, { it: '#A', expect: '#aaaaaa' }, { it: 'AF', expect: '#afafaf' }, { it: '#fc0', expect: '#ffcc00' }, { it: '#936c', expect: '#000000' }, { it: '#936ce', expect: '#000000' }, { it: '#936cef', expect: '#936cef' }, { it: '#EDFGHI', expect: '#000000' } ]; testCases.map(c => { const result = colorPad(c.it); const isPassed = result === c.expect; console.group(`colorPad("${c.it}") -> "${c.expect}"`); isPassed ? console.log('%c√ Pass', 'color: green') : console.log('%c× Failed! the actual result is: ' + result, 'color: red'); console.groupEnd(); }); // 随机 hex 颜色测试 const testNumbers = 10; const hexReg = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i; [...new Array(testNumbers)].map(() => { const result = randomHex(); console.group(`randomHex() -> "${result}"`); hexReg.test(result) ? console.log('%c√ Pass', 'color: green') : console.log('%c× Failed', 'color: red'); console.groupEnd(); }); // 颜色范围测试 [...new Array(testNumbers)].map(() => { const color1 = randomHex(); const color2 = randomHex(); const result = colorRange(color1, color2); console.group(`colorRange("${color1}", "${color2}") -> "${result}"`); hexReg.test(result) ? console.log('%c√ Pass', 'color: green') : console.log('%c× Failed', 'color: red'); console.groupEnd(); }); ```