Skip to content

Instantly share code, notes, and snippets.

@Prinzhorn
Forked from 140bytes/LICENSE.txt
Created May 7, 2012 15:55
Show Gist options
  • Save Prinzhorn/2628611 to your computer and use it in GitHub Desktop.
Save Prinzhorn/2628611 to your computer and use it in GitHub Desktop.
compress hex color string

compress hex color strings

In hex you use three or six digits to define a color. By replacing all six-digit colors with the closest color which can be expressed with three digits, we save 3 bytes each! Hooray!

http://www.w3.org/TR/CSS2/syndata.html#value-def-color

The three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating digits, not by adding zeros.

Examples:

'00ff00' -> '0f0'

'34cf9d' -> '3c9'

function a(b, c) {
return ++c ?
(("0x" + b) / 17 + .5 | 0).toString(16) :
b.replace(/../g, a)
}
function a(b,c){return++c?(("0x"+b)/17+.5|0).toString(16):b.replace(/../g,a)}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2012 Alexander Prinzhorn (@Prinzhorn) https://github.com/Prinzhorn
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "hexGolfer",
"description": "Compress hex color strings by using three instead of six digits.",
"keywords": [
"color",
"hex",
"compress"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div style="background:#34cf9d;">Original value: #<b>34cf9d</b></div>
<div style="background:#3c9;">Expected value: #<b>3c9</b></div>
<div>Actual value: #<b id="ret"></b></div>
<script>
// write a small example that shows off the API for your example
// and tests it in one fell swoop.
var myFunction = function a(b,c){return++c?(("0x"+b)/17+.5|0).toString(16):b.replace(/../g,a)}
var ret = document.getElementById( "ret" );
var color = myFunction('34cf9d');
ret.innerHTML = color;
ret.parentNode.style.background = '#' + color;
</script>
@yckart
Copy link

yckart commented Aug 25, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment