One problem which I encounter time and time again when creating a webpage or applications is matching text color with a changing background color. When creating a GUI you usually create a lot of white boxes with a black text on it, just to get sizes and stuff matching. Then later a designer or customer decides on a theme which affects how that box looks. Most of the time the background and text colors are hand-selected so they match well enough, but from time to time you have to create a box which can change background color on demand, and then you have to have the text color matching to make the box readable. I have done too many slightly different solutions to this problem, so I thought I would write something down here. Since most of the time, text colors are off-white and off-black, the formula should be tweakable to match any given hue.
Solution 1
# From https://stackoverflow.com/a/3943023
# 186 can be tweaked down to 150
(red*0.299 + green*0.587 + blue*0.114) > 186 ? BLACK : WHITE;