SHARE
TWEET

Untitled

a guest Aug 17th, 2019 68 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  
  3. Write a function that takes 2 colors as arguments and returns the average color.
  4. - The parameters will be two 6-digit hexadecimal strings. This does not need to be validated.
  5. - The return value should be a 6-digit hexadecimal string.
  6. - The hexadecimal strings represent colors in RGB, much like in CSS.
  7. - The average color is to be determined by taking the arithmetic mean for each component: red, green and blue.
  8.  
  9. */
  10.  
  11. function get_components(color) {
  12.     const r_hex = color.substr(0, 2);
  13.     const g_hex = color.substr(2, 2);
  14.     const b_hex = color.substr(4, 2);
  15.     return {
  16.         r: parseInt(r_hex, 16),
  17.         g: parseInt(g_hex, 16),
  18.         b: parseInt(b_hex, 16),
  19.     }
  20. }
  21.  
  22. function to_hexstring(x) {
  23.     let result = x.toString(16);
  24.     if (x < 16) {
  25.         result = '0' + result;
  26.     }
  27.     return result;
  28. }
  29.  
  30. function get_blend_color(color1, color2) {
  31.     const color1_components = get_components(color1);
  32.     const color2_components = get_components(color2);
  33.     const r_avg = Math.round((color1_components.r + color2_components.r) / 2);
  34.     const g_avg = Math.round((color1_components.g + color2_components.g) / 2);
  35.     const b_avg = Math.round((color1_components.b + color2_components.b) / 2);
  36.     const color3 = [r_avg, g_avg, b_avg].map(to_hexstring).join('');
  37.     return color3;
  38. }
  39.  
  40. console.assert(get_blend_color('ffffff', '000000') == '808080');
  41. console.assert(get_blend_color('000000', 'ffffff') == '808080');
  42. console.assert(get_blend_color('000000', '000000') == '000000');
  43. console.assert(get_blend_color('ffffff', 'ffffff') == 'ffffff');
  44. console.assert(get_blend_color('444444', 'afafaf') == '7a7a7a');
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top