# Edit in JSFiddle

```// 3色カラーパレット
const palettes = ['DF0413', '059543', '007DC6'];
const samples = ['ff8c69', '000080', '144270', '8c0031', '8cb33e'];

function convertToRGB(hex) {
const match = hex.match(/[0-9a-f]{2}/gi);
return {
r: parseInt(match[0], 16),
g: parseInt(match[1], 16),
b: parseInt(match[2], 16)
}
}

function calcDelta(t, p) {
// https://en.wikipedia.org/wiki/Relative_luminance
// 輝度の重み付けはCIEの資料確認
return Math.pow(((p.r - t.r) * 0.3), 2 ) +
Math.pow( ((p.g - t.g) * 0.59), 2 ) +
Math.pow( ((p.b - t.b) * 0.11), 2 );
}

function chooseColor(palettes, hex) {
const rgb = convertToRGB(hex);

let color;
let d = Number.MAX_SAFE_INTEGER;
palettes.forEach(phex => {
const p = convertToRGB(phex);
const _d = calcDelta(rgb, p);
console.log(_d);
if (_d < d) {
color = phex;
d = _d;
}
});

return color;
}

palettes.forEach(hex => {
const span = document.createElement('span');
span.style.backgroundColor = `#\${hex}`;
document.getElementById('palettes').appendChild(span);
})

samples.forEach(hex => {
const span = document.createElement('span');
span.style.backgroundColor = `#\${hex}`;
document.getElementById('samples').appendChild(span);
})

samples.forEach(hex => {
const color = chooseColor(palettes, hex);
const span = document.createElement('span');
span.style.backgroundColor = `#\${color}`;
document.getElementById('chosen').appendChild(span);
})

```