zhangxinxu / quiz

小测答题收集区
536 stars 43 forks source link

JS基础测试39期 #48

Open zhangxinxu opened 5 years ago

zhangxinxu commented 5 years ago

关于HEX补全和随机生成,如下图

补充说明:第一题,#0或者0都是合法的,1位,2位,3位,6位字符串都是合法的,例如:#A -> #aaaaaa,或者 a -> #aaaaaa;

每题积分:3+2+3

答题前不要看别人回答,答题后可以,但不能修改自己回答

大家提交回答的时候,注意缩进距离,起始位置从左边缘开始;另外,github自带代码高亮,所以请使用下面示意的格式(1积分)。

```js
// 你的JS代码写在这里
 ```

其它:

  1. 首位答题者可获得直播翻牌机会;
  2. 本次答疑直播为10月26日上午10:00,和上一期CSS小测一起,大约50分钟;
XboxYan commented 5 years ago
//1.
function colorPad(color) {
    var reg = /^#?([0-9a-f]{1,3}|[0-9a-f]{6})$/i;
    if (reg.test(color)) {
        return color.replace(reg, function (all, $1) {
            var hex = '';
            if ($1.length === 3) {
                hex = $1.split('').map(function (el) {
                    return el.repeat(2);
                }).join('')
            } else {
                hex = $1.repeat(6 / $1.length);
            }
            return '#' + hex.toLowerCase();
        })
    } else {
        return '#000000'
    }
}

colorPad('0')
colorPad('3')
colorPad('#0')
colorPad('#3')
colorPad('#f1')
colorPad('#f1f')
colorPad('#f1f1F2')
colorPad('f1f1F2')
colorPad('#m1f1F2')
colorPad('#f1f1f26')

//2.
function colorRadom() {
    return '#' + (~~(Math.random() * 0xffffff)).toString(16).padStart(6,'0');
}

colorRadom();

//3.
// Q版的我:xboxyan的随机函数不会出现最大的值
function colorRange(a, b) {
    var color1 = colorPad(a);
    var color2 = colorPad(b);
    var min = parseInt((color1 > color2 ? color2 : color1).slice(1), 16);
    var max = parseInt((color1 > color2 ? color1 : color2).slice(1), 16);
    return '#' + (min + ~~(Math.random() * (max - min))).toString(16).padStart(6,'0');
}

colorRange('#211', '#2f2333');
ziven27 commented 5 years ago
var colorPad = function (color) {
    var result = color.replace(/#/, "").toLowerCase();
    for (var i = 0; i < result.length; i++) {
        // 如果有一个数字超过16的就返回黑色
        if (!(parseInt(result[i], 16) < 16)) {
            return '#000000';
        }
    }
    var resultLength = result.length;
    if (resultLength === 6) {
        return '#' + result;
    } else if (resultLength === 2) {
        return '#' + result + result + result;
    } else if (resultLength === 3) {
        return '#' + result[0] + result[0] + result[1] + result[1] + result[2] + result[2];
    } else if (resultLength === 1) {
        // 这里是补充的
        return '#' + result + result + result + result + result + result;
    }
    return '#000000';
};
console.log(
    '第一题: ',
    colorPad('0'),
    colorPad('#0'),
    colorPad('AF'),
    colorPad('#fc0'),
    colorPad('#936ce'),
    colorPad('#936cef'),
    colorPad('#DEFGHI')
);

var getRandomHEX = function () {
    var result = '#';
    var randomArray = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
    for (var i = 0; i < 6; i++) {
        var randNum = Math.floor(Math.random() * 16);
        result += randomArray[randNum];
    }
    return result;
};
console.log('第二题: ', getRandomHEX());

//zxx: 测试不通过,本题无分
var colorRange = function (startInput, endInput) {
    var randomArray = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
    var result = '#';
    var start = colorPad(startInput);
    var end = colorPad(endInput);
    for (var i = 1; i < 7; i++) {
        var randomIndex1 = randomArray.indexOf(start[i]);
        var randomIndex2 = randomArray.indexOf(end[i]);
        if (randomIndex1 > randomIndex2) {
            var randomIndex = randomIndex2 + Math.floor(Math.random() * (randomIndex1 - randomIndex2 + 1));
        } else {
            var randomIndex = randomIndex1 + Math.floor(Math.random() * (randomIndex2 - randomIndex1 + 1));
        }
        result += randomArray[randomIndex];
    }
    return result;
};
console.log('第三题: ', colorRange('fc0', '#ffcc02'));
Seasonley commented 5 years ago
//1
function colorPad(str) {
  var flag,
    ans = ("" + str).replace(/^#?([0-9A-Fa-f]{1,6})$/, (_, v) => {
      flag = [1, 2, 3, 6].includes(v.length) && 6 / v.length;
      return (
        (v.length === 3 && v.split("").reduce((a, c) => a + c + c, "")) ||
        (flag && v.repeat(flag))
      );
    });
  return `#${flag ? ans.toLowerCase() : "000000"}`;
}
// console.assert(colorPad("0") === "#000000");
// console.assert(colorPad("#0") === "#000000");
// console.assert(colorPad("AF") === "#afafaf");
// console.assert(colorPad("#fc0") === "#ffcc00");
// console.assert(colorPad("#936c") === "#000000");
// console.assert(colorPad("#936ce") === "#000000");
// console.assert(colorPad("#936cef") === "#936cef");
// console.assert(colorPad("#DEFGHI") === "#000000");

//3
function colorRange(a, b) {
  var _color2Int = str => parseInt(colorPad(str).slice(1), 16);
  var _random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
  return (
    "#" +
    _random(_color2Int(a), _color2Int(b))
      .toString(16)
      .padStart(6, "0")
  );
}
// console.assert(/#ffcc0[0|1|2]/.test(colorRange("#fc0", "#ffcc02")));

//2
console.log(colorRange("0", "f"));
notzheng commented 5 years ago

const randomRGB = (min, max) => (Math.floor(Math.random() * (max + 1 - min)) + min).toString(16).padStart(2, '0');

// 均未做参数校验

