UNPKG

@youtwitface/ntcjs

Version:

A Node CommonJS compatible wrapper for the Name That Color library (ntc js) - http://chir.ag/projects/ntc/

77 lines (74 loc) 3.1 kB
"use strict"; /* +-----------------------------------------------------------------+ | Created by Chirag Mehta - http://chir.ag/projects/ntc | |-----------------------------------------------------------------| | ntc js (Name that Color JavaScript) | +-----------------------------------------------------------------+ All the functions, code, lists etc. have been written specifically for the Name that Color JavaScript by Chirag Mehta unless otherwise specified. This script is released under the: Creative Commons License: Attribution 2.5 http://creativecommons.org/licenses/by/2.5/ */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const utils = __importStar(require("./utils")); const names_1 = __importDefault(require("./names")); const getColorName = (color) => { color = color.toUpperCase(); if (color.length < 3 || color.length > 7) { return ['#000000', `Invalid Color: ${color}`, false]; } if (color.length % 3 == 0) { color = `#${color}`; } if (color.length == 4) { color = `#${color[1].repeat(2)}${color[2].repeat(2)}${color[3].repeat(2)}`; } const [r, g, b] = utils.rgb(color); const [h, s, l] = utils.hsl(color); let cl = -1; let df = -1; for (let i = 0; i < names_1.default.length; i++) { if (color === names_1.default[i][0]) { return [names_1.default[i][0], names_1.default[i][1], true]; } const ndf1 = Math.pow(r - names_1.default[i][2], 2) + Math.pow(g - names_1.default[i][3], 2) + Math.pow(b - names_1.default[i][4], 2); const ndf2 = Math.pow(h - names_1.default[i][5], 2) + Math.pow(s - names_1.default[i][6], 2) + Math.pow(l - names_1.default[i][7], 2); const ndf = ndf1 + ndf2 * 2; if (df < 0 || df > ndf) { df = ndf; cl = i; } } return cl < 0 ? ['#000000', `Invalid Color: ${color}`, false] : [names_1.default[cl][0], names_1.default[cl][1], false]; }; exports.default = getColorName;