We are required to write a JavaScript function that takes in hex color as one and only input.
Our function should then find the complementary color for the color taken in as input.
Here are some input and output pairs −
getComplementaryColor('#142814') = '#ebd7eb'; getComplementaryColor('#ffffff') = '#000000'; getComplementaryColor('#3399ff') = '#cc6600';
Example
The code for this will be −
const str1 = '#142814'; const str2 = '#ffffff'; const str3 = '#3399ff'; const getComplementaryColor = (color = '') => { const colorPart = color.slice(1); const ind = parseInt(colorPart, 16); let iter = ((1 << 4 * colorPart.length) - 1 - ind).toString(16); while (iter.length < colorPart.length) { iter = '0' + iter; }; return '#' + iter; }; console.log(getComplementaryColor(str1)); console.log(getComplementaryColor(str2)); console.log(getComplementaryColor(str3));
Output
And the output in the console will be −
#ebd7eb #000000 #cc6600