Open wingmeng opened 4 years ago
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; }
// 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; }
// 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); }
题目:
我的回答:
第 1 题:
第 2 题:
第 3 题:
测试用例
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(); }); ```