Skip to content

Instantly share code, notes, and snippets.

@saintsGrad15
Created April 9, 2019 16:13
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 saintsGrad15/e6ed2418197d6f9834f69818f1db3a30 to your computer and use it in GitHub Desktop.
Save saintsGrad15/e6ed2418197d6f9834f69818f1db3a30 to your computer and use it in GitHub Desktop.
A class that will cycle through a range of colors according to an internal map of "items" to "hsl" color values.
class ColorCycler
{
/**
* A class that will return a CSS-valid "hsl()" string, assigned to distinct items.
*
* An internal mapping of "items" (any valid Object key) to "hsl()" strings.
* If a color is requested for an existing item, the existing color is returned.
* If a color is requested for a non-existing item, a new color is generated, stored for future use and returned.
*
* When a new color is generated the "hue" value is rotated (0 - 360).
* Each time "hue" passed 360 and is wrapped back to 0 the "saturation" value is rotated as well (0% - 100%).
*
* At the time of the class's design:
* The hue range was 0 - 360 with a step of 20 (18 values).
* The saturation range was 100% - 40% with a step of -30 (3 values).
*
* This produces 54 possible distinct hue and saturation combinations.
*/
constructor()
{
this.initColorCycler();
this.toggle = true;
}
initColorCycler()
{
/**
* Set the class's values back to their originals.
*
* :return: None
*/
this.hue = 40;
this.saturation = 100;
this.permIdRecord = {};
}
getItemColor(item)
{
/**
* Produce a color for the value of 'item.'
*
* If 'item' has already been stored, return its color
* otherwise, store a new color for the value of 'item' and return it.
*
* :param: item (any value Object key) A value for which to return a unique color.
*
* :return: A color for the value of 'item.'
*/
if ( !(item in this.permIdRecord) )
{
if (this.toggle)
{
this.permIdRecord[item] = "#e8e8e8";
}
else
{
this.permIdRecord[item] = "white";
}
this.toggle = !this.toggle;
}
// if ( !(item in this.permIdRecord) )
// {
// this.permIdRecord[item] = `hsl(${this._getNextHue()}, ${this._getSaturation()}%, 93%)`;
// }
return this.permIdRecord[item];
}
_getNextHue()
{
/**
* Get a new "hue" value, rotating clockwise around 360 degrees by a step value.
*
* :return: 'this.hue' Rotated clockwise by a step value.
*/
this.hue += 40;
if (this.hue > 360)
{
this.hue -= 360;
this.saturation -= 30;
}
return this.hue;
}
_getSaturation()
{
/**
* Return 'this.saturation', kept within the bounds of 40 - 100.
*
* :return: 'this.saturation', kept within the bounds of 40 - 100.
*/
if (this.saturation < 40)
{
this.saturation = 100;
}
return this.saturation;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment