Skip to content

Instantly share code, notes, and snippets.

@stevereich
Created July 27, 2015 05:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevereich/650a27086b139dda6df1 to your computer and use it in GitHub Desktop.
Save stevereich/650a27086b139dda6df1 to your computer and use it in GitHub Desktop.
This Coldfusion function takes an array of hex colors and sorts them from light to dark.
<cfscript>
private Array function sortHexColors(required Array colorArray) {
var valArray = [];
var sortArray = [];
for(var i=1;i<=arraylen(arguments.colorArray);i++) {
var color = replacenocase(arguments.colorArray[i], '##', '', 'ALL');
if(len(color) == 6) {
var strRed = mid(color, 1, 2);
var strGreen = mid(color, 3, 2);
var strBlue = mid(color, 5, 2);
// this formula comes from https://en.wikipedia.org/wiki/HSL_and_HSV
var retVal = (0.21 * inputbaseN(strRed, 16)) + (0.72 * inputbaseN(strGreen, 16)) + (0.07 * inputbaseN(strBlue, 16));
var tempObj = {};
tempObj['###color#'] = retVal;
arrayappend(sortArray,tempObj);
arrayappend(valArray,retVal);
}
}
arraysort(valArray,'numeric','desc');
var returnArray = [];
for(var ii=1;ii<=arraylen(valArray);ii++){
for(var j=1;j<=arraylen(sortArray);j++){
for(key in sortArray[j]){
if(sortArray[j][key] == valArray[ii]){
arrayappend(returnArray,key);
continue;
}
}
}
}
return returnArray;
}
variables.unsortedColors = ['##2A2A2A','##777777','##373737','##b7b7b7','##333333','##505050','##3C3C3C','##d0d0d0','##7f7f7f','##323232'];
variables.sortedColors = sortHexColors(variables.unsortedColors);
writeoutput("<div style='padding:0;margin:0;width:"&arraylen(variables.unsortedColors)*100&"px;height:100px'>");
for(i=1;i<=arraylen(variables.unsortedColors);i++){
writeoutput("<div class='colorBox' style='padding:0;margin:0;height:100px;width:100px;display:inline-block;position:relative;background-color:#variables.unsortedColors[i]#'></div>");
};
for(ii=1;ii<=arraylen(variables.sortedColors);ii++){
writeoutput("<div class='colorBox' style='padding:0;margin:0;height:100px;width:100px;display:inline-block;position:relative;background-color:#variables.sortedColors[ii]#'></div>");
};
writeoutput("</div>");
</cfscript>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment