주어진 두 색상 사이에 임의의 색상을 생성하는 함수를 작성해야 합니다. 이 문제를 부분적으로 해결해 봅시다 -
-
먼저 → 주어진 두 숫자 사이에 난수를 생성하는 함수를 작성합니다.
-
두 번째 → 임의의 색상 생성을 위해 16진수 스케일을 사용하는 대신 0~15개의 10진수 스케일에 16진수를 매핑하고 대신 사용합니다.
-
마지막으로 → 주어진 색상 문자열을 반복하고 임의의 색상을 생성합니다.
예시
const randomBetween = (a, b) => {
const max = Math.max(a, b);
const min = Math.min(a, b);
return Math.floor(Math.random() * (max - min) + min);
};
const randomColor = (firstColor, secondColor) => {
first = firstColor.toUpperCase().substring(1, secondColor.length);
second = secondColor.toUpperCase().substring(1, firstColor.length);
const scale = '0123456789ABCDEF';
let color = '#';
for(let i = 0; i < first.length && i < second.length; i++ ){
const random = randomBetween(scale.indexOf(first[i]),
scale.indexOf(second[i]));
color += scale[random];
};
return color;
};
console.log(randomColor('#34324a', '#42342c'));
console.log(randomColor('#f43250', '#12342c'));
console.log(randomColor('#34324a', '#47942c'));
console.log(randomColor('#ffffff', '#000000')); 다음은 콘솔에서 가능한 출력입니다 -
참고 − 출력이 매번 무작위로 나오기 때문에 이것은 가능한 많은 출력 중 하나일 뿐입니다.
출력
#33332A #C23328 #36822B #35102A