***** 배열을 반환한다***** 는 것이 중요함!
휠게임을 만들면서 색상의 반복 선택을 방지하고자 만든 함수
const assignSegmentColors = (numItems, availableColors) => {
let lastColorIndex = -1;
return Array.from({ length: numItems }, () => {
let colorIndex;
do {
colorIndex = Math.floor(Math.random() * availableColors.length);
} while (colorIndex === lastColorIndex);
lastColorIndex = colorIndex;
return availableColors[colorIndex];
});
};
여기서 핵심은 Array.from()에 두개의 arguments를 넣었습니다. 하나는 배열의 길이를 numItems 만큼 만드는데, 콜백함수를 이용하는 것입니다. 콜백함수는 새로 선택되는 칼라가 바로 앞에 선택된 색상이랑 같으면, 다시 do 문으로가서 새로운 색상이 될때까지 돌수도 있습니다. 위 예제를 단순화 해서 아래 코드로 이해를 돕습니다.
다음은 MDN 에서 Array.from() 사용 예제입니다.
console.log(Array.from('foo'));
// Array ["f", "o", "o"]
console.log(Array.from([1, 2, 3], (x) => x + x));
// Array [2, 4, 6]
console.log(Array.from({length: 5}, (v, i) => i));
// (5) [0, 1, 2, 3, 4]
let product = {
name: 'T-Shirt LD02',
description: 'Lorem ipsum dolor ',
image: 'image.png',
price: '100 ~ 200',
children: [
{color: '#bfb1a4', size: 'M', price: 100},
{color: '#bfb1a4', size: 'L', price: 120},
{color: '#bfb1a4', size: 'XL', price: 170},
{color: '#9c2f46', size: 'M', price: 140},
{color: '#9c2f46', size: 'L', price: 120},
{color: '#9c2f46', size: 'XL', price: 150},
]
}
let colors = (product.children).map(product => product.color);
colors = Array.from(new Set(colors));
console.log( colors ) // [ '#bfb1a4', '#9c2f46' ]
let sizes = (product.children).map(product => product.size);
sizes = Array.from(new Set(sizes));
console.log( sizes ) // [ 'M', 'L', 'XL' ]
['#bfb1a4', '#9c2f46']
CDN 과 module (0) | 2024.05.03 |
---|---|
VectorSource, VectorLayer (0) | 2024.05.03 |
UUID (0) | 2024.04.26 |
window.location.search (0) | 2024.04.25 |
URLSearchParams, qs - 쿼리 스트링을 다루는 API (0) | 2024.04.25 |