// T1
function hexColorPad(input, withStart = true) {
    const hexRegex = /^#?[0-9a-fA-F]{1,6}/

    const defaultColor = withStart ? '#000000' : '000000';
    const start = withStart ? '#' : '';

    if (!hexRegex.test(input)) {
        return defaultColor;
    }

    input = input.toLowerCase();
    if (input.startsWith('#')) {
        input = input.substring(1);
    }

    switch (input.length) {
        case 1:
            return start + input.repeat(6);
        case 2:
            return start + input.repeat(3);
        case 3:
            let result = start;
            for (let i = 0; i < 3; i++) {
                result += (input[i] + input[i])
            }
            return result;
        case 4:
        case 5:
            return defaultColor;
        case 6:
            return start + input;
        default:
            break;
    }
}

// T3
function colorRange(a, b) {
    const matchRegex = /.{1,2}/g;
    const hexToOct = i => Number(parseInt(i, 16).toString(10))
    a = hexColorPad(a, false);
    b = hexColorPad(b, false);
    const [aR, aG, aB] = a.match(matchRegex).map(hexToOct);
    const [bR, bG, bB] = b.match(matchRegex).map(hexToOct);
    return `#${randomRGB(aR, bR)}${randomRGB(aG, bG)}${randomRGB(aB, bB)}`;
}

