Skip to content

Commit

Permalink
Version 1.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
aminekun90 committed Jul 24, 2024
0 parents commit 91522e3
Show file tree
Hide file tree
Showing 13 changed files with 454 additions and 0 deletions.
125 changes: 125 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

# Other
dist
mdns-listener.plist
.vs
.vscode
package-lock.json
.DS_STORE
build
5 changes: 5 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"printWidth": 120,
"trailingComma": "all",
"singleQuote": false
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 aminekun90

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.
43 changes: 43 additions & 0 deletions README
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# ColorUtils Library

A TypeScript library for working with colors, providing functionality to find distinct colors from a list based on a similarity threshold.

## Installation

Install the library using npm:

```sh
npm install color-utils
```
## Usage
### Importing the Library

You can import the ColorUtils class from the library as follows:

```typescript
import { ColorUtils } from '@color-utils/ColorUtils';
```

### Methods
`getDistinctColors`

Finds a specified number of distinct colors from a list based on a similarity threshold.

Parameters:

`hexColors` (string[]): The list of hex color strings (e.g., `['#ff0000', '#00ff00']`).
`numColors` (number): The number of distinct colors to retrieve.
`threshold` (number): The threshold for color similarity (lower values mean more similar).
Returns:

(string[]): The list of distinct hex color strings.
Example:

```typescript
const colors = ['#ff0000', '#00ff00', '#0000ff', '#ff00ff'];
const numColorsToRetrieve = 2;
const threshold = 20;

const distinctColors = ColorUtils.getDistinctColors(colors, numColorsToRetrieve, threshold);
console.log(distinctColors); // Output: ['#ff0000', '#00ff00']
```
9 changes: 9 additions & 0 deletions config/fileTransformer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// source: https://jestjs.io/docs/code-transformation#examples

const path = require('path');

module.exports = {
process(src, filename, config, options) {
return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';';
},
};
19 changes: 19 additions & 0 deletions jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module.exports = {
roots: ['<rootDir>/src'],
testMatch: ['**/__tests__/**/*.+(ts|tsx|js)', '**/?(*.)+(spec|test).+(ts|tsx|js)'],
transform: {
'^.+\\.(ts|tsx)$': 'ts-jest',
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'./config/fileTransformer.js',
},
globals: {
'ts-jest': {
tsconfig: 'tsconfig.json',
},
},
moduleNameMapper: {
'@color-utils/(.*)': '<rootDir>/src/$1',
},
moduleDirectories: ['<rootDir>/node_modules', '<rootDir>'],
};

35 changes: 35 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "color-utils",
"version": "1.0.0",
"description": "Color utils library",
"main": "dist/ColorUtils.js",
"types": "dist/ColorUtils.d.ts",
"scripts": {
"start": "ts-node -r tsconfig-paths/register src/index.ts",
"test": "jest --no-cache --runInBand",
"test:cov": "jest --coverage --no-cache --runInBand",
"build": "tsc"
},
"author": "aminekun90",
"license": "MIT",
"dependencies": {
"@types/node": "^20.14.12",
"chroma-js": "^2.4.2",
"color-diff": "^1.4.0",
"ts-node": "^10.9.2",
"tslog": "^4.9.3",
"typescript": "^5.5.4"
},
"devDependencies": {
"@types/chroma-js": "^2.4.4",
"@types/color-diff": "^1.2.5",
"@types/jest": "^29.5.12",
"jest": "^29.7.0",
"prettier": "^3.1.0",
"ts-jest": "^29.2.3",
"ts-loader": "^9.4.2",
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.0.4"
}
}
51 changes: 51 additions & 0 deletions src/ColorUtils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ColorUtils = void 0;
const chroma_js_1 = __importDefault(require("chroma-js"));
const color_diff_1 = require("color-diff");
class ColorUtils {
/**
* Convert a hex color to an RGB object.
* @param {string} hex - The hex color string (e.g., '#ff0000').
* @returns {RGBColor} The RGB color object.
*/
static hexToRgb(hex) {
const rgb = (0, chroma_js_1.default)(hex).rgb();
return { R: rgb[0], G: rgb[1], B: rgb[2] };
}
/**
* Convert a hex color to a LAB object.
* @param {string} hex - The hex color string (e.g., '#ff0000').
* @returns {LabColor} The LAB color object.
*/
static hexToLab(hex) {
const [L, a, b] = (0, chroma_js_1.default)(hex).lab();
return { L, a, b };
}
/**
* Get a specified number of distinct colors from a list based on a similarity threshold.
* @param {string[]} hexColors - The list of hex color strings.
* @param {number} numColors - The number of distinct colors to retrieve.
* @param {number} threshold - The threshold for color similarity (lower values mean more similar).
* @returns {string[]} The list of distinct hex color strings.
*/
static getDistinctColors(hexColors, numColors, threshold) {
const distinctColors = [];
for (let i = 0; i < hexColors.length && distinctColors.length < numColors; i++) {
const hex = hexColors[i];
const labColor = this.hexToLab(hex);
const isDistinct = distinctColors.every(distinctHex => {
const distinctLab = this.hexToLab(distinctHex);
return (0, color_diff_1.diff)(labColor, distinctLab) > threshold;
});
if (isDistinct) {
distinctColors.push(hex);
}
}
return distinctColors;
}
}
exports.ColorUtils = ColorUtils;
58 changes: 58 additions & 0 deletions src/ColorUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import chroma from "chroma-js";
import { diff, LabColor, RGBColor } from "color-diff";
import { LogPerf } from "@color-utils/decorators/LogPerf";

export class ColorUtils {

/**
* Convert a hex color to an RGB object.
* @param {string} hex - The hex color string (e.g., "#ff0000").
* @returns {RGBColor} The RGB color object.
*/
public static hexToRgb(hex: string): RGBColor {
const rgb = chroma(hex).rgb();
return { R: rgb[0], G: rgb[1], B: rgb[2] };
}

/**
* Convert a hex color to a LAB object.
* @param {string} hex - The hex color string (e.g., "#ff0000").
* @returns {LabColor} The LAB color object.
*/
private static hexToLab(hex: string): LabColor {
const [L, a, b] = chroma(hex).lab();
return { L, a, b };
}

/**
* Get a specified number of distinct colors from a list based on a similarity threshold.
* @param {string[]} hexColors - The list of hex color strings.
* @param {number} numColors - The number of distinct colors to retrieve.
* @param {number} threshold - The threshold for color similarity (lower values mean more similar).
* @returns {string[]} The list of distinct hex color strings.
*/
@LogPerf("info")
public static getDistinctColors(hexColors: string[], numColors: number, threshold: number): string[] {
if (numColors <= 0) return [];

const distinctColors: string[] = [];
const labColors = hexColors.map(hex => this.hexToLab(hex));

outerLoop: for (let i = 0; i < labColors.length; i++) {
const labColor = labColors[i];
for (let j = 0; j < distinctColors.length; j++) {
const distinctLab = this.hexToLab(distinctColors[j]);
if (diff(labColor, distinctLab) <= threshold) {
continue outerLoop;
}
}
if (distinctColors.length < numColors) {
distinctColors.push(hexColors[i]);
} else {
break;
}
}

return distinctColors;
}
}
Loading

0 comments on commit 91522e3

Please sign in to comment.