A simple function is to calculate whether the total of each RGB channel reaches a certain threshold, with different weights given to each channel. For an example, see the YIQ contrast function used by Bootstrap v4 [0].
WCAG defines their own algorithm for calculating the contrast between two colours to ensure good accessibility [1][2]. Bootstrap v5 uses this [3].
[0] https://github.com/twbs/bootstrap/blob/v4.6.1/scss/_function...
[1] https://www.w3.org/WAI/GL/wiki/Relative_luminance
[2] https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
[3] https://github.com/twbs/bootstrap/blob/v5.1.3/scss/_function...