UNPKG

js-utl

Version:

A collection of JS utility functions to be used across several applications or libraries.

68 lines (62 loc) 2.28 kB
/* * Copyright (c) 2022 Anton Bagdatyev (Tonix) * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ import { hashString } from "./hash"; /** * Color-related utility functions. */ /** * Gets a color's luminance. * * @param {number} color Color int value (RGB). * @return {number} An int greater than 160 if the color is considered dark and less than or * equal to 160 if the color is considered light. */ export function getLuminance(color) { const c = parseInt(color, 16); const r = (c & 0xff0000) >> 16; const g = (c & 0x00ff00) >> 8; const b = c & 0x0000ff; return 0.299 * r + 0.587 * g + 0.114 * b; } /** * Converts an integer to an RGB hex (hexadecimal) string. * * @param {number} i An integer. * @return {string} An RGB hex string (uppercase). */ export function intToRGBHexString(i) { const c = (i & 0x00ffffff).toString(16).toUpperCase(); return "00000".substring(0, 6 - c.length) + c; } /** * Converts a string to an RGB hex (hexadecimal) string representing a color. * * @param {string} str The string. * @return {string} The color as an RGB hex string (uppercase). */ export const colorFromString = str => { const hash = hashString(str); return intToRGBHexString(hash); };