// T2
function randomHexColor() {
    return colorRange('#000000','#ffffff');
}
livetune commented 5 years ago
// 1.
function colorPad(str = '') {
  str = str.toLowerCase()
  const reg = str.match(/^(?:#)?([0-9a-f]+)$/)
  if (!reg) {
    return '#000000'
  }
  str = reg[1]
  if (str.length === 1 || str.length === 2) {
    return '#'.padEnd(7, str)
  } else if (str.length === 3) {
    return '#' + str.split('').reduce((res, v) => res + v + v, '')
  } else if (str.length === 6) {
    return '#' + str
  }
  return '#000000'
}
console.log(colorPad('0!?=')) // #000000 不合法
console.log(colorPad('#a')) // #aaaaaa 重复a
console.log(colorPad('AF')) // #afafaf 重复af
console.log(colorPad('#fc0')) // #ffcc00 重复fc0
console.log(colorPad('#936c')) // #000000 不合法
console.log(colorPad('#93ecee')) // #93ecee 合法

// 2.
function randomHex() {
  return ('#' + (Math.random() * 0x1000000 | 0).toString(16)).padEnd(7, 0)
}
console.log(randomHex())

// 3.

function range(a, b) {
  const hexa = colorPad(a).replace('#', '0x')
  const hexb = colorPad(b).replace('#', '0x')
  const random = Math.min(hexa, hexb) + ((Math.random() * (Math.abs(hexa - hexb) + 1)))
  return '#' + (random >> 0).toString(16).padEnd(6, 0)
}
console.log(range('#fc0', '#ffcc02'))
Despair-lj commented 5 years ago
// 1
// zxx: 测试没通过
function colorPad(color) {
 color = color.replace(/^#?(\w{1,2})$/, function(match, p1) {
    var repeatNum = p1.length === 1 ? 6 : 3;
    return '#' + p1.repeat(repeatNum);
  });
  var div = document.createElement('div');
  div.style.backgroundColor = color;
  document.body.appendChild(div);
  var rgb = window.getComputedStyle(div).backgroundColor;
  document.body.removeChild(div);
  rgb = rgb.split(',').length === 4 ? 'rgb(0, 0, 0)' : rgb;
  // rgb 2 hex
  rgb = rgb
    .substr(4)
    .split(')')[0]
    .split(',');

  var r = (+rgb[0]).toString(16).padStart(2, '0');
  var g = (+rgb[1]).toString(16).padStart(2, '0');
  var b = (+rgb[2]).toString(16).padStart(2, '0');

  return '#' + r + g + b;
}
// 2
function randomHex() {
  var random = Math.random() * (1 << 24);
  var intRandom = ~~random;
  var color = intRandom.toString(16).padStart(6, 0);
  return '#' + color;
}
// 3
// zxx: 测试没通过
function colorRange(a, b) {
  var aHex = parseInt(colorPad(a).substr(1), 16);
  var bHex = parseInt(colorPad(b).substr(1), 16);

  var max = Math.max(aHex, bHex);
  var min = Math.min(aHex, bHex);

  var randomColor =
    '#' +
    (Math.floor(Math.random() * (max - min + 1)) + min)
      .toString(16)
      .padStart(6, 0);

  return randomColor;
}
wingmeng commented 5 years ago

第 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(); }); ```
NeilChen4698 commented 5 years ago
  1. var colorPad = function(color) {
    if (typeof color === 'string' && !!color && color !== '#') {
        color = color.toLowerCase().replace(/^#/, '');
        if (!/[^a-f0-9]/.test(color) && (color.length <= 3 || color.length === 6)) {
            switch(color.length) {
                case 3:
                    return '#' + color.replace(/([a-f0-9])/g, '$1$1');
                case 6:
                    return '#' + color;
                default:
                    return '#' + new Array((6 / color.length) + 1).join(color);
            }
        }
    }
    return '#000000';
    }
  2. var generateRandomColor = function() {
    var color = '#';
    for (var i = 0; i < 3; i++) {
        var r = Math.floor(Math.random() * 256).toString(16);
        color += (r.length === 1 ? ('0' + r) : r);
    }
    return color;
    }
  3. var colorRange = function(a, b) {
    a = colorPad(a).slice(1);
    b = colorPad(b).slice(1);
    var generateRandomInRange = function(m, n) {
        m = parseInt(m, 16);
        n = parseInt(n, 16);
        min = Math.min(m, n);
        max = Math.max(m, n);
        var r = Math.floor(Math.random() * (max - min + 1) + min).toString(16);
        return r.length === 1 ? ('0' + r) : r;
    }
    var color = '#';
    for (var i = 0; i < 6; i += 2) {
        color += (generateRandomInRange(a[i] + a[i + 1], b[i] + b[i + 1]));
    }
    return color;
    }
JaimeCheng commented 5 years ago
// 1
// zxx: 3位字符时候不是直接repeat
function colorPad (str) {
  const reg = /^#?[A-Fa-f0-9]{1,6}$/g
  if (reg.test(str)) {
    str = str.replace('#', '')
    if (str.length === 1) {
      return '#' + str.repeat(6).toLowerCase()
    } else if (str.length === 2) {
      return '#' + str.repeat(3).toLowerCase()
    } else if (str.length === 3) {
      return '#' + str[0].repeat(2) + str[1].repeat(2) + str[2].repeat(2)
    } else if (str.length === 6) {
      return '#' + str.toLowerCase()
    } else {
      return '#000000'
    } 
  } else {
    return '#000000'
  }
}
// 2
var getRandomColor = function () {
  return '#' + (Math.random() * 0xffffff << 0).toString(16);
}
// 3 转10进制 -> 求随机数 -> 转16进制 -> 不足6位补0
function colorRange (start, end) {
  start = parseInt(colorPad(start).split('#')[1], 16)
  end = parseInt(colorPad(end).split('#')[1], 16)
  const randomNum = Math.floor(Math.random() * (end - start + 1) + start)
  const res = randomNum .toString(16)
  return '#' + '0'.repeat(6 - res.length) + res
}
// test
console.log(
  '1. \n',
  '0 => ' + colorPad('A') + '\n',
  '#0 => ' + colorPad('#0') + '\n',
  'AF => ' + colorPad('AF') + '\n',
  '#fc0 => ' + colorPad('#fc0') + '\n',
  '#936c => ' + colorPad('#936c') + '\n',
  '#936ce => ' + colorPad('#936ce') + '\n',
  '#936cef => ' + colorPad('#936cef') + '\n',
  '#936cefd => ' + colorPad('#936cefd') + '\n',
  '#DEFGHI => ' + colorPad('#DEFGHI')
)
console.log(getRandomColor())
console.log(colorRange('#fc0', '#ffcc02'))
console.log(colorRange('#0', '#000002'))
guqianfeng commented 5 years ago
// 题1题3 大量测试不通过
    {
        let colorPad = (str) => {
            let reg = /^#([0-9a-f]{6}|[0-9a-f]{3})$/i;
            let specialReg = /^[0-9a-f]{2}$/i;
            if(reg.test(str)){
                return str.replace(reg, (all, $1) => {
                    $1 = $1.length === 6 ? $1 : [...$1].map(item => item.repeat(2)).join("");
                    return "#" + $1.toLowerCase();
                });
            }else if(specialReg.test(str)){
                return "#" + str.toLowerCase().repeat(3);
            }else{
                return "#" + '0'.repeat(6);
            }
        };

        console.log(colorPad("0"));
        console.log(colorPad("#0"));
        console.log(colorPad("AF"));
        console.log(colorPad("#fc0"));
        console.log(colorPad("#936c"));
        console.log(colorPad("#936c"));
        console.log(colorPad("#936cef"));
        console.log(colorPad("DEFGHI"));

        const {random} = Math;
        let randomColor = () => "#" + (random() * 0xffffff | 0).toString(16).padStart(6, 0);

        console.log(randomColor());

        let colorRange = (a, b) => {
            let [min, max] = [parseInt(colorPad(a).substr(1), 16), parseInt(colorPad(b).substr(1), 16)];
            if(max < min){
                [min, max] =[max, min];
            }
            return "#" + (random() * (max - min + 1) + min | 0).toString(16).padStart(6, 0);
        };

        console.log(colorRange("#fc0", "#ffcc02"));
    }
frankyeyq commented 5 years ago

1.

//zxx: 没有转小写
function colorPad(hex) {
    hex = String(hex).startsWith('#') ? hex.slice(1) : hex
    let isIllegal = hex.split('').some(str => {
        return isNaN(parseInt(str, 16))
    })
    if (isIllegal) return '#000000'
    if (hex.length === 1) {
        return '#' + hex.repeat(6).toLowerCase()
    } else if (hex.length === 2) {
        return '#' + hex.repeat(3).toLowerCase()
    } else if (hex.length === 3) {
        return '#' + hex.split('').map(str => str.repeat(2)).join('')
    } else if (hex.length === 6) {
        return '#' + hex
    } else {
        return '#000000'
    }
}

2.

function randomHex() {
    let hex = ''
    for(let i = 0;i < 6; i++) {
        let item = Math.round(Math.random() * 15)
        hex += item.toString(16)
    }
    return colorPad(hex)
}

3.

//zxx: 前面没补0
function colorRange(a, b) {
    let a10 = parseInt(colorPad(a).slice(1), 16)
    let b10 = parseInt(colorPad(b).slice(1), 16)
    let min, max
    if (a10 < b10) {
        min = a10
        max = b10
    } else {
        min = b10
        max = a10
    }
    let hex10 = Math.round(Math.random() * (max - min) + min)
    let hex16 = hex10.toString(16)
    return '#' + hex16
}
theDrunkFish commented 5 years ago

题目1

function colorPad (str) {
  if(typeof str !== 'string') return '#000000';

  var reg = /^#?([0-9a-f]{1,3}|[0-9a-f]{6})$/i;
  var matchInfo = str.match(reg);

  str = matchInfo ? matchInfo[1] : '000000';

  if(str.length === 3){
    str = str.replace(/([0-9a-f])/ig, '$1$1');
  }

  return '#' + str.padEnd(6, str).toLowerCase();
}

题目2

function getRandomInt(min, max){
  if(min > max){
    [min, max] = [max, min];
  }
  return Math.floor(Math.random() * (max - min + 1) + min);
}

function getRandomHEX(min = 0, max = 0xffffff){
  return '#' + getRandomInt(min, max).toString(16).padStart(6, '0');
}

console.log(getRandomHEX())

题目3

function colorRange(a, b){
  a = parseInt(colorPad(a).slice(1), 16);
  b = parseInt(colorPad(b).slice(1), 16);

  return getRandomHEX(a, b);
}

console.log(colorRange('#fc0','#ffcc02'))
liyongleihf2006 commented 5 years ago
//第一题
console.log(colorPad('0'));
console.log(colorPad('#0'));
console.log(colorPad('AF'));
console.log(colorPad('#fc0'));    //zxx: 3位时候应该是AABBCC重复
console.log(colorPad('#936c'));
console.log(colorPad('#936ce'));
console.log(colorPad('#936cef'));
console.log(colorPad('#DEFGHI'));
function colorPad(color=""){
    color = color.replace(/^#/,'').toLowerCase();
    if(!/^[0-9a-f]+$/.test(color)){
        return '#000000'
    }
    var length = color.length;
    color = color.repeat(6/length);
    if(color.length===6){
        return `#${color}`;
    }else{
        return '#000000'
    }
}
//第二题
console.log(randomHEX());
function randomHEX(){
    return "#"+getRandom()+getRandom()+getRandom();
    function getRandom(){
        return parseInt(Math.random()*0xff).toString(16)
    }
}
//第三题
console.log(colorRange("#000","#222"))
console.log(colorRange("a","c"))
function colorRange(a,b){
    var aValues = getFragments(a);
    var bValues = getFragments(b);
    var result = "#";
    for(var i = 0;i<3;i++){
        result+=getRandom(aValues[i],bValues[i]);
    }
    return result;
    function getFragments(color){
        return colorPad(color)
        .replace('#','')
        .replace(/(?!^)(?=(\w{2})+$)/g,',')
        .split(',')
        .map(item=>new Number(`0x${item}`).valueOf())
    }
    function getRandom(aValue,bValue){
        var value = Math.abs(aValue-bValue)*Math.random();
        value+=Math.min(aValue,bValue);
        value = parseInt(value).toString(16);
        if(value.length===1){
            return `0${value}`
        }
        return value;
    }
}
magiconch commented 5 years ago
// zxx: 测试一片红
// 1.
function colorPad (colorString) {
    if (colorString[0] === '#') {
        colorString.slice(1, colorString.length);
    }
    let returnValue: string;
    if (colorString.match(/^[0-9A-Fa-f]{1,3}$|^[0-9A-Fa-f]{6}$/)) {
        returnValue = '000000';
    }
    if (colorString.length === 1) {
        returnValue = + colorString + colorString + colorString + colorString + colorString + colorString;
    }
    if (colorString.length === 2) {
        returnValue = colorString + colorString + colorString;
    }
    if (colorString.length === 3) {
        returnValue = colorString[0] + colorString[0] + colorString[1] + colorString[1] + colorString[2] + colorString[2];
    }
    return '#' + returnValue.toLowerCase();
}

function getRandomIntInclusive(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

// 2.
function ColorRandom() {
    return '#' + getRandomIntInclusive(0, parseInt('ffffff',16)).toString(16).padStart(6, '0');
}

// 3.
function ColorRange(a, b) {
    let a = colorPad(a).slice(1, a.length);
    let b = colorPad(b).slice(1, b.length);
    return '#' + getRandomIntInclusive(parseInt('ffffff',16), parseInt('ffffff',16)).toString(16).padStart(6, '0');
}
juzhiqiang commented 5 years ago
第一题
function colorPad(hex){
    var hexs = hex.toLocaleLowerCase();
    var str = hexs.replace( /(^#)/i,'');
    //优先排除不正常
    if(!/^[0-9A-F]{1,6}$/i.test(str)) return '#000000';

    if(/(^[0-9A-F]{1}$)/i.test(str)) return '#'+str+str+str+str+str+str;

    if(/(^[0-9A-F]{2}$)/i.test(str)) return '#'+str+str+str;

    if(/(^[0-9A-F]{3}$)/i.test(str)) return '#' + str.replace(/[0-9A-F]/ig,function(a){
        return a + a
     })

    if(/(^[0-9A-F]{6}$)/i.test(str)) return '#'+str;

    return '#000000';   

}

第二题
function  randomHex(){
      function next(color){
           color +=  '0123456789abcdef'[Math.floor(Math.random()*16)];
          return color.length == 6 ?  color : next(color); 
      }

      return  '#' + next('');
}

// 第三题
// zxx: 此算法大大的有问题
function colorRange(a,b){
  var str = '0123456789abcdef';
  var  aColor =  colorPad(a).match(/[0-9A-F]/ig);
  var  bColor = colorPad(b).match(/[0-9A-F]/ig);
  var  newHex = '';
  for(var i=0;i<6;i++){
        var arrs = aColor[i] < bColor[i] ?  [aColor[i],bColor[i]] :[bColor[i],aColor[i]];
    var strs = str.substring(str.indexOf(arrs[0]),str.indexOf(arrs[1])+1);
    newHex += strs[Math.floor(Math.random()*(strs.length))];
    }
    return newHex;

}
colorRange('#fc0','#ffcc02')
asyncguo commented 5 years ago

第一题

//zxx: 2字符平铺规则个题意不符合
function colorPad(x) {
    x = x.replace(/#/g, '')
    let len = x.length
    // 非正确十六进制或长度不对,直接返回黑色
    if (isNaN(Number(`0x${x}`)) || len < 1 || (len > 3 && len !== 6)) return '#000000'

    x = x.split('').map(v => v.repeat(6 / len)).join('')

    return `#${x.toLowerCase()}`
};

console.log(colorPad('0'));
console.log(colorPad('#0'));
console.log(colorPad('AF'));
console.log(colorPad('#fc0'));
console.log(colorPad('#936c'));
console.log(colorPad('#936ce'));
console.log(colorPad('#936cef'));
console.log(colorPad('#DEFGHI'));

第二题

// 1. 通过random随机数截取
function getHex() {
  return `#${Math.random().toString(16).slice(2, 8).padStart(6, 0)}`
}
// 2. 通过两数之前的随机数实现
function getHex1() {
  let min = 0, max = 0xffffff
  let randomNumber = Math.floor(Math.random() * (0xffffff - 0 + 1)) + min

  return `#${randomNumber.toString(16).padStart(6, 0)}`
}
console.log(getHex())
console.log(getHex1())

第三题

// zxx:测试不通过
function colorRange(a, b) {
  a = colorPad(a).replace(/#/g, '')
  b = colorPad(b).replace(/#/g, '')

  let a_16 = Number(`0x${a}`)
  let b_16 = Number(`0x${b}`)

  let diff_16 = Math.abs(a_16 - b_16)
  let result = ''

  result = a_16 + Math.ceil(Math.random() * diff_16)

  return `#${result.toString(16)}`
}

console.log(colorRange('#fc0', '#ffcc02'))
lifelikejuly commented 5 years ago

console.log(colorPad("0")); console.log(colorPad("#0")); console.log(colorPad("AF")); console.log(colorPad("#fc0")); console.log(colorPad("#936c")); console.log(colorPad("#936ce")); console.log(colorPad("#936cef")); console.log(colorPad("#DEFGHI"));

* 第二题
```js
function getRadomColorValue() {
    var value = "#";
    for (var n = 0; n < 6; n++) { //取每一位数值0-16转16进制
        value += Math.floor(Math.random() * 16).toString(16);
    }
    return value;
}

console.log(getRadomColorValue());

console.log(colorRange("#101010", "#101212"));

les-lee commented 5 years ago
// 使用了一些笨方法

    // 1.
//zxx: 没对超出f的字符做处理
    function colorPad(colorStr) {
      colorStr = colorStr.toLowerCase()
      var defaultColor = '#000000'
      if (!(/(^#[0-9a-f]{1,6}$)|([0-9a-f]{1,6}$)/ig.test(colorStr))) {
        return defaultColor
      }
      switch (colorStr.length) {
        case 1:
          if (colorStr.startsWith('#')) {
            return defaultColor
          } else {
            return `#${colorStr}${colorStr}${colorStr}${colorStr}${colorStr}${colorStr}`
          }
          break
        case 2:
          if (colorStr.startsWith('#')) {
            var c = colorStr.substring(1)
            return `#${c}${c}${c}${c}${c}${c}`
          } else {
            return `#${colorStr}${colorStr}${colorStr}`
          }
          break
        case 3:
          if (colorStr.startsWith('#')) {
            var c = colorStr.substring(1)
            return `#${c}${c}${c}`
          } else {
            return `#${colorStr}${colorStr}`
          }
          break
        case 4:
          if (colorStr.startsWith('#')) {
            var c = colorStr.substring(1)
            return `#${c[0]}${c[0]}${c[1]}${c[1]}${c[2]}${c[2]}`
          } else {
            return defaultColor
          }
          break
        case 6:
          if (colorStr.startsWith('#')) {
            return defaultColor
          } else {
            return `#${colorStr}`
          }
          break
        case 7:
          if (colorStr.startsWith('#')) {
            return colorStr
          }
          break
        default:
          return defaultColor
      }

    }
    // test 1 
    console.log(colorPad('0'))
    console.log(colorPad('#0'))
    console.log(colorPad('AF'))
    console.log(colorPad('#fc0'))
    console.log(colorPad('#936c'))
    console.log(colorPad('#936ce'))
    console.log(colorPad('#936cef'))
    console.log(colorPad('#DEFGHI'))

    // 2

    function randomHexColor() {
      var hexArr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']

      return '#' + hexArr[Math.floor(Math.random() * hexArr.length)] +
        hexArr[Math.floor(Math.random() * hexArr.length)] +
        hexArr[Math.floor(Math.random() * hexArr.length)] +
        hexArr[Math.floor(Math.random() * hexArr.length)] +
        hexArr[Math.floor(Math.random() * hexArr.length)] +
        hexArr[Math.floor(Math.random() * hexArr.length)]
    }

    // test 2
    console.log('------------------------------------------')
    console.log(randomHexColor())
    console.log(randomHexColor())
    console.log(randomHexColor())

    // 3
//zxx: 算法有问题
    function colorRange(a, b) {
      a = colorPad(a).substring(1)
      b = colorPad(b).substring(1)
      var hexArr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
      return '#' + Array.from(a).map((element, index) => {
        var aRange = hexArr.indexOf(element)
        var bRange = hexArr.indexOf(b[index])
        if (aRange < bRange) {
          return hexArr[Math.floor(aRange + Math.random() * (bRange - aRange + 1))]
        } else if (aRange == bRange) {
          return element
        } else {
          return hexArr[Math.floor(bRange + Math.random() * (aRange - bRange + 1))]
        }
      }).join('');
    }

    // test 3
    console.log('-------------------------------------')
    console.log(colorRange('#fc0', '#ffcc02'))
    console.log(colorRange('#fc0', '#ffcc02'))
    console.log(colorRange('#fc0', '#ffcc02'))
zy017 commented 5 years ago
// 1
function colorPad(s) {
  s = String(s)
  if (!s) {
    return '#000000'
  }
  if (/^#?[A-Fa-f0-9]{1,2}$/.test(s)) {
    let s1 = s.replace('#', '')
    let len = 6 / s1.length
    return '#' + s1.toLowerCase().repeat(len)
  }
  if (/^#?[A-Fa-f0-9]{3}$/.test(s)) {
    let s1 = s.replace('#', '')
    return '#' + s1.toLowerCase().replace(/[a-f0-9]/g, i => i + i)
  }
  if (/^#?[A-Fa-f0-9]{6}$/.test(s)) {
    let s1 = s.replace('#', '')
    return '#' + s1.toLowerCase()
  }
  return '#000000'
}
// 测试1
console.log('-------------------------test 1----------------------------')
console.log(colorPad('0') === '#000000')
console.log(colorPad('#0') === '#000000')
console.log(colorPad('AF') === '#afafaf')
console.log(colorPad('#fc0') === '#ffcc00')
console.log(colorPad('#936c') === '#000000')
console.log(colorPad('#936ce') === '#000000')
console.log(colorPad('#936cef') === '#936cef')
console.log(colorPad('#DEFGHI') === '#000000')

// 2
function getRandomHEX() {
  let s = '0123456789ABCDEF'
  let hex = '#'
  for (let i = 0; i < 6; i++) {
    let index = Math.floor(Math.random() * 16)
    hex += s[index]
  }
  return hex
}
// 测试 2
console.log('-------------------------test 2----------------------------')
console.log(getRandomHEX())
// 3
// zxx: 算法有问题
function colorRange(a, b) {
  let s = '0123456789abcdef'
  a = colorPad(a)
  b = colorPad(b)
  let hex = '#'
  for (let i = 0; i < 6; i++) {
    let c = parseInt(a[i + 1], 16)
    let d = parseInt(b[i + 1], 16)
    let min = Math.min(c, d)
    let max = Math.max(c, d)
    let index = Math.floor(Math.random() * (max - min + 1)) + min
    hex += s[index]
  }
  return hex
}

// 测试3
console.log('-------------------------test 3----------------------------')
for (let i = 0; i < 6; i++) {
  console.log(colorRange('#fc0', '#ffcc02'))
}
fzpijl commented 5 years ago
// 1.
// zxx: 1位字符有问题
function colorPad(hex) {
    var reg = /^#*[0-9a-f]{0,6}$/i
    if(!reg.test(hex)){
        return '#000000'
    }
    if(hex.indexOf('#') > -1 ){
        hex = hex.slice(1)
    }
    switch(hex.length){
        case 1:
            hex = hex + hex + hex + hex + hex + hex;
        case 2:
            hex = hex + hex + hex;
            break;
        case 3:
            hex = hex.split('').map(s => s+s).join('');
            break;
        case 6:
            break;
        default:
            hex = '000000'
    }
    return '#' +  hex.toLowerCase();
}
// 2.
// zxx:没有补0
function rand256(){
    return Math.round(Math.random() * 256);
}
function randHex(){
    return '#' + rand256().toString(16) + rand256().toString(16) + rand256().toString(16);
}
// 3.
// zxx:没有补0
function colorRange(a, b){
    a = parseInt(colorPad(a).slice(1), 16);
    b = parseInt(colorPad(b).slice(1), 16);
    var value = Math.round(Math.random() * (b - a)) + a;
    return '#' +  value.toString(16)
}
GCGligoudan commented 5 years ago

第一题:

function colorPad(color) {
  let colorResult;
  if (color.slice(0, 1) === '#') {
    color = color.slice(1);
  }
  if (color.length === 1) {
    colorResult = color + color + color + color + color + color;
  } else if (color.length === 2) {
    colorResult = color + color + color;
  } else if (color.length === 3) {
    let n1 = color.slice(0, 1);
    let n2 = color.slice(1, 2);
    let n3 = color.slice(2, 3);
    colorResult = n1 + n1 + n2 + n2 + n3 + n3;
  } else if (color.length === 6) {
    colorResult = color;
  } else {
    colorResult = '000000';
  }
  colorResult = `#${colorResult.toLowerCase()}`;
  if (!/^#([0-9a-fA-F]{6})$/.test(colorResult)) {
    colorResult = '#000000';
  }
  return colorResult;
}

第二题:

function randomColor() {
  let randomHex = '#' + (Math.floor(Math.random() * (parseInt(0xffffff, 10)+1))).toString(16);
  if (/^#([0-9a-fA-F]{6})$/.test(randomHex)) {
    return randomHex;
  } else {
    return randomColor();
  }
}

第三题:

// zxx: 没有前面补0
function formatColor(hex) {
  let colorResult;
  if (hex.slice(0, 1) === '#') {
    hex = hex.slice(1);
  }
  if (hex.length === 1) {
    colorResult = hex + hex + hex + hex + hex + hex;
  } else if (hex.length === 2) {
    colorResult = hex + hex + hex;
  } else if (hex.length === 3) {
    let n1 = hex.slice(0, 1);
    let n2 = hex.slice(1, 2);
    let n3 = hex.slice(2, 3);
    colorResult = n1 + n1 + n2 + n2 + n3 + n3;
  } else if (hex.length === 6) {
    colorResult = hex;
  }
  return `${colorResult.toLowerCase()}`;
}

// 假设a,b都是合法的hex值
function colorRange(a, b) {
  a = formatColor(a);
  b = formatColor(b);
  let hexAVal = parseInt('0x'+a, 16);
  let hexBVal = parseInt('0x'+b, 16);
  let randomColor;
  if (hexAVal > hexBVal) {
    randomColor = Math.round(Math.random() * (hexAVal - hexBVal)) + hexBVal;
  } else {
    randomColor = Math.round(Math.random() * (hexBVal - hexAVal)) + hexAVal;
  }
  return `#${randomColor.toString(16)}`;

}
colorRange('#fc0', '#ffcc02');
rayj1993 commented 5 years ago
// 不太会

// 第一题
//zxx: 2位重复规则有问题
function colorPad(str) {
    var len = str.replace(/^#/, '').length;
    var colorStr = str.replace(/^#/, '').toLowerCase();
    // 补全数值
    switch (len) {
        case 1:
            var i = 0
            while (i < 5) {
                colorStr = colorStr + colorStr;
                i++;
            }
            case 2:
                var arr = colorStr.split('');
                colorStr = arr[0] + arr[0] + arr[0] + arr[1] + arr[1] + arr[1];
                break;
            case 3:
                var arr = colorStr.split('');
                colorStr = arr[0] + arr[0] + arr[1] + arr[1] + arr[2] + arr[2];
                break;
            case 6:
                break;
            default:
                return '#000000';
                break;
    }
    var colorStr = '#' + colorStr;
    // 判断hex是否合法
    var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    if (reg.test(colorStr)) {
        return colorStr;
    } else {
        return '#000000';
    }
}
var num = 255;
num.toString(16);
console.log(colorPad('0'));
console.log(colorPad('#0'));
console.log(colorPad('AF'));
console.log(colorPad('#fc0'));
console.log(colorPad('#936c'));
console.log(colorPad('#936ce'));
console.log(colorPad('#936cef'));
console.log(colorPad('#DEFGHI'));

// 第二题

function randomHex() {
    var sColorChange = [Math.round(Math.random() * 255), Math.round(Math.random() * 255), Math.round(Math
        .random() * 255)]
    var str = "RGB(" + sColorChange.join(",") + ")";
    var that = str;
    //十六进制颜色值的正则表达式
    var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    // 如果是rgb颜色表示
    if (/^(rgb|RGB)/.test(that)) {
        var aColor = that.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
        var strHex = "#";
        for (var i = 0; i < aColor.length; i++) {
            var hex = Number(aColor[i]).toString(16);
            if (hex.length < 2) {
                hex = '0' + hex;
            }
            strHex += hex;
        }
        if (strHex.length !== 7) {
            strHex = that;
        }
        return strHex;
    } else if (reg.test(that)) {
        var aNum = that.replace(/#/, "").split("");
        if (aNum.length === 6) {
            return that;
        } else if (aNum.length === 3) {
            var numHex = "#";
            for (var i = 0; i < aNum.length; i += 1) {
                numHex += (aNum[i] + aNum[i]);
            }
            return numHex;
        }
    }
    return that;
};
console.log(randomHex());

// 第三题不会,不理解这个区间怎么产生
sghweb commented 5 years ago

写了个简单测试的 demo

// 第一题

function colorPad(str) {
  if (str.indexOf("#") == 0) {
    str = str.split("#")[1]
  }
  str = str.toLowerCase()
  let patter1 = /^[0-9a-f]$/i
  let patter2 = /^[0-9a-f]{2}$/i
  let patter3 = /^[0-9a-f]{3}$/i
  let patter6 = /^[0-9a-f]{6}$/i
  if (patter1.test(str)) {
    str = '#' + str.repeat(6)
  } else if (patter2.test(str)) {
    str = '#' + str.repeat(3)
  } else if (patter3.test(str)) {
    str = '#' + str.replace(/([0-9a-f])/g, '$1$1')
  } else if (patter6.test(str)) {
    str = '#' + str
  } else {
    str = '#000000'
  }
  return str
}

// 第二题
function mnd(a) {
  for (let i = a.length; i; i--) {
    let j = Math.floor(Math.random() * i);
    [a[i - 1], a[j]] = [a[j], a[i - 1]];
  }
  return a;
}
let hexArr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
function mndHex(len) {
  let hex = '#'
  for (var i = 0; i < len; i++) {
    hex += mnd(hexArr)[i]
  }
  return hex
}

// 第三题
//zxx: 测试没通过
function colorRange(min, max) {
  min = colorPad(min)
  max = colorPad(max)
  let hexMnd = mndHexRange(6,min,max)
  return hexMnd
}
function cloneArr(arr,min,max) {
  let copyArr = JSON.parse(JSON.stringify(arr))
  for (var i = copyArr.length - 1; i >= 0; i--) {
    if (copyArr[i] < min || copyArr[i] > max) {
      copyArr.splice(i, 1)
    }
  }
  return copyArr
}
function mndHexRange(len, min,max) {
  let hex = '#'
  for (var i = 0; i < len; i++) {
    if(hex==min.slice(0,i+1)||hex==max.slice(0,i+1)){
      let strArr = mnd(cloneArr(hexArr,min.charAt(i+1),max.charAt(i+1)))
      hex += strArr[i]?strArr[i]:strArr[0]
    }else {
      hex += mnd(hexArr)[i]
    }
  }
  return hex
}
xxf1996 commented 5 years ago
//zxx:  虽然代码多,但是执行没有任何问题
// 第一题
/**
 * 补全hex颜色值
 * @param {string} str hex颜色值
 */
function colorPad (str) {
  let isValid = true
  let hex = '#000000'
  let checkStr = str

  // 判断字符的有效性
  if (typeof str !== 'string' || str.length > 7 || str.length === 0) {
    isValid = false
  } else {
    if (str[0] === '#') {
      checkStr = str.substring(1)
    }
    if ([1, 2, 3, 6].indexOf(checkStr.length) !== -1) {
      checkStr = checkStr.toLowerCase()
      if (/[^\da-f]/.test(checkStr)) {
        isValid = false
      }
    } else {
      isValid = false
    }
  }

  if (isValid) {
    switch (checkStr.length) {
      case 1:
        hex = `#${checkStr.repeat(6)}`
        break
      case 2:
        hex = `#${checkStr.repeat(3)}`
        break
      case 3:
        let r = checkStr[0].repeat(2)
        let g = checkStr[1].repeat(2)
        let b = checkStr[2].repeat(2)
        hex = `#${r}${g}${b}`
        break
      case 6:
        hex = `#${checkStr}`
        break
      default:
        break
    }
  }

  return hex
}

// 第二题
/**
 * 获取一个随机的hex颜色值
 */
function randomColor () {
  let getHex = () => {
    let hex = Math.floor(Math.random() * 16)
    return hex.toString(16) // 转16进制
  }

  let color = '#'

  for (let i = 0; i < 6; i++) {
    color += getHex()
  }

  return color
}

// 第三题
/**
 * 获取一个介于a,b之间的随机颜色
 * @param {string} a hex颜色值
 * @param {string} b hex颜色值
 */

// Q版的我: (#000111,#00200)会出现000200以后的
function colorRange (a, b) {
  let color = '#'
  a = colorPad(a).substring(1)
  b = colorPad(b).substring(1)

  // 按两位分割,得到rgb各自的数值
  let aList = a.split(/(.{2})/).filter(item => item !== '').map(item => parseInt(item, 16))
  let bList = b.split(/(.{2})/).filter(item => item !== '').map(item => parseInt(item, 16))

  // 按两个颜色的rgb分量区间获取随机值
  aList.forEach((item, idx) => {
    let aHex = item
    let bHex = bList[idx]
    let minHex = Math.min(aHex, bHex)
    let maxHex = Math.max(aHex, bHex)
    let randomHex = aHex === bHex ? aHex : (Math.floor(Math.abs(maxHex - minHex + 1) * Math.random()) + minHex)
    let hex = randomHex.toString(16)
    if (hex.length === 1) hex = '0' + hex // 补位
    color += hex
  })

  return color
}

let testCase = [
  '0',
  '#0',
  'AF',
  '#fc0',
  '#936c',
  '#936ce',
  '936cef',
  '#DEFGHI'
]

// testCase.forEach(item => {
//   console.log(colorPad(item))
// })

第三题修正版:

/**
 * 获取一个介于a,b之间的随机颜色
 * 修正版:将hex颜色值整体看做一个数值
 * @param {string} a hex颜色值
 * @param {string} b hex颜色值
 */
function colorRange (a, b) {
  let color = '#'
  a = colorPad(a).substring(1)
  b = colorPad(b).substring(1)

  // 将hex颜色值转为十进制数值
  let aNum = parseInt(a, 16)
  let bNum = parseInt(b, 16)
  let minNum = Math.min(aNum, bNum)
  let maxNum = Math.max(aNum, bNum)
  let randomHex = aNum === bNum ? aNum : (Math.floor(Math.abs(maxNum - minNum + 1) * Math.random()) + minNum)
  let hex = randomHex.toString(16).padStart(6, '0') // 补0
  color += hex

  return color
}
silverWolf818 commented 5 years ago

测试

//第一题    
function colorpad(color) {
    var regColor = /^#?([0-9a-fA-f]{1,3}|[0-9a-fA-f]{6})$/;
    if (regColor.test(color)) {
        return color.replace(regColor, function ($1, $2) {
            var hex = "";
            if ($2.length === 1) {
                hex = $2.repeat(6);
            } else if ($2.length === 2) {
                hex = $2.repeat(3);
            }else if ($2.length === 3) {
                hex = $2.split("").map(function (item) {
                    return item.concat(item);
                }).join("");
            } else{
                hex = $2;
            }
            return "#" + hex;
        })
    } else {
        console.log("非法hex值");
        return "#000000";
    }
}

//第二题 
function randomHex(){
    var n = "0123456789abcdef";
    var arr = [];
    function r(arr){
        if(arr.length > 5){
            return false;
        }else{
            arr.push(n[Math.floor(Math.random()*16)]);
            r(arr);
        }
    }
    r(arr);
    return "#" + arr.join("");
}

//第三题 
function hexRange(a,b){
    var c1 = parseInt(colorpad(a).slice(1),16);
    var c2 = parseInt(colorpad(b).slice(1),16);
    return "#" + (Math.floor(Math.random() * (c2 - c1)) + c1).toString(16)
}

console.log(colorpad("0"));
console.log(colorpad("#f"));
console.log(colorpad("#f3"));
console.log(colorpad("#fd1312"));
console.log(colorpad("#fd112"));
console.log(randomHex());
console.log(hexRange("#fc0", "#ffcc02"));
zhangxinxu commented 5 years ago

本期要点:

  1. 题目1,3测试见:http://quiz.xiliz.com/qunit39.html 2. 优秀回答参考XboxYan。
  2. 常见错误算法:取范围的时候,依次取对应位数的范围,举例:'100' 和 '001' 之间范围的值,如果是错误算法,055是不可能取到的。而且'000'并不在范围之内,所以这是严重错误的算法。
  3. 常见错误2:没有补0,已经在代码那里备注了。
  4. HEX色值本质上是16进制的颜色表示方法。所以,如果我们要比对,可以转成10进制,如果要把数值变成HEX色值,直接转16进制就可以。JS自带很多方法,例如(200).toString(16) -> 'c8',注意前面补0,可以使用ES6 padStart()方法。
  5. 代码不精简没关系,算法小白也没关系,运行正确才是首位的。
asyncguo commented 5 years ago

第一题

//zxx: 2字符平铺规则个题意不符合
function colorPad(x) {
    x = x.replace(/#/g, '')
    let len = x.length
    // 非正确十六进制或长度不对,直接返回黑色
    if (isNaN(Number(`0x${x}`)) || len < 1 || (len > 3 && len !== 6)) return '#000000'

    x = x.split('').map(v => v.repeat(6 / len)).join('')

    return `#${x.toLowerCase()}`
};

console.log(colorPad('0'));
console.log(colorPad('#0'));
console.log(colorPad('AF'));
console.log(colorPad('#fc0'));
console.log(colorPad('#936c'));
console.log(colorPad('#936ce'));
console.log(colorPad('#936cef'));
console.log(colorPad('#DEFGHI'));

第二题

// 1. 通过random随机数截取
function getHex() {
  return `#${Math.random().toString(16).slice(2, 8).padStart(6, 0)}`
}
// 2. 通过两数之前的随机数实现
function getHex1() {
  let min = 0, max = 0xffffff
  let randomNumber = Math.floor(Math.random() * (0xffffff - 0 + 1)) + min

  return `#${randomNumber.toString(16).padStart(6, 0)}`
}
console.log(getHex())
console.log(getHex1())

第三题

// zxx:测试不通过
function colorRange(a, b) {
  a = colorPad(a).replace(/#/g, '')
  b = colorPad(b).replace(/#/g, '')

  let a_16 = Number(`0x${a}`)
  let b_16 = Number(`0x${b}`)

  let diff_16 = Math.abs(a_16 - b_16)
  let result = ''

  result = a_16 + Math.ceil(Math.random() * diff_16)

  return `#${result.toString(16)}`
}

console.log(colorRange('#fc0', '#ffcc02'))

第二题修改

function colorPad(x) {
    x = x.replace(/#/g, '')
    let len = x.length
    // 非正确十六进制或长度不对,直接返回黑色
    if (isNaN(Number(`0x${x}`)) || len < 1 || (len > 3 && len !== 6)) return '#000000'
    if (len === 2) return `#${x.repeat(3)}`
    x = x.split('').map(v => v.repeat(6 / len)).join('')

    return `#${x.toLowerCase()}`
};

第三题修改

由于之前通过ceil下取整,则对于取到0的概率会大大降低(即100次的随机取整,极大可能取不到0),会使函数随机性不均匀分分布,改为floor上取整


function colorRange(a, b) {
a = colorPad(a).replace(/#/g, '')
b = colorPad(b).replace(/#/g, '')

let a_16 = Number(0x${a}) let b_16 = Number(0x${b}) let min_16 = Math.min(a_16, b_16)

let diff_16 = Math.abs(a_16 - b_16) let result = ''

result = Math.floor(Math.random() * (diff_16 + 1)) + min_16

return #${result.toString(16). padStart(6, 0)} }